├── .clang-format ├── .gitattributes ├── .github └── workflows │ ├── cpp.yml │ ├── labels.yml │ ├── links.yml │ └── typos.yml ├── .gitignore ├── .typos.toml ├── .vscode ├── extensions.json ├── launch.json └── settings.json ├── CODE_OF_CONDUCT.md ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── lychee.toml ├── pixi.lock ├── pixi.toml ├── rerun_bridge ├── CMakeLists.txt ├── include │ └── rerun_bridge │ │ └── rerun_ros_interface.hpp ├── launch │ ├── carla_example.launch │ ├── carla_example_params.yaml │ ├── go2_example.launch │ └── go2_example_params.yaml ├── package.xml └── src │ └── rerun_bridge │ ├── collection_adapters.hpp │ ├── rerun_ros_interface.cpp │ ├── visualizer_node.cpp │ └── visualizer_node.hpp └── scripts └── template_update.py /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | 3 | # Make it slightly more similar to Rust. 4 | # Based loosely on https://gist.github.com/YodaEmbedding/c2c77dc693d11f3734d78489f9a6eea4 5 | AccessModifierOffset: -2 6 | AlignAfterOpenBracket: BlockIndent 7 | AllowAllArgumentsOnNextLine: false 8 | AllowShortBlocksOnASingleLine: false 9 | AllowShortCaseLabelsOnASingleLine: false 10 | AllowShortFunctionsOnASingleLine: Empty 11 | AllowShortIfStatementsOnASingleLine: Never 12 | AlwaysBreakAfterReturnType: None 13 | AlwaysBreakBeforeMultilineStrings: true 14 | BinPackArguments: false 15 | BreakStringLiterals: false 16 | ColumnLimit: 100 17 | ContinuationIndentWidth: 4 18 | DerivePointerAlignment: false 19 | EmptyLineBeforeAccessModifier: LogicalBlock 20 | IndentWidth: 4 21 | IndentWrappedFunctionNames: true 22 | InsertBraces: true 23 | InsertTrailingCommas: Wrapped 24 | MaxEmptyLinesToKeep: 1 25 | NamespaceIndentation: All 26 | PointerAlignment: Left 27 | ReflowComments: false 28 | SeparateDefinitionBlocks: Always 29 | SpacesBeforeTrailingComments: 1 30 | 31 | # Don't change include blocks, we want to control this manually. 32 | # Sorting headers however is allowed as all our headers should be standalone. 33 | IncludeBlocks: Preserve 34 | SortIncludes: CaseInsensitive 35 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # GitHub syntax highlighting 2 | pixi.lock linguist-language=YAML 3 | 4 | -------------------------------------------------------------------------------- /.github/workflows/cpp.yml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/rerun-io/rerun_template 2 | on: [push, pull_request] 3 | 4 | name: C++ 5 | 6 | jobs: 7 | cpp-check: 8 | name: C++ 9 | runs-on: ubuntu-22.04 10 | steps: 11 | - uses: actions/checkout@v4 12 | 13 | - uses: prefix-dev/setup-pixi@v0.8.1 14 | with: 15 | pixi-version: v0.26.1 16 | cache: true 17 | 18 | - run: pixi run cpp-fmt-check 19 | 20 | - run: pixi run build 21 | -------------------------------------------------------------------------------- /.github/workflows/labels.yml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/rerun-io/rerun_template 2 | 3 | # https://github.com/marketplace/actions/require-labels 4 | # Check for existence of labels 5 | # See all our labels at https://github.com/rerun-io/rerun/issues/labels 6 | 7 | name: PR Labels 8 | 9 | on: 10 | pull_request: 11 | types: 12 | - opened 13 | - synchronize 14 | - reopened 15 | - labeled 16 | - unlabeled 17 | 18 | jobs: 19 | label: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Check for a "do-not-merge" label 23 | uses: mheap/github-action-required-labels@v3 24 | with: 25 | mode: exactly 26 | count: 0 27 | labels: "do-not-merge" 28 | -------------------------------------------------------------------------------- /.github/workflows/links.yml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/rerun-io/rerun_template 2 | on: [push, pull_request] 3 | 4 | name: Link checker 5 | 6 | jobs: 7 | link-checker: 8 | name: Check links 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | 13 | - name: Restore link checker cache 14 | uses: actions/cache@v3 15 | with: 16 | path: .lycheecache 17 | key: cache-lychee-${{ github.sha }} 18 | restore-keys: cache-lychee- 19 | 20 | # Check https://github.com/lycheeverse/lychee on how to run locally. 21 | - name: Link Checker 22 | id: lychee 23 | uses: lycheeverse/lychee-action@v1.9.0 24 | with: 25 | fail: true 26 | lycheeVersion: "0.14.3" 27 | # When given a directory, lychee checks only markdown, html and text files, everything else we have to glob in manually. 28 | args: | 29 | --base . --cache --max-cache-age 1d . "**/*.rs" "**/*.toml" "**/*.hpp" "**/*.cpp" "**/CMakeLists.txt" "**/*.py" "**/*.yml" 30 | -------------------------------------------------------------------------------- /.github/workflows/typos.yml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/rerun-io/rerun_template 2 | 3 | # https://github.com/crate-ci/typos 4 | # Add exceptions to `.typos.toml` 5 | # install and run locally: cargo install typos-cli && typos 6 | 7 | name: Spell Check 8 | on: [pull_request] 9 | 10 | jobs: 11 | run: 12 | name: Spell Check 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout Actions Repository 16 | uses: actions/checkout@v4 17 | 18 | - name: Check spelling of entire workspace 19 | uses: crate-ci/typos@master 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Mac stuff: 2 | .DS_Store 3 | 4 | # C++ build directory 5 | build 6 | 7 | # Rust compile target directories: 8 | target 9 | target_ra 10 | target_wasm 11 | 12 | # https://github.com/lycheeverse/lychee 13 | .lycheecache 14 | 15 | # Pixi environment 16 | .pixi 17 | 18 | # Python stuff: 19 | __pycache__ 20 | .mypy_cache 21 | .ruff_cache 22 | venv 23 | 24 | # LSP stuff: 25 | compile_commands.json 26 | 27 | # ROS stuff: 28 | humble_ws 29 | *.bag 30 | -------------------------------------------------------------------------------- /.typos.toml: -------------------------------------------------------------------------------- 1 | # https://github.com/crate-ci/typos 2 | # install: cargo install typos-cli 3 | # run: typos 4 | 5 | [default.extend-words] 6 | teh = "teh" # part of @teh-cmc 7 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "charliermarsh.ruff", 6 | "gaborv.flatbuffers", 7 | "github.vscode-github-actions", 8 | "josetr.cmake-language-support-vscode", 9 | "ms-python.mypy-type-checker", 10 | "ms-python.python", 11 | "ms-vscode.cmake-tools", 12 | "ms-vscode.cpptools-extension-pack", 13 | "ms-vsliveshare.vsliveshare", 14 | "polymeilex.wgsl", 15 | "rust-lang.rust-analyzer", 16 | "serayuzgur.crates", 17 | "streetsidesoftware.code-spell-checker", 18 | "tamasfe.even-better-toml", 19 | "vadimcn.vscode-lldb", 20 | "wayou.vscode-todo-highlight", 21 | "webfreak.debug", 22 | "xaver.clang-format", // C++ formatter 23 | "zxh404.vscode-proto3", 24 | "esbenp.prettier-vscode" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | // Python 8 | { 9 | "name": "Python Debugger: Current File", 10 | "type": "debugpy", 11 | "request": "launch", 12 | "program": "${file}", 13 | "console": "integratedTerminal" 14 | }, 15 | // Rust: 16 | { 17 | "name": "Debug 'PROJ_NAME'", 18 | "type": "lldb", 19 | "request": "launch", 20 | "cargo": { 21 | "args": [ 22 | "build" 23 | ], 24 | "filter": { 25 | "name": "PROJ_NAME", 26 | "kind": "bin" 27 | } 28 | }, 29 | "args": [], 30 | "cwd": "${workspaceFolder}", 31 | "env": { 32 | "RUST_LOG": "debug" 33 | } 34 | }, 35 | { 36 | "name": "Launch Rust tests", 37 | "type": "lldb", 38 | "request": "launch", 39 | "cargo": { 40 | "args": [ 41 | "test", 42 | "--no-run", 43 | "--lib", 44 | "--all-features" 45 | ], 46 | "filter": { 47 | "kind": "lib" 48 | } 49 | }, 50 | "cwd": "${workspaceFolder}", 51 | "env": { 52 | "RUST_LOG": "debug" 53 | } 54 | }, 55 | ] 56 | } 57 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.semanticTokenColorCustomizations": { 4 | "rules": { 5 | "*.unsafe:rust": "#eb5046" 6 | } 7 | }, 8 | "files.autoGuessEncoding": true, 9 | "files.insertFinalNewline": true, 10 | "files.trimTrailingWhitespace": true, 11 | // don't share a cargo lock with rust-analyzer. 12 | // see https://github.com/rerun-io/rerun/pull/519 for rationale 13 | "rust-analyzer.check.overrideCommand": [ 14 | "cargo", 15 | "cranky", 16 | "--target-dir=target_ra", 17 | "--workspace", 18 | "--message-format=json", 19 | "--all-targets", 20 | "--all-features" 21 | ], 22 | "rust-analyzer.cargo.buildScripts.overrideCommand": [ 23 | "cargo", 24 | "check", 25 | "--quiet", 26 | "--target-dir=target_ra", 27 | "--workspace", 28 | "--message-format=json", 29 | "--all-targets", 30 | "--all-features", 31 | ], 32 | // Our build scripts are generating code. 33 | // Having Rust Analyzer do this while doing other builds can lead to catastrophic failures. 34 | // INCLUDING attempts to publish a new release! 35 | "rust-analyzer.cargo.buildScripts.enable": false, 36 | "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools", // Use cmake-tools to grab configs. 37 | "C_Cpp.autoAddFileAssociations": false, 38 | "cmake.buildDirectory": "${workspaceRoot}/build/debug", 39 | "cmake.generator": "Ninja", // Use Ninja, just like we do in our just/pixi command. 40 | "rust-analyzer.showUnlinkedFileNotification": false, 41 | "ruff.format.args": [ 42 | "--config=pyproject.toml" 43 | ], 44 | "ruff.lint.args": [ 45 | "--config=pyproject.toml" 46 | ], 47 | "prettier.requireConfig": true, 48 | "prettier.configPath": ".prettierrc.toml", 49 | "[python]": { 50 | "editor.defaultFormatter": "charliermarsh.ruff" 51 | }, 52 | } 53 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | opensource@rerun.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 126 | [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 130 | [Mozilla CoC]: https://github.com/mozilla/diversity 131 | [FAQ]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024 Rerun Technologies AB 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C++ Example: ROS 2 Bridge 2 | 3 | This is an example that shows how to use Rerun's C++ API to log and visualize [ROS 2](https://docs.ros.org/en/humble/index.html) messages (for the ROS 1 version, see [here](https://github.com/rerun-io/cpp-example-ros-bridge)). 4 | 5 | It works by subscribing to all topics with supported types, converting the messages, and logging the data to Rerun. It further allows to remap topic names to specific entity paths, specify additional timeless transforms, and pinhole parameters via an external config file. See the [launch](https://github.com/rerun-io/cpp-example-ros2-bridge/tree/main/rerun_bridge/launch) directory for usage examples. 6 | 7 | | CARLA | Go2 | 8 | | --- | --- | 9 | | ![carla](https://github.com/rerun-io/cpp-example-ros2-bridge/assets/9785832/f4e91f4b-18b4-4890-b2cc-ff00880ca65c) | ![go2](https://github.com/rerun-io/cpp-example-ros2-bridge/assets/9785832/2856b5af-d02b-426b-8e23-2cf6f7c2bfd8) | 10 | 11 | This example is built for ROS 2. For more ROS examples, also check out the [ROS 2 example](https://www.rerun.io/docs/howto/ros2-nav-turtlebot), the [URDF data-loader](https://github.com/rerun-io/rerun-loader-python-example-urdf), and the [ROS 1 bridge](https://github.com/rerun-io/cpp-example-ros-bridge). 12 | 13 | > NOTE: Currently only some of the most common messages are supported (see https://github.com/rerun-io/cpp-example-ros2-bridge/issues/4 for an overview). However, extending to other messages should be straightforward. 14 | 15 | ## Compile and run using pixi 16 | The easiest way to get started is to install [pixi](https://prefix.dev/docs/pixi/overview). 17 | 18 | The pixi environment described in `pixi.toml` contains all required dependencies, including the example data, and the Rerun viewer. To run the [CARLA](https://carla.org/) example use 19 | ```shell 20 | pixi run carla_example 21 | ``` 22 | and to run the [Go2](https://www.unitree.com/go2/) example use 23 | ```shell 24 | pixi run go2_example 25 | ``` 26 | 27 | ## Compile and run using existing ROS environment 28 | If you have an existing ROS workspace and would like to add the Rerun node to it, clone this repository into the workspace's `src` directory and build the workspace. 29 | 30 | To manually run the CARLA example, first download the [CARLA bag](https://storage.googleapis.com/rerun-example-datasets/carla_ros2.zip) or [Go2 bag](https://storage.googleapis.com/rerun-example-datasets/go2_ros2.zip) and extract it to the `share` directory of the `rerun_bridge` package (typically located in `{workspace_dir}/install/rerun_bridge/share/rerun_bridge`). Then, run the corresponding launch file: 31 | ```shell 32 | ros2 launch rerun_bridge {carla,go2}_example.launch 33 | ``` 34 | 35 | ## Development 36 | Prior to opening a pull request, run `pixi run lint-typos && pixi run cpp-fmt` to check for typos and format the C++ code. 37 | 38 | You can update this repository with the latest changes from the [template](https://github.com/rerun-io/rerun_template/) by running: 39 | * `scripts/template_update.py update --languages cpp` 40 | 41 | ## Acknowledgements 42 | This code uses the [turbo colormap lookup table](https://gist.github.com/mikhailov-work/6a308c20e494d9e0ccc29036b28faa7a) by [Anton Mikhailov](https://github.com/mikhailov-work). 43 | -------------------------------------------------------------------------------- /lychee.toml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/rerun-io/rerun_template 2 | 3 | ################################################################################ 4 | # Config for the link checker lychee. 5 | # 6 | # Download & learn more at: 7 | # https://github.com/lycheeverse/lychee 8 | # 9 | # Example config: 10 | # https://github.com/lycheeverse/lychee/blob/master/lychee.example.toml 11 | # 12 | # Run `lychee . --dump` to list all found links that are being checked. 13 | # 14 | # Note that by default lychee will only check markdown and html files, 15 | # to check any other files you have to point to them explicitly, e.g.: 16 | # `lychee **/*.rs` 17 | # To make things worse, `exclude_path` is ignored for these globs, 18 | # so local runs with lots of gitignored files will be slow. 19 | # (https://github.com/lycheeverse/lychee/issues/1405) 20 | # 21 | # This unfortunately doesn't list anything for non-glob checks. 22 | ################################################################################ 23 | 24 | # Maximum number of concurrent link checks. 25 | # Workaround for "too many open files" error on MacOS, see https://github.com/lycheeverse/lychee/issues/1248 26 | max_concurrency = 32 27 | 28 | # Check links inside `` and `
` blocks as well as Markdown code blocks.
29 | include_verbatim = true
30 | 
31 | # Proceed for server connections considered insecure (invalid TLS).
32 | insecure = true
33 | 
34 | # Exclude these filesystem paths from getting checked.
35 | exclude_path = [
36 |   # Unfortunately lychee doesn't yet read .gitignore https://github.com/lycheeverse/lychee/issues/1331
37 |   # The following entries are there because of that:
38 |   ".git",
39 |   "__pycache__",
40 |   "_deps/",
41 |   ".pixi",
42 |   "build",
43 |   "target_ra",
44 |   "target_wasm",
45 |   "target",
46 |   "venv",
47 | ]
48 | 
49 | # Exclude URLs and mail addresses from checking (supports regex).
50 | exclude = [
51 |   # Skip speculative links
52 |   '.*?speculative-link',
53 | 
54 |   # Strings with replacements.
55 |   '/__VIEWER_VERSION__/', # Replacement variable __VIEWER_VERSION__.
56 |   '/\$',                  # Replacement variable $.
57 |   '/GIT_HASH/',           # Replacement variable GIT_HASH.
58 |   '\{\}',                 # Ignore links with string interpolation.
59 |   '\$relpath\^',          # Relative paths as used by rerun_cpp's doc header.
60 |   '%7B.+%7D',             # Ignore strings that look like ready to use links but contain a replacement strings. The URL escaping is for '{.+}' (this seems to be needed for html embedded urls since lychee assumes they use this encoding).
61 |   '%7B%7D',               # Ignore links with string interpolation, escaped variant.
62 | 
63 |   # Local links that require further setup.
64 |   'http://127.0.0.1',
65 |   'http://localhost',
66 |   'recording:/',      # rrd recording link.
67 |   'ws:/',
68 |   're_viewer.js',     # Build artifact that html is linking to.
69 | 
70 |   # Api endpoints.
71 |   'https://fonts.googleapis.com/', # Font API entrypoint, not a link.
72 |   'https://fonts.gstatic.com/',    # Font API entrypoint, not a link.
73 |   'https://tel.rerun.io/',         # Analytics endpoint.
74 | 
75 |   # Avoid rate limiting.
76 |   'https://crates.io/crates/.*',                  # Avoid crates.io rate-limiting
77 |   'https://github.com/rerun-io/rerun/commit/\.*', # Ignore links to our own commits (typically in changelog).
78 |   'https://github.com/rerun-io/rerun/pull/\.*',   # Ignore links to our own pull requests (typically in changelog).
79 | 
80 |   # Used in rerun_template repo until the user search-replaces `cpp-example-ros2-bridge`
81 |   'https://github.com/rerun-io/cpp-example-ros2-bridge',
82 | ]
83 | 


--------------------------------------------------------------------------------
/pixi.toml:
--------------------------------------------------------------------------------
  1 | # Pixi is a package management tool for developers.
  2 | # Before running a task, pixi ensures that all listed dependencies are installed first.echop
  3 | #
  4 | # Pixi is not required for rerun, but it is a convenient way to install the
  5 | # dependencies required for this example.
  6 | #
  7 | # https://prefix.dev/docs/pixi/overview
  8 | #
  9 | # Use `pixi task list` to list the available tasks,
 10 | # and `pixi run TASK` to run it (e.g. `pixi run example`).
 11 | 
 12 | [project]
 13 | name = "rerun_bridge2"
 14 | authors = ["rerun.io "]
 15 | channels = ["robostack-staging", "conda-forge"]
 16 | description = "rerun_bridge2"
 17 | homepage = "https://rerun.io"
 18 | license = "MIT OR Apache-2.0"
 19 | 
 20 | platforms = ["linux-64", "linux-aarch64", "osx-arm64", "osx-64", "win-64"]
 21 | readme = "README.md"
 22 | repository = "https://github.com/rerun-io/cpp-example-ros2-bridge"
 23 | version = "0.1.0"
 24 | 
 25 | 
 26 | [tasks]
 27 | # ------------------------------------------------------------------------------------------
 28 | # C++ stuff:
 29 | # Note: extra CLI argument after `pixi run TASK` are passed to the task cmd.
 30 | 
 31 | # Clean C++ build artifacts
 32 | clean = { cmd = "rm -rf build bin CMakeFiles/" }
 33 | print-env = { cmd = "echo $PATH" }
 34 | 
 35 | # Format C++ code
 36 | cpp-fmt = { cmd = "clang-format -i rerun_bridge/**/*.[hc]pp" }
 37 | 
 38 | # Check formatting of C++ code
 39 | cpp-fmt-check = { cmd = "clang-format --dry-run --Werror -i rerun_bridge/**/*.[hc]pp" }
 40 | 
 41 | # Check for typos
 42 | lint-typos = "typos"
 43 | 
 44 | # ------------------------------------------------------------------------------------------
 45 | # ROS2 stuff:
 46 | 
 47 | [tasks.ws]
 48 | cmd = "mkdir -p humble_ws/src && ln -sfn $(pwd)/rerun_bridge humble_ws/src/rerun_bridge"
 49 | cwd = "."
 50 | 
 51 | [tasks.build]
 52 | cmd = "colcon build --packages-select rerun_bridge --cmake-args -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=ON"
 53 | depends_on = ["ws"]
 54 | cwd = "humble_ws"
 55 | 
 56 | # Get mcap support from source since its not available in robostack channel
 57 | #
 58 | # We first check if the src directory already exists to avoid repeating the clone.
 59 | [tasks.rosbag2_storage_mcap]
 60 | cmd = """
 61 | (test -d src/rosbag2_storage_mcap || git clone https://github.com/ros-tooling/rosbag2_storage_mcap.git src/rosbag2_storage_mcap)
 62 | && colcon build --packages-select mcap_vendor rosbag2_storage_mcap_testdata rosbag2_storage_mcap --cmake-args -DCMAKE_BUILD_TYPE=Release
 63 | """
 64 | depends_on = ["ws"]
 65 | cwd = "humble_ws"
 66 | 
 67 | # ------------------------------------------------------------------------------------------
 68 | # CARLA example:
 69 | 
 70 | [tasks.carla_example_data]
 71 | cmd = "curl -L -C - -O https://storage.googleapis.com/rerun-example-datasets/carla_ros2.zip && unzip carla_ros2.zip"
 72 | cwd = "humble_ws/install/rerun_bridge/share/rerun_bridge"
 73 | outputs = ["humble_ws/install/rerun_bridge/share/rerun_bridge/carla_ros2"]
 74 | depends_on = ["build"]
 75 | 
 76 | [tasks.carla_example]
 77 | cmd = "bash -c 'source ./install/local_setup.bash && ros2 launch rerun_bridge carla_example.launch'"
 78 | depends_on = ["build", "rerun_viewer", "carla_example_data"]
 79 | cwd = "humble_ws"
 80 | 
 81 | # ------------------------------------------------------------------------------------------
 82 | # Go2 example:
 83 | 
 84 | [tasks.go2_example_data]
 85 | cmd = "curl -L -C - -O https://storage.googleapis.com/rerun-example-datasets/go2_ros2.zip && unzip go2_ros2.zip"
 86 | cwd = "humble_ws/install/rerun_bridge/share/rerun_bridge"
 87 | outputs = ["humble_ws/install/rerun_bridge/share/rerun_bridge/go2_ros2"]
 88 | depends_on = ["build"]
 89 | 
 90 | # Get the go2_ros2_sdk package
 91 | #
 92 | # We first check if the src directory already exists to avoid repeating the clone.
 93 | [tasks.go2_ros2_sdk]
 94 | cmd = """
 95 | (test -d src/go2_ros2_sdk || git clone --recurse-submodules https://github.com/abizovnuralem/go2_ros2_sdk.git src/go2_ros2_sdk)
 96 | && colcon build --packages-select go2_interfaces go2_robot_sdk --cmake-args -DCMAKE_BUILD_TYPE=Release
 97 | """
 98 | cwd = "humble_ws"
 99 | depends_on = ["ws"]
100 | 
101 | [tasks.go2_example]
102 | cmd = "bash -c 'source ./install/local_setup.bash && ros2 launch rerun_bridge go2_example.launch'"
103 | depends_on = [
104 |     "build",
105 |     "go2_example_data",
106 |     "go2_ros2_sdk",
107 |     "rosbag2_storage_mcap",
108 |     "rerun_viewer",
109 |     "rerun_urdf_loader",
110 | ]
111 | cwd = "humble_ws"
112 | 
113 | # Install Rerun and URDF loader manually via pip3, this should be replaced with direct pypi dependencies in the future.
114 | [tasks.rerun_viewer]
115 | cmd = "pip install rerun-sdk==0.18.2"
116 | 
117 | [tasks.rerun_urdf_loader]
118 | cmd = "pip install git+https://github.com/rerun-io/rerun-loader-python-example-urdf.git"
119 | 
120 | [dependencies]
121 | pip = ">=24.0,<25" # To install rerun-sdk and rerun-loader-python-example-urdf
122 | 
123 | # C++ build-tools:
124 | cmake = "3.27.6"
125 | clang-tools = ">=15,<16" # clang-format
126 | cxx-compiler = "1.6.0.*"
127 | ninja = "1.11.1"
128 | 
129 | # ROS 2 build-tools:
130 | colcon-core = ">=0.16.0,<0.17"
131 | colcon-common-extensions = ">=0.3.0,<0.4"
132 | 
133 | # Misc linting:
134 | typos = ">=1.20.9,<1.21"
135 | 
136 | # Rerun bridge dependencies:
137 | ros-humble-desktop = ">=0.10.0,<0.11"
138 | yaml-cpp = ">=0.8.0,<0.9"
139 | opencv = ">=4.9.0,<4.10"
140 | 
141 | # Additional dependencies for mcap support
142 | ros-humble-rosbag2-test-common = ">=0.15.9,<0.16"
143 | 
144 | [target.linux-64.dependencies]
145 | sysroot_linux-64 = ">=2.17,<3" # rustc 1.64+ requires glibc 2.17+, see https://blog.rust-lang.org/2022/08/01/Increasing-glibc-kernel-requirements.html
146 | 
147 | [target.linux-aarch64.dependencies]
148 | sysroot_linux-aarch64 = ">=2.17,<3" # rustc 1.64+ requires glibc 2.17+, see https://blog.rust-lang.org/2022/08/01/Increasing-glibc-kernel-requirements.html
149 | 


--------------------------------------------------------------------------------
/rerun_bridge/CMakeLists.txt:
--------------------------------------------------------------------------------
 1 | cmake_minimum_required(VERSION 3.5)
 2 | project(rerun_bridge)
 3 | 
 4 | if(NOT DEFINED CMAKE_CXX_STANDARD)
 5 |   set(CMAKE_CXX_STANDARD 17)
 6 | endif()
 7 | 
 8 | # Avoid warning about CMP0135
 9 | if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.24.0")
10 |   cmake_policy(SET CMP0135 NEW)
11 | endif()
12 | 
13 | find_package(ament_cmake REQUIRED)
14 | find_package(rclcpp REQUIRED)
15 | find_package(sensor_msgs REQUIRED)
16 | find_package(nav_msgs REQUIRED)
17 | find_package(geometry_msgs REQUIRED)
18 | find_package(cv_bridge REQUIRED)
19 | find_package(tf2_ros REQUIRED)
20 | find_package(tf2_msgs REQUIRED)
21 | find_package(OpenCV REQUIRED)
22 | find_package(yaml-cpp REQUIRED)
23 | 
24 | include(FetchContent)
25 | FetchContent_Declare(rerun_sdk URL https://github.com/rerun-io/rerun/releases/download/0.18.2/rerun_cpp_sdk.zip)
26 | FetchContent_MakeAvailable(rerun_sdk)
27 | 
28 | # setup targets (has to be done before ament_package call)
29 | add_library(${PROJECT_NAME} src/rerun_bridge/rerun_ros_interface.cpp)
30 | add_executable(visualizer src/rerun_bridge/visualizer_node.cpp)
31 | 
32 | # add system dependencies
33 | target_include_directories(${PROJECT_NAME} PUBLIC include)
34 | target_include_directories(visualizer PUBLIC include ${YAML_CPP_INCLUDE_DIRS})
35 | 
36 | target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} ${YAML_CPP_LIBRARIES} rerun_sdk)
37 | target_link_libraries(visualizer ${PROJECT_NAME} ${YAML_CPP_LIBRARIES} rerun_sdk)
38 | 
39 | # add ament dependencies
40 | ament_target_dependencies(${PROJECT_NAME} rclcpp sensor_msgs nav_msgs geometry_msgs cv_bridge tf2_ros tf2_msgs)
41 | ament_target_dependencies(visualizer rclcpp sensor_msgs nav_msgs geometry_msgs cv_bridge tf2_ros tf2_msgs)
42 | 
43 | ament_export_dependencies(rclcpp sensor_msgs nav_msgs geometry_msgs cv_bridge tf2_ros tf2_msgs)
44 | ament_export_include_directories(include)
45 | ament_export_libraries(${PROJECT_NAME})
46 | ament_package()
47 | 
48 | install(DIRECTORY launch DESTINATION share/${PROJECT_NAME})
49 | install(TARGETS visualizer DESTINATION lib/${PROJECT_NAME})
50 | 


--------------------------------------------------------------------------------
/rerun_bridge/include/rerun_bridge/rerun_ros_interface.hpp:
--------------------------------------------------------------------------------
 1 | #pragma once
 2 | 
 3 | #include 
 4 | #include 
 5 | 
 6 | #include 
 7 | #include 
 8 | #include 
 9 | #include 
10 | #include 
11 | #include 
12 | #include 
13 | #include 
14 | 
15 | #include 
16 | 
17 | void log_imu(
18 |     const rerun::RecordingStream& rec, const std::string& entity_path,
19 |     const sensor_msgs::msg::Imu::ConstSharedPtr& msg
20 | );
21 | 
22 | struct ImageOptions {
23 |     std::optional min_depth;
24 |     std::optional max_depth;
25 | };
26 | 
27 | void log_image(
28 |     const rerun::RecordingStream& rec, const std::string& entity_path,
29 |     const sensor_msgs::msg::Image::ConstSharedPtr& msg, const ImageOptions& options = ImageOptions{}
30 | );
31 | 
32 | void log_pose_stamped(
33 |     const rerun::RecordingStream& rec, const std::string& entity_path,
34 |     const geometry_msgs::msg::PoseStamped::ConstSharedPtr& msg
35 | );
36 | 
37 | void log_odometry(
38 |     const rerun::RecordingStream& rec, const std::string& entity_path,
39 |     const nav_msgs::msg::Odometry::ConstSharedPtr& msg
40 | );
41 | 
42 | void log_camera_info(
43 |     const rerun::RecordingStream& rec, const std::string& entity_path,
44 |     const sensor_msgs::msg::CameraInfo::ConstSharedPtr& msg
45 | );
46 | 
47 | void log_tf_message(
48 |     const rerun::RecordingStream& rec,
49 |     const std::map& tf_frame_to_entity_path,
50 |     const tf2_msgs::msg::TFMessage::ConstSharedPtr& msg
51 | );
52 | 
53 | void log_transform(
54 |     const rerun::RecordingStream& rec, const std::string& entity_path,
55 |     const geometry_msgs::msg::TransformStamped::ConstSharedPtr& msg
56 | );
57 | 
58 | struct PointCloud2Options {
59 |     std::optional colormap;
60 |     std::optional colormap_field;
61 |     std::optional colormap_min;
62 |     std::optional colormap_max;
63 | };
64 | 
65 | void log_point_cloud2(
66 |     const rerun::RecordingStream& rec, const std::string& entity_path,
67 |     const sensor_msgs::msg::PointCloud2::ConstSharedPtr& msg, const PointCloud2Options& options
68 | );
69 | 


--------------------------------------------------------------------------------
/rerun_bridge/launch/carla_example.launch:
--------------------------------------------------------------------------------
 1 | 
 2 |   
11 |   
12 | 
13 |   
14 |   
15 |     
16 |     
17 |   
18 | 
19 | 


--------------------------------------------------------------------------------
/rerun_bridge/launch/carla_example_params.yaml:
--------------------------------------------------------------------------------
 1 | extra_transform3ds: []
 2 | extra_pinholes: []
 3 | tf:
 4 |   update_rate: 0.0  # set to 0 to log raw tf data only (i.e., without interoplation)
 5 | 
 6 |   # We need to predefine the tf-tree currently to define the entity paths
 7 |   # See: https://github.com/rerun-io/rerun/issues/5242
 8 |   tree: 
 9 |     map:
10 |       ego_vehicle:
11 |         ego_vehicle/depth_front: null
12 |         ego_vehicle/dvs_front: null
13 |         ego_vehicle/gnss: null
14 |         ego_vehicle/imu: null
15 |         ego_vehicle/lidar: null
16 |         ego_vehicle/radar_front: null
17 |         ego_vehicle/rgb_front: null
18 |         ego_vehicle/rgb_left: null
19 |         ego_vehicle/rgb_right: null
20 |         ego_vehicle/rgb_view: null
21 |         ego_vehicle/semantic_lidar: null
22 |         ego_vehicle/semantic_segmentation_front: null
23 |         ego_vehicle/lane_invasion: null
24 | topic_options:
25 |   /carla/ego_vehicle/depth_front/image:
26 |     max_depth: 100.0
27 |   /carla/ego_vehicle/rgb_front/image: 
28 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_front
29 |   /carla/ego_vehicle/rgb_front/camera_info: 
30 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_front
31 |   /carla/ego_vehicle/rgb_left/image: 
32 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_left
33 |   /carla/ego_vehicle/rgb_left/camera_info: 
34 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_left
35 |   /carla/ego_vehicle/rgb_right/image: 
36 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_right
37 |   /carla/ego_vehicle/rgb_right/camera_info: 
38 |     entity_path: /map/ego_vehicle/ego_vehicle/rgb_right
39 | urdf:
40 |   file_path: ""
41 |   entity_path: "odom"
42 | 


--------------------------------------------------------------------------------
/rerun_bridge/launch/go2_example.launch:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 | 
 4 | 
 5 | 
 6 |     
 7 |     
 8 | 
 9 | 
10 | 


--------------------------------------------------------------------------------
/rerun_bridge/launch/go2_example_params.yaml:
--------------------------------------------------------------------------------
 1 | extra_transform3ds: []
 2 | extra_pinholes:
 3 |   - entity_path: /map/odom/base_link/Head_upper/front_camera/image
 4 |     height: 720
 5 |     width: 1280
 6 |     image_from_camera: [1200, 0, 640, 0, 1200, 360, 0, 0, 1]
 7 | tf:
 8 |   update_rate: 50.0  # set to 0 to log raw tf data only (i.e., without interoplation)
 9 | 
10 |   # We need to predefine the tf-tree currently to define the entity paths
11 |   # See: https://github.com/rerun-io/rerun/issues/5242
12 |   tree:
13 |     map:
14 |       odom:
15 |         base_link:
16 |           FL_hip:
17 |             FL_thigh:
18 |               FL_calf:
19 |                 FL_calflower:
20 |                   FL_calflower1: null
21 |                 FL_foot: null
22 |           FR_hip:
23 |             FR_thigh:
24 |               FR_calf:
25 |                 FR_calflower:
26 |                   FR_calflower1: null
27 |                 FR_foot: null
28 |           RL_hip:
29 |             RL_thigh:
30 |               RL_calf:
31 |                 RL_calflower:
32 |                   RL_calflower1: null
33 |                 RL_foot: null
34 |           RR_hip:
35 |             RR_thigh:
36 |               RR_calf:
37 |                 RR_calflower:
38 |                   RR_calflower1: null
39 |                 RR_foot: null
40 |           Head_upper:
41 |             front_camera: null
42 |             Head_lower: null
43 |           base_footprint: null
44 |           imu: null
45 |           radar: null
46 | topic_options:
47 |   /point_cloud2:
48 |     colormap: turbo
49 |     colormap_field: z
50 |     restamp: true
51 |   /go2_camera/color/image: 
52 |     entity_path: /map/odom/base_link/Head_upper/front_camera/image
53 | urdf:
54 |   file_path: "package://go2_robot_sdk/urdf/go2.urdf"
55 |   entity_path: "/"  # the root of this urdf is map
56 | 


--------------------------------------------------------------------------------
/rerun_bridge/package.xml:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 |   rerun_bridge
 4 |   0.1.0
 5 |   The rerun_bridge package
 6 |   rerun.io
 7 |   Apache-2.0
 8 |   ament_cmake
 9 | 
10 |   cv_bridge
11 |   geometry_msgs
12 |   nav_msgs
13 |   rclcpp
14 |   sensor_msgs
15 |   tf2_ros
16 |   tf2_msgs
17 |   yaml-cpp
18 | 
19 |   
20 |     ament_cmake
21 |   
22 | 
23 | 


--------------------------------------------------------------------------------
/rerun_bridge/src/rerun_bridge/collection_adapters.hpp:
--------------------------------------------------------------------------------
 1 | #pragma once
 2 | 
 3 | #include 
 4 | #include 
 5 | 
 6 | // Adapters so we can borrow an OpenCV image easily into Rerun images without copying:
 7 | template 
 8 | struct rerun::CollectionAdapter {
 9 |     /// Borrow for non-temporary.
10 |     Collection operator()(const cv::Mat& img) {
11 |         return Collection::borrow(
12 |             reinterpret_cast(img.data),
13 |             img.total() * img.channels()
14 |         );
15 |     }
16 | 
17 |     // Do a full copy for temporaries (otherwise the data might be deleted when the temporary is destroyed).
18 |     Collection operator()(cv::Mat&& img) {
19 |         std::vector img_vec(img.total() * img.channels());
20 |         img_vec.assign(img.data, img.data + img.total() * img.channels());
21 |         return Collection::take_ownership(std::move(img_vec));
22 |     }
23 | };
24 | 
25 | inline rerun::WidthHeight width_height(const cv::Mat& img) {
26 |     return rerun::WidthHeight(static_cast(img.cols), static_cast(img.rows));
27 | };
28 | 


--------------------------------------------------------------------------------
/rerun_bridge/src/rerun_bridge/rerun_ros_interface.cpp:
--------------------------------------------------------------------------------
  1 | #include "rerun_bridge/rerun_ros_interface.hpp"
  2 | #include "collection_adapters.hpp"
  3 | 
  4 | #include 
  5 | #include 
  6 | #include 
  7 | 
  8 | // Turbo colormap lookup table
  9 | // from: https://gist.github.com/mikhailov-work/6a308c20e494d9e0ccc29036b28faa7a
 10 | // Copyright 2019 Google LLC.
 11 | // SPDX-License-Identifier: Apache-2.0
 12 | //
 13 | // Author: Anton Mikhailov
 14 | constexpr float TurboBytes[256][3] = {
 15 |     {48, 18, 59},    {50, 21, 67},    {51, 24, 74},   {52, 27, 81},   {53, 30, 88},
 16 |     {54, 33, 95},    {55, 36, 102},   {56, 39, 109},  {57, 42, 115},  {58, 45, 121},
 17 |     {59, 47, 128},   {60, 50, 134},   {61, 53, 139},  {62, 56, 145},  {63, 59, 151},
 18 |     {63, 62, 156},   {64, 64, 162},   {65, 67, 167},  {65, 70, 172},  {66, 73, 177},
 19 |     {66, 75, 181},   {67, 78, 186},   {68, 81, 191},  {68, 84, 195},  {68, 86, 199},
 20 |     {69, 89, 203},   {69, 92, 207},   {69, 94, 211},  {70, 97, 214},  {70, 100, 218},
 21 |     {70, 102, 221},  {70, 105, 224},  {70, 107, 227}, {71, 110, 230}, {71, 113, 233},
 22 |     {71, 115, 235},  {71, 118, 238},  {71, 120, 240}, {71, 123, 242}, {70, 125, 244},
 23 |     {70, 128, 246},  {70, 130, 248},  {70, 133, 250}, {70, 135, 251}, {69, 138, 252},
 24 |     {69, 140, 253},  {68, 143, 254},  {67, 145, 254}, {66, 148, 255}, {65, 150, 255},
 25 |     {64, 153, 255},  {62, 155, 254},  {61, 158, 254}, {59, 160, 253}, {58, 163, 252},
 26 |     {56, 165, 251},  {55, 168, 250},  {53, 171, 248}, {51, 173, 247}, {49, 175, 245},
 27 |     {47, 178, 244},  {46, 180, 242},  {44, 183, 240}, {42, 185, 238}, {40, 188, 235},
 28 |     {39, 190, 233},  {37, 192, 231},  {35, 195, 228}, {34, 197, 226}, {32, 199, 223},
 29 |     {31, 201, 221},  {30, 203, 218},  {28, 205, 216}, {27, 208, 213}, {26, 210, 210},
 30 |     {26, 212, 208},  {25, 213, 205},  {24, 215, 202}, {24, 217, 200}, {24, 219, 197},
 31 |     {24, 221, 194},  {24, 222, 192},  {24, 224, 189}, {25, 226, 187}, {25, 227, 185},
 32 |     {26, 228, 182},  {28, 230, 180},  {29, 231, 178}, {31, 233, 175}, {32, 234, 172},
 33 |     {34, 235, 170},  {37, 236, 167},  {39, 238, 164}, {42, 239, 161}, {44, 240, 158},
 34 |     {47, 241, 155},  {50, 242, 152},  {53, 243, 148}, {56, 244, 145}, {60, 245, 142},
 35 |     {63, 246, 138},  {67, 247, 135},  {70, 248, 132}, {74, 248, 128}, {78, 249, 125},
 36 |     {82, 250, 122},  {85, 250, 118},  {89, 251, 115}, {93, 252, 111}, {97, 252, 108},
 37 |     {101, 253, 105}, {105, 253, 102}, {109, 254, 98}, {113, 254, 95}, {117, 254, 92},
 38 |     {121, 254, 89},  {125, 255, 86},  {128, 255, 83}, {132, 255, 81}, {136, 255, 78},
 39 |     {139, 255, 75},  {143, 255, 73},  {146, 255, 71}, {150, 254, 68}, {153, 254, 66},
 40 |     {156, 254, 64},  {159, 253, 63},  {161, 253, 61}, {164, 252, 60}, {167, 252, 58},
 41 |     {169, 251, 57},  {172, 251, 56},  {175, 250, 55}, {177, 249, 54}, {180, 248, 54},
 42 |     {183, 247, 53},  {185, 246, 53},  {188, 245, 52}, {190, 244, 52}, {193, 243, 52},
 43 |     {195, 241, 52},  {198, 240, 52},  {200, 239, 52}, {203, 237, 52}, {205, 236, 52},
 44 |     {208, 234, 52},  {210, 233, 53},  {212, 231, 53}, {215, 229, 53}, {217, 228, 54},
 45 |     {219, 226, 54},  {221, 224, 55},  {223, 223, 55}, {225, 221, 55}, {227, 219, 56},
 46 |     {229, 217, 56},  {231, 215, 57},  {233, 213, 57}, {235, 211, 57}, {236, 209, 58},
 47 |     {238, 207, 58},  {239, 205, 58},  {241, 203, 58}, {242, 201, 58}, {244, 199, 58},
 48 |     {245, 197, 58},  {246, 195, 58},  {247, 193, 58}, {248, 190, 57}, {249, 188, 57},
 49 |     {250, 186, 57},  {251, 184, 56},  {251, 182, 55}, {252, 179, 54}, {252, 177, 54},
 50 |     {253, 174, 53},  {253, 172, 52},  {254, 169, 51}, {254, 167, 50}, {254, 164, 49},
 51 |     {254, 161, 48},  {254, 158, 47},  {254, 155, 45}, {254, 153, 44}, {254, 150, 43},
 52 |     {254, 147, 42},  {254, 144, 41},  {253, 141, 39}, {253, 138, 38}, {252, 135, 37},
 53 |     {252, 132, 35},  {251, 129, 34},  {251, 126, 33}, {250, 123, 31}, {249, 120, 30},
 54 |     {249, 117, 29},  {248, 114, 28},  {247, 111, 26}, {246, 108, 25}, {245, 105, 24},
 55 |     {244, 102, 23},  {243, 99, 21},   {242, 96, 20},  {241, 93, 19},  {240, 91, 18},
 56 |     {239, 88, 17},   {237, 85, 16},   {236, 83, 15},  {235, 80, 14},  {234, 78, 13},
 57 |     {232, 75, 12},   {231, 73, 12},   {229, 71, 11},  {228, 69, 10},  {226, 67, 10},
 58 |     {225, 65, 9},    {223, 63, 8},    {221, 61, 8},   {220, 59, 7},   {218, 57, 7},
 59 |     {216, 55, 6},    {214, 53, 6},    {212, 51, 5},   {210, 49, 5},   {208, 47, 5},
 60 |     {206, 45, 4},    {204, 43, 4},    {202, 42, 4},   {200, 40, 3},   {197, 38, 3},
 61 |     {195, 37, 3},    {193, 35, 2},    {190, 33, 2},   {188, 32, 2},   {185, 30, 2},
 62 |     {183, 29, 2},    {180, 27, 1},    {178, 26, 1},   {175, 24, 1},   {172, 23, 1},
 63 |     {169, 22, 1},    {167, 20, 1},    {164, 19, 1},   {161, 18, 1},   {158, 16, 1},
 64 |     {155, 15, 1},    {152, 14, 1},    {149, 13, 1},   {146, 11, 1},   {142, 10, 1},
 65 |     {139, 9, 2},     {136, 8, 2},     {133, 7, 2},    {129, 6, 2},    {126, 5, 2},
 66 |     {122, 4, 3}};
 67 | 
 68 | std::vector colormap(
 69 |     const std::vector& values, std::optional min_value, std::optional max_value
 70 | ) {
 71 |     if (!min_value) {
 72 |         min_value = *std::min_element(values.begin(), values.end());
 73 |     }
 74 |     if (!max_value) {
 75 |         max_value = *std::max_element(values.begin(), values.end());
 76 |     }
 77 | 
 78 |     std::vector colors;
 79 | 
 80 |     for (const auto& value : values) {
 81 |         auto idx = static_cast(
 82 |             255 * (value - min_value.value()) / (max_value.value() - min_value.value())
 83 |         );
 84 |         colors.emplace_back(rerun::Color(TurboBytes[idx][0], TurboBytes[idx][1], TurboBytes[idx][2])
 85 |         );
 86 |     }
 87 |     return colors;
 88 | }
 89 | 
 90 | void log_imu(
 91 |     const rerun::RecordingStream& rec, const std::string& entity_path,
 92 |     const sensor_msgs::msg::Imu::ConstSharedPtr& msg
 93 | ) {
 94 |     rec.set_time_seconds(
 95 |         "timestamp",
 96 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
 97 |     );
 98 | 
 99 |     rec.log(entity_path + "/x", rerun::Scalar(msg->linear_acceleration.x));
100 |     rec.log(entity_path + "/y", rerun::Scalar(msg->linear_acceleration.y));
101 |     rec.log(entity_path + "/z", rerun::Scalar(msg->linear_acceleration.z));
102 | }
103 | 
104 | void log_image(
105 |     const rerun::RecordingStream& rec, const std::string& entity_path,
106 |     const sensor_msgs::msg::Image::ConstSharedPtr& msg, const ImageOptions& options
107 | ) {
108 |     rec.set_time_seconds(
109 |         "timestamp",
110 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
111 |     );
112 | 
113 |     // Depth images are 32-bit float (in meters) or 16-bit uint (in millimeters)
114 |     // See: https://ros.org/reps/rep-0118.html
115 |     if (msg->encoding == "16UC1") {
116 |         cv::Mat img = cv_bridge::toCvCopy(msg)->image;
117 |         rec.log(
118 |             entity_path,
119 |             rerun::DepthImage(rerun::Collection(img), width_height(img)).with_meter(1000)
120 |         );
121 |     } else if (msg->encoding == "32FC1") {
122 |         cv::Mat img = cv_bridge::toCvCopy(msg)->image;
123 |         if (options.min_depth) {
124 |             cv::threshold(img, img, options.min_depth.value(), 0, cv::THRESH_TOZERO);
125 |         }
126 |         if (options.max_depth) {
127 |             cv::threshold(img, img, options.max_depth.value(), 0, cv::THRESH_TOZERO_INV);
128 |         }
129 |         rec.log(
130 |             entity_path,
131 |             rerun::DepthImage(rerun::Collection(img), width_height(img)).with_meter(1.0)
132 |         );
133 |     } else {
134 |         cv::Mat img = cv_bridge::toCvCopy(msg, "rgb8")->image;
135 |         rec.log(
136 |             entity_path,
137 |             rerun::Image::from_rgb24(rerun::Collection(img), width_height(img))
138 |         );
139 |     }
140 | }
141 | 
142 | void log_pose_stamped(
143 |     const rerun::RecordingStream& rec, const std::string& entity_path,
144 |     const geometry_msgs::msg::PoseStamped::ConstSharedPtr& msg
145 | ) {
146 |     rec.set_time_seconds(
147 |         "timestamp",
148 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
149 |     );
150 | 
151 |     rec.log(
152 |         entity_path,
153 |         rerun::Transform3D(
154 |             rerun::components::Translation3D(
155 |                 msg->pose.position.x,
156 |                 msg->pose.position.y,
157 |                 msg->pose.position.z
158 |             ),
159 |             rerun::Quaternion::from_wxyz(
160 |                 msg->pose.orientation.w,
161 |                 msg->pose.orientation.x,
162 |                 msg->pose.orientation.y,
163 |                 msg->pose.orientation.z
164 |             )
165 |         )
166 |     );
167 | 
168 |     // this is a somewhat hacky way to get a trajectory visualization in Rerun
169 |     // this should be be easier in the future, see https://github.com/rerun-io/rerun/issues/723
170 |     std::string trajectory_entity_path = "/trajectories/" + entity_path;
171 |     rec.log(
172 |         trajectory_entity_path,
173 |         rerun::Points3D(
174 |             {{static_cast(msg->pose.position.x),
175 |               static_cast(msg->pose.position.y),
176 |               static_cast(msg->pose.position.z)}}
177 |         )
178 |     );
179 | }
180 | 
181 | void log_tf_message(
182 |     const rerun::RecordingStream& rec,
183 |     const std::map& tf_frame_to_entity_path,
184 |     const tf2_msgs::msg::TFMessage::ConstSharedPtr& msg
185 | ) {
186 |     for (const auto& transform : msg->transforms) {
187 |         if (tf_frame_to_entity_path.find(transform.child_frame_id) ==
188 |             tf_frame_to_entity_path.end()) {
189 |             rec.disable_timeline("timestamp");
190 |             rec.log("/", rerun::TextLog("No entity path for frame_id " + transform.child_frame_id));
191 |             continue;
192 |         }
193 | 
194 |         rec.set_time_seconds(
195 |             "timestamp",
196 |             rclcpp::Time(transform.header.stamp.sec, transform.header.stamp.nanosec).seconds()
197 |         );
198 | 
199 |         rec.log(
200 |             tf_frame_to_entity_path.at(transform.child_frame_id),
201 |             rerun::Transform3D(
202 |                 rerun::components::Translation3D(
203 |                     transform.transform.translation.x,
204 |                     transform.transform.translation.y,
205 |                     transform.transform.translation.z
206 |                 ),
207 |                 rerun::Quaternion::from_wxyz(
208 |                     transform.transform.rotation.w,
209 |                     transform.transform.rotation.x,
210 |                     transform.transform.rotation.y,
211 |                     transform.transform.rotation.z
212 |                 )
213 |             )
214 |         );
215 |     }
216 | }
217 | 
218 | void log_odometry(
219 |     const rerun::RecordingStream& rec, const std::string& entity_path,
220 |     const nav_msgs::msg::Odometry::ConstSharedPtr& msg
221 | ) {
222 |     rec.set_time_seconds(
223 |         "timestamp",
224 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
225 |     );
226 | 
227 |     rec.log(
228 |         entity_path,
229 |         rerun::Transform3D(
230 |             rerun::components::Translation3D(
231 |                 msg->pose.pose.position.x,
232 |                 msg->pose.pose.position.y,
233 |                 msg->pose.pose.position.z
234 |             ),
235 |             rerun::Quaternion::from_wxyz(
236 |                 msg->pose.pose.orientation.w,
237 |                 msg->pose.pose.orientation.x,
238 |                 msg->pose.pose.orientation.y,
239 |                 msg->pose.pose.orientation.z
240 |             )
241 |         )
242 |     );
243 | }
244 | 
245 | void log_camera_info(
246 |     const rerun::RecordingStream& rec, const std::string& entity_path,
247 |     const sensor_msgs::msg::CameraInfo::ConstSharedPtr& msg
248 | ) {
249 |     // Rerun uses column-major order for Mat3x3
250 |     const std::array image_from_camera = {
251 |         static_cast(msg->k[0]),
252 |         static_cast(msg->k[3]),
253 |         static_cast(msg->k[6]),
254 |         static_cast(msg->k[1]),
255 |         static_cast(msg->k[4]),
256 |         static_cast(msg->k[7]),
257 |         static_cast(msg->k[2]),
258 |         static_cast(msg->k[5]),
259 |         static_cast(msg->k[8]),
260 |     };
261 |     rec.log(
262 |         entity_path,
263 |         rerun::Pinhole(image_from_camera)
264 |             .with_resolution(static_cast(msg->width), static_cast(msg->height))
265 |     );
266 | }
267 | 
268 | void log_transform(
269 |     const rerun::RecordingStream& rec, const std::string& entity_path,
270 |     const geometry_msgs::msg::TransformStamped::ConstSharedPtr& msg
271 | ) {
272 |     rec.set_time_seconds(
273 |         "timestamp",
274 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
275 |     );
276 | 
277 |     rec.log(
278 |         entity_path,
279 |         rerun::Transform3D(
280 |             rerun::components::Translation3D(
281 |                 msg->transform.translation.x,
282 |                 msg->transform.translation.y,
283 |                 msg->transform.translation.z
284 |             ),
285 |             rerun::Quaternion::from_wxyz(
286 |                 msg->transform.rotation.w,
287 |                 msg->transform.rotation.x,
288 |                 msg->transform.rotation.y,
289 |                 msg->transform.rotation.z
290 |             )
291 |         )
292 |     );
293 | }
294 | 
295 | void log_point_cloud2(
296 |     const rerun::RecordingStream& rec, const std::string& entity_path,
297 |     const sensor_msgs::msg::PointCloud2::ConstSharedPtr& msg, const PointCloud2Options& options
298 | ) {
299 |     rec.set_time_seconds(
300 |         "timestamp",
301 |         rclcpp::Time(msg->header.stamp.sec, msg->header.stamp.nanosec).seconds()
302 |     );
303 | 
304 |     // TODO(leo) should match the behavior described here
305 |     // https://wiki.ros.org/rviz/DisplayTypes/PointCloud
306 |     // TODO(leo) if not specified, check if 2D points or 3D points
307 |     // TODO(leo) allow arbitrary color mapping
308 | 
309 |     size_t x_offset, y_offset, z_offset, rgb_offset;
310 |     bool has_x{false}, has_y{false}, has_z{false}, has_rgb{false};
311 | 
312 |     for (const auto& field : msg->fields) {
313 |         if (field.name == "x") {
314 |             x_offset = field.offset;
315 |             if (field.datatype != sensor_msgs::msg::PointField::FLOAT32) {
316 |                 rec.log(entity_path, rerun::TextLog("Only FLOAT32 x field supported"));
317 |                 return;
318 |             }
319 |             has_x = true;
320 |         } else if (field.name == "y") {
321 |             y_offset = field.offset;
322 |             if (field.datatype != sensor_msgs::msg::PointField::FLOAT32) {
323 |                 rec.log(entity_path, rerun::TextLog("Only FLOAT32 y field supported"));
324 |                 return;
325 |             }
326 |             has_y = true;
327 |         } else if (field.name == "z") {
328 |             z_offset = field.offset;
329 |             if (field.datatype != sensor_msgs::msg::PointField::FLOAT32) {
330 |                 rec.log(entity_path, rerun::TextLog("Only FLOAT32 z field supported"));
331 |                 return;
332 |             }
333 |             has_z = true;
334 |         } else if (field.name == options.colormap_field.value_or("rgb")) {
335 |             if (field.datatype == sensor_msgs::msg::PointField::UINT32 ||
336 |                 field.datatype == sensor_msgs::msg::PointField::FLOAT32) {
337 |                 has_rgb = true;
338 |                 rgb_offset = field.offset;
339 |             } else {
340 |                 rec.log(entity_path, rerun::TextLog("Only UINT32 and FLOAT32 rgb field supported"));
341 |                 continue;
342 |             }
343 |         }
344 |     }
345 | 
346 |     if (!has_x || !has_y || !has_z) {
347 |         rec.log(
348 |             entity_path,
349 |             rerun::TextLog("Currently only PointCloud2 messages with x, y, z fields are supported")
350 |         );
351 |         return;
352 |     }
353 | 
354 |     std::vector points(msg->width * msg->height);
355 |     std::vector colors;
356 | 
357 |     if (has_rgb) {
358 |         colors.reserve(msg->width * msg->height);
359 |     }
360 | 
361 |     for (size_t i = 0; i < msg->height; ++i) {
362 |         for (size_t j = 0; j < msg->width; ++j) {
363 |             auto point_offset = i * msg->row_step + j * msg->point_step;
364 |             rerun::Position3D position;
365 |             // TODO(leo) if xyz are consecutive fields we can do this in a single memcpy
366 |             std::memcpy(&position.xyz.xyz[0], &msg->data[point_offset + x_offset], sizeof(float));
367 |             std::memcpy(&position.xyz.xyz[1], &msg->data[point_offset + y_offset], sizeof(float));
368 |             std::memcpy(&position.xyz.xyz[2], &msg->data[point_offset + z_offset], sizeof(float));
369 |             if (has_rgb) {
370 |                 uint8_t bgra[4];
371 |                 std::memcpy(&bgra, &msg->data[point_offset + rgb_offset], sizeof(uint32_t));
372 |                 colors.emplace_back(rerun::Color(bgra[2], bgra[1], bgra[0]));
373 |             }
374 |             points[i * msg->width + j] = position;
375 |         }
376 |     }
377 | 
378 |     if (options.colormap == "turbo") {
379 |         std::vector values(msg->width * msg->height);
380 |         auto& colormap_field =
381 |             *std::find_if(msg->fields.begin(), msg->fields.end(), [&](const auto& field) {
382 |                 return field.name == options.colormap_field;
383 |             });
384 |         for (size_t i = 0; i < msg->height; ++i) {
385 |             for (size_t j = 0; j < msg->width; ++j) {
386 |                 float value;
387 |                 std::memcpy(
388 |                     &value,
389 |                     &msg->data[i * msg->row_step + j * msg->point_step + colormap_field.offset],
390 |                     sizeof(float)
391 |                 );
392 |                 values[i * msg->width + j] = value;
393 |             }
394 |         }
395 |         colors = colormap(values, options.colormap_min, options.colormap_max);
396 |     } else if (options.colormap == "rgb") {
397 |         if (!has_rgb) {
398 |             rec.log(entity_path, rerun::TextLog("RGB colormap specified but no RGB field present"));
399 |         }
400 |     } else if (options.colormap) {
401 |         rec.log("/", rerun::TextLog("Unsupported colormap specified: " + options.colormap.value()));
402 |     }
403 | 
404 |     rec.log(entity_path, rerun::Points3D(points).with_colors(colors));
405 | }
406 | 


--------------------------------------------------------------------------------
/rerun_bridge/src/rerun_bridge/visualizer_node.cpp:
--------------------------------------------------------------------------------
  1 | #include "visualizer_node.hpp"
  2 | #include "rerun_bridge/rerun_ros_interface.hpp"
  3 | 
  4 | #include 
  5 | #include 
  6 | #include 
  7 | 
  8 | #include 
  9 | #include 
 10 | 
 11 | using namespace std::chrono_literals;
 12 | 
 13 | ImageOptions image_options_from_topic_options(const TopicOptions& topic_options) {
 14 |     ImageOptions options;
 15 |     if (topic_options.find("min_depth") != topic_options.end()) {
 16 |         options.min_depth = topic_options.at("min_depth").as();
 17 |     }
 18 |     if (topic_options.find("max_depth") != topic_options.end()) {
 19 |         options.max_depth = topic_options.at("max_depth").as();
 20 |     }
 21 |     return options;
 22 | }
 23 | 
 24 | PointCloud2Options point_cloud2_options_from_topic_options(const TopicOptions& topic_options) {
 25 |     PointCloud2Options options;
 26 |     if (topic_options.find("colormap") != topic_options.end()) {
 27 |         options.colormap = topic_options.at("colormap").as();
 28 |     }
 29 |     if (topic_options.find("colormap_field") != topic_options.end()) {
 30 |         options.colormap_field = topic_options.at("colormap_field").as();
 31 |     }
 32 |     if (topic_options.find("colormap_min") != topic_options.end()) {
 33 |         options.colormap_min = topic_options.at("colormap_min").as();
 34 |     }
 35 |     if (topic_options.find("colormap_max") != topic_options.end()) {
 36 |         options.colormap_max = topic_options.at("colormap_max").as();
 37 |     }
 38 |     return options;
 39 | }
 40 | 
 41 | std::string parent_entity_path(const std::string& entity_path) {
 42 |     auto last_slash = entity_path.rfind('/');
 43 |     if (last_slash == std::string::npos) {
 44 |         return "";
 45 |     }
 46 |     return entity_path.substr(0, last_slash);
 47 | }
 48 | 
 49 | std::string resolve_ros_path(const std::string& path) {
 50 |     if (path.find("package://") == 0) {
 51 |         std::string package_name = path.substr(10, path.find('/', 10) - 10);
 52 |         std::string relative_path = path.substr(10 + package_name.size());
 53 |         try {
 54 |             std::string package_path = ament_index_cpp::get_package_share_directory(package_name);
 55 |             return package_path + relative_path;
 56 |         } catch (ament_index_cpp::PackageNotFoundError& e) {
 57 |             throw std::runtime_error(
 58 |                 "Could not resolve " + path +
 59 |                 ". Replace with relative / absolute path, source the correct ROS environment, or install " +
 60 |                 package_name + "."
 61 |             );
 62 |         }
 63 |     } else if (path.find("file://") == 0) {
 64 |         return path.substr(7);
 65 |     } else {
 66 |         return path;
 67 |     }
 68 | }
 69 | 
 70 | RerunLoggerNode::RerunLoggerNode() : Node("rerun_logger_node") {
 71 |     _rec.spawn().exit_on_failure();
 72 | 
 73 |     _parallel_callback_group = this->create_callback_group(rclcpp::CallbackGroupType::Reentrant);
 74 | 
 75 |     _tf_buffer = std::make_unique(this->get_clock());
 76 |     _tf_listener = std::make_unique(*_tf_buffer);
 77 | 
 78 |     _last_tf_update_time = this->get_clock()->now();
 79 | 
 80 |     // Read additional config from yaml file
 81 |     // NOTE We're not using the ROS parameter server for this, because roscpp doesn't support
 82 |     //   reading nested data structures.
 83 |     std::string yaml_path;
 84 |     this->declare_parameter("yaml_path", "");
 85 |     if (this->get_parameter("yaml_path", yaml_path)) {
 86 |         RCLCPP_INFO(this->get_logger(), "Read yaml config at %s", yaml_path.c_str());
 87 |     }
 88 |     _read_yaml_config(yaml_path);
 89 | 
 90 |     // check for new topics every 0.1 seconds
 91 |     _create_subscriptions_timer = this->create_wall_timer(
 92 |         100ms,
 93 |         [&]() -> void { _create_subscriptions(); },
 94 |         _parallel_callback_group
 95 |     );
 96 | 
 97 |     if (_tf_fixed_rate != 0.0) {
 98 |         _update_tf_timer = this->create_wall_timer(
 99 |             std::chrono::duration(1. / _tf_fixed_rate),
100 |             [&]() { _update_tf(); },
101 |             _parallel_callback_group
102 |         );
103 |     }
104 | }
105 | 
106 | /// Convert a topic name to its entity path.
107 | /// If the topic is explicitly mapped to an entity path, use that.
108 | /// Otherwise, the topic name will be automatically converted to a flattened entity path like this:
109 | ///   "/one/two/three/four" -> "/topics/one-two-three/four"
110 | std::string RerunLoggerNode::_resolve_entity_path(
111 |     const std::string& topic, const TopicOptions& topic_options
112 | ) const {
113 |     if (topic_options.find("entity_path") != topic_options.end()) {
114 |         return topic_options.at("entity_path").as();
115 |     } else {
116 |         std::string flattened_topic = topic;
117 |         auto last_slash =
118 |             (std::find(flattened_topic.rbegin(), flattened_topic.rend(), '/') + 1).base();
119 | 
120 |         if (last_slash != flattened_topic.begin()) {
121 |             // keep leading slash and last slash
122 |             std::replace(flattened_topic.begin() + 1, last_slash, '/', '-');
123 |         }
124 | 
125 |         return "/topics" + flattened_topic;
126 |     }
127 | }
128 | 
129 | // Resolve topic options for a given topic.
130 | // The options are merged from all matching keys overwriting previous values in the following order:
131 | //  1. Options for partial topic names (such as /, /ns, etc.)
132 | //  2. Options for message types (such as sensor_msgs::msg::Image)
133 | //  3. Options for the exact topic name (such as /ns/topic)
134 | // Aside from these rules, the options are merged in the order they are defined in the yaml file.
135 | TopicOptions RerunLoggerNode::_resolve_topic_options(
136 |     const std::string& topic, const std::string& message_type
137 | ) const {
138 |     TopicOptions merged_options;
139 |     // 1. partial topic names
140 |     for (const auto& [prefix, options] : _raw_topic_options) {
141 |         if (topic.find(prefix) == 0) {
142 |             merged_options.insert(options.begin(), options.end());
143 |         }
144 |     }
145 | 
146 |     // 2. message types
147 |     if (_raw_topic_options.find(message_type) != _raw_topic_options.end()) {
148 |         auto options = _raw_topic_options.at(message_type);
149 |         merged_options.insert(options.begin(), options.end());
150 |     }
151 | 
152 |     // 3. exact topic name
153 |     if (_raw_topic_options.find(topic) != _raw_topic_options.end()) {
154 |         auto options = _raw_topic_options.at(topic);
155 |         merged_options.insert(options.begin(), options.end());
156 |     }
157 | 
158 |     return merged_options;
159 | }
160 | 
161 | void RerunLoggerNode::_read_yaml_config(std::string yaml_path) {
162 |     const YAML::Node config = YAML::LoadFile(yaml_path);
163 | 
164 |     // see https://www.rerun.io/docs/howto/ros2-nav-turtlebot#tf-to-rrtransform3d
165 |     if (config["extra_transform3ds"]) {
166 |         for (const auto& extra_transform3d : config["extra_transform3ds"]) {
167 |             const std::array translation = {
168 |                 extra_transform3d["transform"][3].as(),
169 |                 extra_transform3d["transform"][7].as(),
170 |                 extra_transform3d["transform"][11].as()};
171 |             // Rerun uses column-major order for Mat3x3
172 |             const std::array mat3x3 = {
173 |                 extra_transform3d["transform"][0].as(),
174 |                 extra_transform3d["transform"][4].as(),
175 |                 extra_transform3d["transform"][8].as(),
176 |                 extra_transform3d["transform"][1].as(),
177 |                 extra_transform3d["transform"][5].as(),
178 |                 extra_transform3d["transform"][9].as(),
179 |                 extra_transform3d["transform"][2].as(),
180 |                 extra_transform3d["transform"][6].as(),
181 |                 extra_transform3d["transform"][10].as()};
182 |             _rec.log_static(
183 |                 extra_transform3d["entity_path"].as(),
184 |                 rerun::Transform3D(
185 |                     rerun::Vec3D(translation),
186 |                     rerun::Mat3x3(mat3x3),
187 |                     extra_transform3d["from_parent"].as()
188 |                 )
189 |             );
190 |         }
191 |     }
192 |     if (config["extra_pinholes"]) {
193 |         for (const auto& extra_pinhole : config["extra_pinholes"]) {
194 |             // Rerun uses column-major order for Mat3x3
195 |             const std::array image_from_camera = {
196 |                 extra_pinhole["image_from_camera"][0].as(),
197 |                 extra_pinhole["image_from_camera"][3].as(),
198 |                 extra_pinhole["image_from_camera"][6].as(),
199 |                 extra_pinhole["image_from_camera"][1].as(),
200 |                 extra_pinhole["image_from_camera"][4].as(),
201 |                 extra_pinhole["image_from_camera"][7].as(),
202 |                 extra_pinhole["image_from_camera"][2].as(),
203 |                 extra_pinhole["image_from_camera"][5].as(),
204 |                 extra_pinhole["image_from_camera"][8].as(),
205 |             };
206 |             _rec.log_static(
207 |                 extra_pinhole["entity_path"].as(),
208 |                 rerun::Pinhole(image_from_camera)
209 |                     .with_resolution(
210 |                         extra_pinhole["width"].as(),
211 |                         extra_pinhole["height"].as()
212 |                     )
213 |             );
214 |         }
215 |     }
216 |     if (config["tf"]) {
217 |         if (config["tf"]["update_rate"]) {
218 |             _tf_fixed_rate = config["tf"]["update_rate"].as();
219 |         }
220 | 
221 |         if (config["tf"]["tree"] && config["tf"]["tree"].size()) {
222 |             // set root frame, all messages with frame_id will be logged relative to this frame
223 |             _root_frame = config["tf"]["tree"].begin()->first.as();
224 | 
225 |             // recurse through the tree and add all transforms
226 |             _add_tf_tree(config["tf"]["tree"], "", "");
227 |         }
228 |     }
229 | 
230 |     if (config["topic_options"]) {
231 |         _raw_topic_options = config["topic_options"].as>();
232 |     }
233 | 
234 |     if (config["urdf"]) {
235 |         std::string urdf_entity_path;
236 |         if (config["urdf"]["entity_path"]) {
237 |             urdf_entity_path = config["urdf"]["entity_path"].as();
238 |         }
239 |         if (config["urdf"]["file_path"]) {
240 |             std::string urdf_file_path =
241 |                 resolve_ros_path(config["urdf"]["file_path"].as());
242 |             if (urdf_file_path.size()) {
243 |                 RCLCPP_INFO(
244 |                     this->get_logger(),
245 |                     "Logging URDF from file path %s",
246 |                     urdf_file_path.c_str()
247 |                 );
248 |                 _rec.log_file_from_path(urdf_file_path, urdf_entity_path, true);
249 |             }
250 |         }
251 |     }
252 | }
253 | 
254 | void RerunLoggerNode::_add_tf_tree(
255 |     const YAML::Node& topic_options, const std::string& parent_entity_path,
256 |     const ::std::string& parent_frame
257 | ) {
258 |     for (const auto& child : topic_options) {
259 |         auto frame = child.first.as();
260 |         auto value = child.second;
261 |         const std::string entity_path = parent_entity_path + "/" + frame;
262 |         _tf_frame_to_entity_path[frame] = entity_path;
263 |         _tf_frame_to_parent[frame] = parent_frame;
264 |         RCLCPP_INFO(
265 |             this->get_logger(),
266 |             "Mapping tf frame %s to entity path %s",
267 |             frame.c_str(),
268 |             entity_path.c_str()
269 |         );
270 |         if (value.size() >= 1) {
271 |             _add_tf_tree(value, entity_path, frame);
272 |         }
273 |     }
274 | }
275 | 
276 | void RerunLoggerNode::_create_subscriptions() {
277 |     for (const auto& [topic_name, topic_types] : this->get_topic_names_and_types()) {
278 |         // already subscribed to this topic?
279 |         if (_topic_to_subscription.find(topic_name) != _topic_to_subscription.end()) {
280 |             continue;
281 |         }
282 | 
283 |         if (topic_types.size() != 1) {
284 |             RCLCPP_WARN(
285 |                 this->get_logger(),
286 |                 "Skipping topic %s with multiple types",
287 |                 topic_name.c_str()
288 |             );
289 |             continue;
290 |         }
291 | 
292 |         const auto topic_type = topic_types[0];
293 |         const auto message_type = topic_types[0];
294 |         const auto topic_options = _resolve_topic_options(topic_name, message_type);
295 | 
296 |         if (topic_type == "sensor_msgs/msg/Image") {
297 |             _topic_to_subscription[topic_name] =
298 |                 _create_image_subscription(topic_name, topic_options);
299 |         } else if (topic_type == "sensor_msgs/msg/Imu") {
300 |             _topic_to_subscription[topic_name] =
301 |                 _create_imu_subscription(topic_name, topic_options);
302 |         } else if (topic_type == "geometry_msgs/msg/PoseStamped") {
303 |             _topic_to_subscription[topic_name] =
304 |                 _create_pose_stamped_subscription(topic_name, topic_options);
305 |         } else if (topic_type == "tf2_msgs/msg/TFMessage") {
306 |             _topic_to_subscription[topic_name] =
307 |                 _create_tf_message_subscription(topic_name, topic_options);
308 |         } else if (topic_type == "nav_msgs/msg/Odometry") {
309 |             _topic_to_subscription[topic_name] =
310 |                 _create_odometry_subscription(topic_name, topic_options);
311 |         } else if (topic_type == "sensor_msgs/msg/CameraInfo") {
312 |             _topic_to_subscription[topic_name] =
313 |                 _create_camera_info_subscription(topic_name, topic_options);
314 |         } else if (topic_type == "sensor_msgs/msg/PointCloud2") {
315 |             _topic_to_subscription[topic_name] =
316 |                 _create_point_cloud2_subscription(topic_name, topic_options);
317 |         }
318 |     }
319 | }
320 | 
321 | void RerunLoggerNode::_update_tf() {
322 |     // NOTE We log the interpolated transforms with an offset assuming the whole tree has
323 |     //  been updated after this offset. This is not an ideal solution. If a frame is updated
324 |     //  with a delay longer than this offset we will never log interpolated transforms for it.
325 |     //  It might be possible to always log the interpolated transforms on a per frame basis whenever
326 |     //  a new message is received for that frame. This would require maintaining the latest
327 |     //  transform for each frame. However, this would not work if transforms for a frame arrive
328 |     //  out of order (maybe this is not a problem in practice?).
329 | 
330 |     auto now = this->get_clock()->now();
331 | 
332 |     // If no time has passed since the last update, don't do anything
333 |     // This can happen when using simulation time that does not keep going at the end
334 |     if (now - _last_tf_update_time == 0s) {
335 |         return;
336 |     }
337 | 
338 |     for (const auto& [frame, entity_path] : _tf_frame_to_entity_path) {
339 |         auto parent = _tf_frame_to_parent.find(frame);
340 |         if (parent == _tf_frame_to_parent.end() or parent->second.empty()) {
341 |             continue;
342 |         }
343 |         try {
344 |             auto transform = std::make_shared(
345 |                 _tf_buffer->lookupTransform(parent->second, frame, now - rclcpp::Duration(1, 0))
346 |             );
347 |             log_transform(_rec, entity_path, transform);
348 |             _last_tf_update_time = now;
349 |         } catch (tf2::TransformException& ex) {
350 |             RCLCPP_WARN_THROTTLE(
351 |                 this->get_logger(),
352 |                 *this->get_clock(),
353 |                 1000,
354 |                 "Could not lookup transform: %s",
355 |                 ex.what()
356 |             );
357 |         }
358 |     }
359 | }
360 | 
361 | std::shared_ptr>
362 |     RerunLoggerNode::_create_image_subscription(
363 |         const std::string& topic, const TopicOptions& topic_options
364 |     ) {
365 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
366 |     bool lookup_transform = (topic_options.find("entity_path") == topic_options.end());
367 |     bool restamp = false;
368 |     if (topic_options.find("restamp") != topic_options.end()) {
369 |         restamp = topic_options.at("restamp").as();
370 |     }
371 | 
372 |     auto image_options = image_options_from_topic_options(topic_options);
373 | 
374 |     rclcpp::SubscriptionOptions subscription_options;
375 |     subscription_options.callback_group = _parallel_callback_group;
376 | 
377 |     RCLCPP_INFO(
378 |         this->get_logger(),
379 |         "Subscribing to Image topic %s, logging to entity path %s",
380 |         topic.c_str(),
381 |         entity_path.c_str()
382 |     );
383 | 
384 |     return this->create_subscription(
385 |         topic,
386 |         1000,
387 |         [&, entity_path, lookup_transform, restamp, image_options](
388 |             const sensor_msgs::msg::Image::SharedPtr msg
389 |         ) {
390 |             _handle_msg_header(
391 |                 restamp,
392 |                 lookup_transform,
393 |                 parent_entity_path(entity_path),
394 |                 msg->header
395 |             );
396 |             log_image(_rec, entity_path, msg, image_options);
397 |         },
398 |         subscription_options
399 |     );
400 | }
401 | 
402 | std::shared_ptr>
403 |     RerunLoggerNode::_create_imu_subscription(
404 |         const std::string& topic, const TopicOptions& topic_options
405 |     ) {
406 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
407 |     bool restamp = false;
408 |     if (topic_options.find("restamp") != topic_options.end()) {
409 |         restamp = topic_options.at("restamp").as();
410 |     }
411 | 
412 |     rclcpp::SubscriptionOptions subscription_options;
413 |     subscription_options.callback_group = _parallel_callback_group;
414 | 
415 |     return this->create_subscription(
416 |         topic,
417 |         1000,
418 |         [&, entity_path, restamp](const sensor_msgs::msg::Imu::SharedPtr msg) {
419 |             _handle_msg_header(restamp, false, entity_path, msg->header);
420 |             log_imu(_rec, entity_path, msg);
421 |         },
422 |         subscription_options
423 |     );
424 | }
425 | 
426 | std::shared_ptr>
427 |     RerunLoggerNode::_create_pose_stamped_subscription(
428 |         const std::string& topic, const TopicOptions& topic_options
429 |     ) {
430 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
431 |     bool lookup_transform = (topic_options.find("entity_path") == topic_options.end());
432 |     bool restamp = false;
433 |     if (topic_options.find("restamp") != topic_options.end()) {
434 |         restamp = topic_options.at("restamp").as();
435 |     }
436 | 
437 |     rclcpp::SubscriptionOptions subscription_options;
438 |     subscription_options.callback_group = _parallel_callback_group;
439 | 
440 |     return this->create_subscription(
441 |         topic,
442 |         1000,
443 |         [&, entity_path, lookup_transform, restamp](
444 |             const geometry_msgs::msg::PoseStamped::SharedPtr msg
445 |         ) {
446 |             _handle_msg_header(restamp, lookup_transform, entity_path, msg->header);
447 |             log_pose_stamped(_rec, entity_path, msg);
448 |         },
449 |         subscription_options
450 |     );
451 | }
452 | 
453 | std::shared_ptr>
454 |     RerunLoggerNode::_create_tf_message_subscription(
455 |         const std::string& topic, const TopicOptions& topic_options
456 |     ) {
457 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
458 | 
459 |     rclcpp::SubscriptionOptions subscription_options;
460 |     subscription_options.callback_group = _parallel_callback_group;
461 | 
462 |     return this->create_subscription(
463 |         topic,
464 |         1000,
465 |         [&, entity_path](const tf2_msgs::msg::TFMessage::SharedPtr msg) {
466 |             log_tf_message(_rec, _tf_frame_to_entity_path, msg);
467 |         },
468 |         subscription_options
469 |     );
470 | }
471 | 
472 | std::shared_ptr>
473 |     RerunLoggerNode::_create_odometry_subscription(
474 |         const std::string& topic, const TopicOptions& topic_options
475 |     ) {
476 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
477 |     bool lookup_transform = (topic_options.find("entity_path") == topic_options.end());
478 |     bool restamp = false;
479 |     if (topic_options.find("restamp") != topic_options.end()) {
480 |         restamp = topic_options.at("restamp").as();
481 |     }
482 | 
483 |     rclcpp::SubscriptionOptions subscription_options;
484 |     subscription_options.callback_group = _parallel_callback_group;
485 | 
486 |     return this->create_subscription(
487 |         topic,
488 |         1000,
489 |         [&, entity_path, lookup_transform, restamp](const nav_msgs::msg::Odometry::SharedPtr msg) {
490 |             _handle_msg_header(restamp, lookup_transform, entity_path, msg->header);
491 |             log_odometry(_rec, entity_path, msg);
492 |         },
493 |         subscription_options
494 |     );
495 | }
496 | 
497 | std::shared_ptr>
498 |     RerunLoggerNode::_create_camera_info_subscription(
499 |         const std::string& topic, const TopicOptions& topic_options
500 |     ) {
501 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
502 |     bool restamp = false;
503 |     if (topic_options.find("restamp") != topic_options.end()) {
504 |         restamp = topic_options.at("restamp").as();
505 |     }
506 | 
507 |     rclcpp::SubscriptionOptions subscription_options;
508 |     subscription_options.callback_group = _parallel_callback_group;
509 | 
510 |     // If the camera_info topic has not been explicility mapped to an entity path,
511 |     // we assume that the camera_info topic is a sibling of the image topic, and
512 |     // hence use the parent as the entity path for the pinhole model.
513 |     if (topic_options.find("entity_path") == topic_options.end()) {
514 |         entity_path = parent_entity_path(entity_path);
515 |     }
516 | 
517 |     return this->create_subscription(
518 |         topic,
519 |         1,
520 |         [&, entity_path, restamp](const sensor_msgs::msg::CameraInfo::SharedPtr msg) {
521 |             _handle_msg_header(restamp, false, entity_path, msg->header);
522 |             log_camera_info(_rec, entity_path, msg);
523 |         },
524 |         subscription_options
525 |     );
526 | }
527 | 
528 | std::shared_ptr>
529 |     RerunLoggerNode::_create_point_cloud2_subscription(
530 |         const std::string& topic, const TopicOptions& topic_options
531 |     ) {
532 |     std::string entity_path = _resolve_entity_path(topic, topic_options);
533 |     bool lookup_transform = (topic_options.find("entity_path") == topic_options.end());
534 |     bool restamp = false;
535 |     if (topic_options.find("restamp") != topic_options.end()) {
536 |         restamp = topic_options.at("restamp").as();
537 |     }
538 |     auto point_cloud2_options = point_cloud2_options_from_topic_options(topic_options);
539 | 
540 |     rclcpp::SubscriptionOptions subscription_options;
541 |     subscription_options.callback_group = _parallel_callback_group;
542 | 
543 |     RCLCPP_INFO(
544 |         this->get_logger(),
545 |         "Subscribing to PointCloud2 topic %s, logging to entity path %s",
546 |         topic.c_str(),
547 |         entity_path.c_str()
548 |     );
549 | 
550 |     return this->create_subscription(
551 |         topic,
552 |         1000,
553 |         [&, entity_path, lookup_transform, restamp, point_cloud2_options](
554 |             const sensor_msgs::msg::PointCloud2::SharedPtr msg
555 |         ) {
556 |             _handle_msg_header(restamp, lookup_transform, entity_path, msg->header);
557 |             log_point_cloud2(_rec, entity_path, msg, point_cloud2_options);
558 |         },
559 |         subscription_options
560 |     );
561 | }
562 | 
563 | void RerunLoggerNode::_handle_msg_header(
564 |     bool restamp, bool lookup_transform, const std::string& entity_path,
565 |     std_msgs::msg::Header& header
566 | ) {
567 |     if (restamp) {
568 |         auto now = this->get_clock()->now();
569 |         header.stamp = now;
570 |     }
571 |     if (!_root_frame.empty() && lookup_transform) {
572 |         try {
573 |             auto transform = std::make_shared(
574 |                 _tf_buffer->lookupTransform(_root_frame, header.frame_id, header.stamp, 100ms)
575 |             );
576 |             log_transform(_rec, entity_path, transform);
577 |         } catch (tf2::TransformException& ex) {
578 |             RCLCPP_WARN(this->get_logger(), "%s", ex.what());
579 |         }
580 |     }
581 | }
582 | 
583 | int main(int argc, char** argv) {
584 |     rclcpp::init(argc, argv);
585 |     rclcpp::executors::MultiThreadedExecutor executor;
586 | 
587 |     // Executor does not take ownership of the topic_options, so we have to maintain a shared_ptr
588 |     auto rerun_logger_node = std::make_shared();
589 |     executor.add_node(rerun_logger_node);
590 | 
591 |     executor.spin();
592 |     rclcpp::shutdown();
593 |     return 0;
594 | }
595 | 


--------------------------------------------------------------------------------
/rerun_bridge/src/rerun_bridge/visualizer_node.hpp:
--------------------------------------------------------------------------------
 1 | #pragma once
 2 | 
 3 | #include 
 4 | #include 
 5 | #include 
 6 | 
 7 | #include 
 8 | #include 
 9 | #include 
10 | #include 
11 | #include 
12 | #include 
13 | #include 
14 | #include 
15 | #include 
16 | #include 
17 | #include 
18 | 
19 | #include 
20 | 
21 | using TopicOptions = std::map;
22 | 
23 | class RerunLoggerNode : public rclcpp::Node {
24 |   public:
25 |     RerunLoggerNode();
26 |     void spin();
27 | 
28 |   private:
29 |     rclcpp::CallbackGroup::SharedPtr _parallel_callback_group;
30 |     std::map> _topic_to_subscription;
31 |     std::map _tf_frame_to_entity_path;
32 |     std::map _tf_frame_to_parent;
33 |     std::map _raw_topic_options;
34 |     rclcpp::Time _last_tf_update_time;
35 | 
36 |     void _read_yaml_config(std::string yaml_path);
37 | 
38 |     TopicOptions _resolve_topic_options(const std::string& topic, const std::string& message_type)
39 |         const;
40 |     std::string _resolve_entity_path(const std::string& topic, const TopicOptions& topic_options)
41 |         const;
42 | 
43 |     void _add_tf_tree(
44 |         const YAML::Node& node, const std::string& parent_entity_path,
45 |         const std::string& parent_frame
46 |     );
47 | 
48 |     const rerun::RecordingStream _rec{"rerun_logger_node"};
49 |     std::string _root_frame;
50 |     float _tf_fixed_rate;
51 |     std::unique_ptr _tf_buffer;
52 |     std::unique_ptr _tf_listener;
53 | 
54 |     rclcpp::TimerBase::SharedPtr _create_subscriptions_timer;
55 |     rclcpp::TimerBase::SharedPtr _update_tf_timer;
56 | 
57 |     void _create_subscriptions();
58 |     void _update_tf();
59 | 
60 |     void _handle_msg_header(
61 |         bool restamp, bool lookup_transform, const std::string& entity_path,
62 |         std_msgs::msg::Header& header
63 |     );
64 | 
65 |     /* Message specific subscriber factory functions */
66 |     std::shared_ptr> _create_image_subscription(
67 |         const std::string& topic, const TopicOptions& topic_options
68 |     );
69 |     std::shared_ptr> _create_imu_subscription(
70 |         const std::string& topic, const TopicOptions& topic_options
71 |     );
72 |     std::shared_ptr>
73 |         _create_pose_stamped_subscription(
74 |             const std::string& topic, const TopicOptions& topic_options
75 |         );
76 |     std::shared_ptr> _create_tf_message_subscription(
77 |         const std::string& topic, const TopicOptions& topic_options
78 |     );
79 |     std::shared_ptr> _create_odometry_subscription(
80 |         const std::string& topic, const TopicOptions& topic_options
81 |     );
82 |     std::shared_ptr>
83 |         _create_camera_info_subscription(
84 |             const std::string& topic, const TopicOptions& topic_options
85 |         );
86 |     std::shared_ptr>
87 |         _create_point_cloud2_subscription(
88 |             const std::string& topic, const TopicOptions& topic_options
89 |         );
90 | };
91 | 


--------------------------------------------------------------------------------
/scripts/template_update.py:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env python3
  2 | # Copied from https://github.com/rerun-io/rerun_template
  3 | 
  4 | """
  5 | The script has two purposes.
  6 | 
  7 | After using `rerun_template` as a template, run this to clean out things you don't need.
  8 | Use `scripts/template_update.py init --languages cpp,rust,python` for this.
  9 | 
 10 | Update an existing repository with the latest changes from the template.
 11 | Use `scripts/template_update.py update --languages cpp,rust,python` for this.
 12 | 
 13 | In either case, make sure the list of languages matches the languages you want to support.
 14 | You can also use `--dry-run` to see what would happen without actually changing anything.
 15 | """
 16 | 
 17 | from __future__ import annotations
 18 | 
 19 | import argparse
 20 | import os
 21 | import shutil
 22 | import tempfile
 23 | 
 24 | from git import Repo
 25 | 
 26 | OWNER = "rerun-io"
 27 | 
 28 | # Files requires by C++, but not by both Python or Rust.
 29 | CPP_FILES = {
 30 |     ".clang-format",
 31 |     ".github/workflows/cpp.yml",
 32 |     "CMakeLists.txt",
 33 |     "pixi.lock",  # Not needed by Rust
 34 |     "pixi.toml",  # Not needed by Rust
 35 |     "src/main.cpp",
 36 |     "src/",
 37 | }
 38 | 
 39 | # Files requires by Python, but not by both C++ or Rust
 40 | PYTHON_FILES = {
 41 |     ".github/workflows/python.yml",
 42 |     ".mypy.ini",
 43 |     "main.py",
 44 |     "pixi.lock",  # Not needed by Rust
 45 |     "pixi.toml",  # Not needed by Rust
 46 |     "pyproject.toml",
 47 |     "requirements.txt",
 48 | }
 49 | 
 50 | # Files requires by Rust, but not by both C++ or Python
 51 | RUST_FILES = {
 52 |     ".github/workflows/rust.yml",
 53 |     "bacon.toml",
 54 |     "Cargo.lock",
 55 |     "Cargo.toml",
 56 |     "clippy.toml",
 57 |     "Cranky.toml",
 58 |     "deny.toml",
 59 |     "rust-toolchain",
 60 |     "scripts/clippy_wasm/",
 61 |     "scripts/clippy_wasm/clippy.toml",
 62 |     "src/lib.rs",
 63 |     "src/main.rs",
 64 |     "src/",
 65 | }
 66 | 
 67 | 
 68 | def parse_languages(lang_str: str) -> set[str]:
 69 |     languages = lang_str.split(",") if lang_str else []
 70 |     for lang in languages:
 71 |         assert lang in ["cpp", "python", "rust"], f"Unsupported language: {lang}"
 72 |     return set(languages)
 73 | 
 74 | 
 75 | def calc_deny_set(languages: set[str]) -> set[str]:
 76 |     """The set of files to delete/ignore."""
 77 |     files_to_delete = CPP_FILES | PYTHON_FILES | RUST_FILES
 78 |     if "cpp" in languages:
 79 |         files_to_delete -= CPP_FILES
 80 |     if "python" in languages:
 81 |         files_to_delete -= PYTHON_FILES
 82 |     if "rust" in languages:
 83 |         files_to_delete -= RUST_FILES
 84 |     return files_to_delete
 85 | 
 86 | 
 87 | def init(languages: set[str], dry_run: bool) -> None:
 88 |     print("Removing all language-specific files not needed for languages {languages}.")
 89 |     files_to_delete = calc_deny_set(languages)
 90 |     delete_files_and_folder(files_to_delete, dry_run)
 91 | 
 92 | 
 93 | def delete_files_and_folder(paths: set[str], dry_run: bool) -> None:
 94 |     repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
 95 |     for path in paths:
 96 |         full_path = os.path.join(repo_path, path)
 97 |         if os.path.exists(full_path):
 98 |             if os.path.isfile(full_path):
 99 |                 print(f"Removing file {full_path}…")
100 |                 if not dry_run:
101 |                     os.remove(full_path)
102 |             elif os.path.isdir(full_path):
103 |                 print(f"Removing folder {full_path}…")
104 |                 if not dry_run:
105 |                     shutil.rmtree(full_path)
106 | 
107 | 
108 | def update(languages: set[str], dry_run: bool) -> None:
109 |     # Don't overwrite these
110 |     ALWAYS_IGNORE_FILES = {"README.md", "pixi.lock", "Cargo.lock", "main.py", "requirements.txt"}
111 | 
112 |     files_to_ignore = calc_deny_set(languages) | ALWAYS_IGNORE_FILES
113 |     repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
114 | 
115 |     with tempfile.TemporaryDirectory() as temp_dir:
116 |         Repo.clone_from("https://github.com/rerun-io/rerun_template.git", temp_dir)
117 |         for root, dirs, files in os.walk(temp_dir):
118 |             for file in files:
119 |                 src_path = os.path.join(root, file)
120 |                 rel_path = os.path.relpath(src_path, temp_dir)
121 | 
122 |                 if rel_path.startswith(".git/"):
123 |                     continue
124 |                 if rel_path.startswith("src/"):
125 |                     continue
126 |                 if rel_path in files_to_ignore:
127 |                     continue
128 | 
129 |                 dest_path = os.path.join(repo_path, rel_path)
130 | 
131 |                 print(f"Updating {rel_path}…")
132 |                 if not dry_run:
133 |                     os.makedirs(os.path.dirname(dest_path), exist_ok=True)
134 |                     shutil.copy2(src_path, dest_path)
135 | 
136 | 
137 | def main() -> None:
138 |     parser = argparse.ArgumentParser(description="Handle the Rerun template.")
139 |     subparsers = parser.add_subparsers(dest="command")
140 | 
141 |     init_parser = subparsers.add_parser("init", help="Initialize a new checkout of the template.")
142 |     init_parser.add_argument(
143 |         "--languages", default="", nargs="?", const="", help="The languages to support (e.g. `cpp,python,rust`)."
144 |     )
145 |     init_parser.add_argument("--dry-run", action="store_true", help="Don't actually delete any files.")
146 | 
147 |     update_parser = subparsers.add_parser(
148 |         "update", help="Update all existing Rerun repositories with the latest changes from the template"
149 |     )
150 |     update_parser.add_argument(
151 |         "--languages", default="", nargs="?", const="", help="The languages to support (e.g. `cpp,python,rust`)."
152 |     )
153 |     update_parser.add_argument("--dry-run", action="store_true", help="Don't actually delete any files.")
154 | 
155 |     args = parser.parse_args()
156 | 
157 |     if args.command == "init":
158 |         init(parse_languages(args.languages), args.dry_run)
159 |     elif args.command == "update":
160 |         update(parse_languages(args.languages), args.dry_run)
161 |     else:
162 |         parser.print_help()
163 |         exit(1)
164 | 
165 | 
166 | if __name__ == "__main__":
167 |     main()
168 | 


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