From 48ca9e0589c21cbba2097beb80a5db9cdd26513c Mon Sep 17 00:00:00 2001 From: Rouven Spreckels Date: Sat, 19 Aug 2023 14:05:55 +0200 Subject: [PATCH] Initial commit. --- .cargo/config.toml | 2 + .github/workflows/build.yml | 91 +++++++++ .gitignore | 3 + Cargo.toml | 82 ++++++++ LICENSES/Apache-2.0 | 176 +++++++++++++++++ LICENSES/MIT | 23 +++ README.md | 167 ++++++++++++++++ RELEASES.md | 3 + examples/constellation_clamp.rs | 233 ++++++++++++++++++++++ examples/egui.rs | 266 +++++++++++++++++++++++++ examples/exponential_map.rs | 62 ++++++ examples/gliding_clamp.rs | 127 ++++++++++++ examples/scaling_modes.rs | 211 ++++++++++++++++++++ examples/wasm/Makefile | 63 ++++++ examples/wasm/example.html | 113 +++++++++++ rustfmt.toml | 4 + src/camera.rs | 172 +++++++++++++++++ src/constellation.rs | 89 +++++++++ src/controller.rs | 132 +++++++++++++ src/controller/input.rs | 201 +++++++++++++++++++ src/controller/key.rs | 117 +++++++++++ src/controller/mouse.rs | 128 ++++++++++++ src/controller/touch.rs | 89 +++++++++ src/controller/viewport.rs | 111 +++++++++++ src/lib.rs | 332 ++++++++++++++++++++++++++++++++ 25 files changed, 2997 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .github/workflows/build.yml create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSES/Apache-2.0 create mode 100644 LICENSES/MIT create mode 100644 README.md create mode 100644 RELEASES.md create mode 100644 examples/constellation_clamp.rs create mode 100644 examples/egui.rs create mode 100644 examples/exponential_map.rs create mode 100644 examples/gliding_clamp.rs create mode 100644 examples/scaling_modes.rs create mode 100644 examples/wasm/Makefile create mode 100644 examples/wasm/example.html create mode 100644 rustfmt.toml create mode 100644 src/camera.rs create mode 100644 src/constellation.rs create mode 100644 src/controller.rs create mode 100644 src/controller/input.rs create mode 100644 src/controller/key.rs create mode 100644 src/controller/mouse.rs create mode 100644 src/controller/touch.rs create mode 100644 src/controller/viewport.rs create mode 100644 src/lib.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000000..758ed61020 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.wasm32-unknown-unknown] +runner = "wasm-server-runner" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000000..a636d5167d --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,91 @@ +name: build +on: + merge_group: + pull_request: + push: +env: + CARGO_TERM_COLOR: always +jobs: + default: + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v3 + - name: msrv + run: | + msrv=$(cargo metadata --no-deps --format-version 1 | + jq --raw-output '.packages[] | select(.name=="bevy_trackball") | .rust_version') + echo "MSRV=$msrv" >> $GITHUB_ENV + - name: toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.MSRV }} + components: rustfmt, rust-docs, clippy + - name: dependencies + run: | + sudo apt update + sudo apt install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev + - name: test + run: cargo test + - name: clippy + run: cargo clippy --tests --examples -- -D clippy::all -D clippy::pedantic -D clippy::nursery + - name: doc + run: cargo doc + - name: fmt + run: cargo fmt --check + all-features: + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v3 + - name: msrv + run: | + msrv=$(cargo metadata --no-deps --format-version 1 | + jq --raw-output '.packages[] | select(.name=="bevy_trackball") | .rust_version') + echo "MSRV=$msrv" >> $GITHUB_ENV + - name: toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.MSRV }} + components: rustfmt, rust-docs, clippy + - name: dependencies + run: | + sudo apt update + sudo apt install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev + - name: test + run: cargo test --all-features + - name: clippy + run: cargo clippy --tests --examples --all-features -- -D clippy::all -D clippy::pedantic -D clippy::nursery + - name: doc + run: cargo doc --all-features + - name: fmt + run: cargo fmt --check + all-features-nightly: + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v3 + - name: msrv + run: | + msrv=$(cargo metadata --no-deps --format-version 1 | + jq --raw-output '.packages[] | select(.name=="bevy_trackball") | .rust_version') + echo "MSRV=$msrv" >> $GITHUB_ENV + - name: toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: nightly + components: rustfmt, rust-docs, clippy + - name: dependencies + run: | + sudo apt update + sudo apt install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev + - name: test + run: cargo test --all-features + - name: clippy + run: cargo clippy --tests --examples --all-features -- -D clippy::all -D clippy::pedantic -D clippy::nursery + - name: doc + env: + RUSTDOCFLAGS: --cfg docsrs + run: cargo doc --all-features + - name: fmt + run: cargo fmt --check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..0b5bc6b435 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target +Cargo.lock +**/*.swp diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000..40c95ad14d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,82 @@ +[package] +name = "bevy_trackball" +version = "0.1.0" +rust-version = "1.70.0" +authors = ["Rouven Spreckels "] +edition = "2021" +description = "Coherent virtual trackball controller/camera plugin for Bevy" +homepage = "https://qu1x.github.io/bevy_trackball" +documentation = "https://docs.rs/bevy_trackball" +repository = "https://github.com/qu1x/bevy_trackball" +readme = "README.md" +license = "MIT OR Apache-2.0" +keywords = [ + "virtual-trackball", + "exponential-map", + "coherent-rotation", + "pan-orbit", + "bevy-camera", +] +categories = [ + "graphics", + "rendering", + "game-engines", + "science", +] +include = [ + "src/**/*.rs", + "examples/**/*.rs", + "Cargo.toml", + "README.md", + "RELEASES.md", + "LICENSES/*.md", +] + +[package.metadata.docs.rs] +features = ["serialize"] +rustdoc-args = ["--cfg", "docsrs"] + +[features] +bevy_egui = ["dep:bevy_egui"] +serialize = ["bevy/serialize", "trackball/serde"] + +[dependencies] +bevy = { version = "0.11.1", default-features = false, features = ["bevy_render"] } +bevy_egui = { version = "0.21.0", default-features = false, optional = true } +trackball = { version = "0.11.2", features = ["glam"] } + +[dev-dependencies.bevy] +version = "0.11.1" +default-features = false +features = [ + "bevy_winit", + "bevy_core_pipeline", + "bevy_pbr", + "ktx2", + "zstd", + "tonemapping_luts", + "wayland", + "webgl2", +] + +[[example]] +name = "exponential_map" +required-features = [] +[[example]] +name = "gliding_clamp" +required-features = [] +[[example]] +name = "constellation_clamp" +required-features = ["bevy/bevy_ui", "bevy/default_font"] +[[example]] +name = "egui" +required-features = ["bevy_egui/default_fonts"] +[[example]] +name = "scaling_modes" +required-features = [] + +[profile.wasm-release] +inherits = "release" +opt-level = "z" +lto = "fat" +codegen-units = 1 diff --git a/LICENSES/Apache-2.0 b/LICENSES/Apache-2.0 new file mode 100644 index 0000000000..1b5ec8b78e --- /dev/null +++ b/LICENSES/Apache-2.0 @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSES/MIT b/LICENSES/MIT new file mode 100644 index 0000000000..31aa79387f --- /dev/null +++ b/LICENSES/MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..77d86e3d79 --- /dev/null +++ b/README.md @@ -0,0 +1,167 @@ +# bevy_trackball + +Coherent virtual trackball controller/camera plugin for Bevy + +[![Build][]](https://github.com/qu1x/bevy_trackball/actions/workflows/build.yml) +[![Documentation][]](https://docs.rs/bevy_trackball) +[![Downloads][]](https://crates.io/crates/bevy_trackball) +[![Version][]](https://crates.io/crates/bevy_trackball) +[![Rust][]](https://www.rust-lang.org) +[![License][]](https://opensource.org/licenses) + +[Build]: https://github.com/qu1x/bevy_trackball/actions/workflows/build.yml/badge.svg +[Documentation]: https://docs.rs/bevy_trackball/badge.svg +[Downloads]: https://img.shields.io/crates/d/bevy_trackball.svg +[Version]: https://img.shields.io/crates/v/bevy_trackball.svg +[Rust]: https://img.shields.io/badge/rust-v1.70-brightgreen.svg +[License]: https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue.svg + +Run simple and advanced [examples] in your browser using WASM and WebGL. + +## Coherence Features + +This is an alternative trackball technique using exponential map and parallel transport to +preserve distances and angles for inducing coherent and intuitive trackball rotations. For +instance, displacements on straight radial lines through the screen’s center are carried to arcs +of the same length on great circles of the trackball (e.g., dragging the mouse along an eights +of the trackball's circumference rolls the camera by 360/8=45 degrees, dragging the mouse from +the screen's center to its further edge *linearly* rotates the camera by 1 [radian], where the +trackball's diameter is the maximum of the screen's width and height). This is in contrast to +state-of-the-art techniques using orthogonal projection which distorts radial distances further +away from the screen’s center (e.g., the rotation accelerates towards the edge). + +[radian]: https://en.wikipedia.org/wiki/Radian + + * Coherent and intuitive orbiting via the exponential map, see the underlying [`trackball`] + crate which follows the recipe given in the paper of Stantchev, G.. “Virtual Trackball + Modeling and the Exponential Map.”. [S2CID] [44199608]. See the [`exponential_map`] example. + * Coherent first person view aka free look or mouse look with the world trackball centered at + eye instead of target. + * Coherent scaling by translating mouse wheel device units, see [`TrackballWheelUnit`]. Scales + eye distance from current cursor position or centroid of finger positions projected onto + focus plane. + * Coherent linear/angular [`TrackballVelocity`] for sliding/orbiting or free look by + time-based input (e.g., pressed key). By default, the linear velocity is derived from + angular velocity (where target and eye positions define the world radius) which in turn is + defined in units of vertical field of view per seconds and hence independent of the world + unit scale. + +[S2CID]: https://en.wikipedia.org/wiki/S2CID_(identifier) +[44199608]: https://api.semanticscholar.org/CorpusID:44199608 + +[`trackball`]: https://docs.rs/trackball/latest/trackball/ +[`TrackballWheelUnit`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballWheelUnit.html +[`TrackballVelocity`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballVelocity.html + +## Additional Features + + * Time-free multi-touch gesture recognition for orbit, scale, slide, and focus (i.e., slide to + cursor/finger position) operations. + * Smoothing of movement implemented as fps-agnostic exponential easy-out. + * Gimbal lock-free using quaternion instead of Euler angles. + * Gliding clamp (experimental): The movement of a camera can be restricted to user-defined + boundary conditions (e.g., to not orbit below the ground plane). When the movement is not + orthogonal to a boundary plane, it is changed such that the camera glides along the boundary + plane. Currently, only implemented for orbit and slide operations, see the [`gliding_clamp`] + example. + * Camera constellation: A camera is decoupled from its input controller and instead multiple + cameras can be sensitive to zero or multiple selected controllers (e.g., a minimap + controlled by the same controller of the main viewport). + * Constellation clamp: Cameras sensitive to the same controller are referred to as a group + and can be configured to clamp the movement for the whole group whenever a group member + crosses a boundary condition (e.g., rigid and loose constellation clamp), see the + [`constellation_clamp`] example. + * Viewport stealing: This allows UI system (e.g., egui behind `bevy_egui` feature gate) to + steal the viewport and hence capture the input instead, see the [`egui`] example. + * Scale-preserving transitioning between orthographic and perspective projection mode. + * Converting between scaling modes (i.e., fixed vertical or horizontal field of view or fixed + unit per pixels). This defines whether the scene scales or the corresponding vertical or + horizontal field of view adjusts whenever the height or width of the viewport is resized, + see the [`scaling_modes`] example. + * Object inspection mode scaling clip plane distances by measuring from target instead of eye. + This benefits the precision of the depth map. Applicable, whenever the extend of the object + to inspect is known and hence the near clip plane can safely be placed just in front of it. + * `f64`-ready for large worlds (e.g., solar system scale) whenever Bevy is, see issue [#1680]. + +[#1680]: https://github.com/bevyengine/bevy/issues/1680 + +See the [release history](RELEASES.md) to keep track of the development. + +## Input Mappings + +Following mappings are the defaults which can be customized, see [`TrackballInput`]. + +Mouse (Buttons) | Touch (Fingers) | Keyboard | Operation +----------------------- | ----------------------- | -------- | --------------------------------- +Left Press + Drag | One + Drag | `ijkl` | Orbits around target. +↳ at trackball's border | Two + Roll | `uo` | Rolls about view direction. +Middle Press + Drag | Any + Drag + Left Shift | `↑←↓→` | First person view. +Right Press + Drag | Two + Drag | `esdf` | Slides trackball on focus plane. +  |   | `gv` | Slides trackball in/out. +Scroll In/Out | Two + Pinch Out/In | `hn` | Scales distance zooming in/out. +Left Press + Release | Any + Release |   | Slides to cursor/finger position. +  |   | `p` | Toggle orthographic/perspective. +  |   | `Return` | Reset camera transform. + +[`TrackballInput`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballInput.html + +## Usage + +Add the [`TrackballPlugin`] followed by spawning a [`TrackballController`] together with a +[`TrackballCamera`] and a `Camera3dBundle` or see simple and advanced [examples]. + +```rust +use bevy::prelude::*; +use bevy_trackball::prelude::*; + +// Add the trackball plugin. +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_plugins(TrackballPlugin) + .add_systems(Startup, setup) + .run(); +} + +// Add a trackball controller and trackball camera to a camera 3D bundle. +fn setup(mut commands: Commands) { + let [target, eye, up] = [Vec3::ZERO, Vec3::Z * 10.0, Vec3::Y]; + commands.spawn(( + TrackballController::default(), + TrackballCamera::look_at(target, eye, up), + Camera3dBundle::default(), + )); + + // Set up your scene... +} +``` + +[`TrackballPlugin`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballPlugin.html +[`TrackballController`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballController.html +[`TrackballCamera`]: https://docs.rs/bevy_trackball/latest/bevy_trackball/struct.TrackballCamera.html +[`Camera3dBundle`]: https://docs.rs/bevy/latest/bevy/core_pipeline/core_3d/struct.Camera3dBundle.html + +[examples]: https://qu1x.github.io/bevy_trackball/examples +[`exponential_map`]: https://qu1x.github.io/bevy_trackball/examples/exponential_map.html +[`gliding_clamp`]: https://qu1x.github.io/bevy_trackball/examples/gliding_clamp.html +[`constellation_clamp`]: https://qu1x.github.io/bevy_trackball/examples/constellation_clamp.html +[`egui`]: https://qu1x.github.io/bevy_trackball/examples/egui.html +[`scaling_modes`]: https://github.com/qu1x/bevy_trackball/blob/main/examples/scaling_modes.rs + +# License + +Copyright © 2023 Rouven Spreckels + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSES/Apache-2.0](LICENSES/Apache-2.0) or + https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSES/MIT](LICENSES/MIT) or https://opensource.org/licenses/MIT) + +at your option. + +# Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in +this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without +any additional terms or conditions. diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 0000000000..51ca5a51d4 --- /dev/null +++ b/RELEASES.md @@ -0,0 +1,3 @@ +# Version 0.1.0 (2023-08-19) + + * Initial release. diff --git a/examples/constellation_clamp.rs b/examples/constellation_clamp.rs new file mode 100644 index 0000000000..c877d0e8af --- /dev/null +++ b/examples/constellation_clamp.rs @@ -0,0 +1,233 @@ +//! Demonstrates rigid as well as loose constellation clamp on the ground plane. +//! +//! 1. There is a main viewport (maximap) and a minimap at the right bottom. +//! 2. Both have their own trackball controller. +//! 3. The minimap is additionally sensitive to the controller of the maximap. +//! 5. When orbiting the maximap down by pressing `k`, it will stop as soon as the initially lower +//! positioned minimap camera hits the ground plane. +//! 6. Toggling from rigid to loose constellation clamp by pressing `Space` while keeping `k` +//! pressed allows the maximap camera to orbit further until it hits the ground by itself. +//! 7. Press `Return` to reset camera positions and try again. + +#![allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)] + +use std::f32::consts::PI; + +use bevy::{ + core_pipeline::clear_color::ClearColorConfig, + prelude::*, + render::{ + camera::Viewport, + render_resource::{Extent3d, TextureDimension, TextureFormat}, + }, + window::WindowResized, +}; +use bevy_trackball::prelude::*; + +fn main() { + App::new() + .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) + .add_plugins(TrackballPlugin) + .add_systems(Startup, setup) + .add_systems(Update, resize_minimap) + .add_systems(Update, toggle_rigid_loose) + .run(); +} + +/// A marker component for our shapes so we can query them separately from the ground plane +#[derive(Component)] +struct Shape; + +const X_EXTENT: f32 = 14.5; + +fn setup( + windows: Query<&Window>, + mut commands: Commands, + mut meshes: ResMut>, + mut images: ResMut>, + mut materials: ResMut>, +) { + let debug_material = materials.add(StandardMaterial { + base_color_texture: Some(images.add(uv_debug_texture())), + ..default() + }); + + let shapes = [ + meshes.add(shape::Cube::default().into()), + meshes.add(shape::Box::default().into()), + meshes.add(shape::Capsule::default().into()), + meshes.add(shape::Torus::default().into()), + meshes.add(shape::Cylinder::default().into()), + meshes.add(shape::Icosphere::default().try_into().unwrap()), + meshes.add(shape::UVSphere::default().into()), + ]; + + let num_shapes = shapes.len(); + + for (i, shape) in shapes.into_iter().enumerate() { + commands.spawn(( + PbrBundle { + mesh: shape, + material: debug_material.clone(), + transform: Transform::from_xyz( + (i as f32 / (num_shapes - 1) as f32).mul_add(X_EXTENT, -X_EXTENT / 2.), + 3.0, + 0.0, + ) + .with_rotation(Quat::from_rotation_x(-PI / 4.)), + ..default() + }, + Shape, + )); + } + + // ground plane + commands.spawn(PbrBundle { + mesh: meshes.add(shape::Plane::from_size(50.0).into()), + material: materials.add(Color::SILVER.into()), + ..default() + }); + // light + commands.spawn(PointLightBundle { + point_light: PointLight { + intensity: 9000.0, + range: 100., + shadows_enabled: true, + ..default() + }, + transform: Transform::from_xyz(8.0, 16.0, 8.0), + ..default() + }); + // UI + commands.spawn( + TextBundle::from_section( + "Rigid Constellation Clamp (Toggle: Space)", + TextStyle { + font_size: 18.0, + color: Color::WHITE, + ..default() + }, + ) + .with_style(Style { + position_type: PositionType::Absolute, + bottom: Val::Px(10.0), + left: Val::Px(10.0), + ..default() + }), + ); + // cameras and boundary conditions + let mut bound = Bound::default(); + bound.min_target[1] = 0.0; + bound.min_eye[1] = 0.3; + bound.min_distance = 6.0; + bound.max_distance = 50.0; + let [target, eye, up] = [Vec3::Y, Vec3::new(0.0, 9.0, 12.0), Vec3::Y]; + let maximap = commands + .spawn(( + TrackballController::default(), + TrackballCamera::look_at(target, eye, up).with_clamp(bound.clone()), + Camera3dBundle::default(), + )) + .id(); + let window = windows.single(); + let size = window.resolution.physical_width() / 4; + let eye = Vec3::new(0.0, 3.0, 12.0); + commands.spawn(( + TrackballController::default(), + TrackballCamera::look_at(target, eye, Vec3::Y) + .with_clamp(bound) + .add_controller(maximap, true), + Camera3dBundle { + camera: Camera { + order: 1, + viewport: Some(Viewport { + physical_position: UVec2::new( + window.resolution.physical_width() - size, + window.resolution.physical_height() - size, + ), + physical_size: UVec2::new(size, size), + ..default() + }), + ..default() + }, + camera_3d: Camera3d { + clear_color: ClearColorConfig::None, + ..default() + }, + ..default() + }, + MinimapCamera, + )); +} + +#[derive(Component)] +struct MinimapCamera; + +#[allow(clippy::needless_pass_by_value)] +fn resize_minimap( + windows: Query<&Window>, + mut resize_events: EventReader, + mut minimap: Query<&mut Camera, With>, +) { + for resize_event in &mut resize_events { + let window = windows.get(resize_event.window).unwrap(); + let mut minimap = minimap.single_mut(); + let size = window.resolution.physical_width() / 4; + minimap.viewport = Some(Viewport { + physical_position: UVec2::new( + window.resolution.physical_width() - size, + window.resolution.physical_height() - size, + ), + physical_size: UVec2::new(size, size), + ..default() + }); + } +} + +#[allow(clippy::needless_pass_by_value)] +fn toggle_rigid_loose( + mut minimap: Query<&mut TrackballCamera, With>, + mut text: Query<&mut Text>, + keycode: Res>, +) { + if keycode.just_pressed(KeyCode::Space) { + let mut text = text.single_mut(); + let text = &mut text.sections[0].value; + let mut minimap = minimap.single_mut(); + let rigid = minimap.group.values_mut().next().unwrap(); + if *rigid { + *text = "Loose Constellation Clamp (Toggle: Space)".to_owned(); + } else { + *text = "Rigid Constellation Clamp (Toggle: Space)".to_owned(); + } + *rigid = !*rigid; + } +} + +/// Creates a colorful test pattern +fn uv_debug_texture() -> Image { + const TEXTURE_SIZE: usize = 8; + + let mut palette: [u8; 32] = [ + 255, 102, 159, 255, 255, 159, 102, 255, 236, 255, 102, 255, 121, 255, 102, 255, 102, 255, + 198, 255, 102, 198, 255, 255, 121, 102, 255, 255, 236, 102, 255, 255, + ]; + + let mut texture_data = [0; TEXTURE_SIZE * TEXTURE_SIZE * 4]; + for y in 0..TEXTURE_SIZE { + let offset = TEXTURE_SIZE * y * 4; + texture_data[offset..(offset + TEXTURE_SIZE * 4)].copy_from_slice(&palette); + palette.rotate_right(4); + } + + Image::new_fill( + Extent3d { + width: TEXTURE_SIZE as u32, + height: TEXTURE_SIZE as u32, + depth_or_array_layers: 1, + }, + TextureDimension::D2, + &texture_data, + TextureFormat::Rgba8UnormSrgb, + ) +} diff --git a/examples/egui.rs b/examples/egui.rs new file mode 100644 index 0000000000..ebad63044d --- /dev/null +++ b/examples/egui.rs @@ -0,0 +1,266 @@ +//! Demonstrates viewport stealing to share input with egui. + +use std::f32::consts::PI; + +use bevy::{ + core_pipeline::clear_color::ClearColorConfig, + prelude::*, + render::{ + camera::RenderTarget, + render_resource::{ + Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, + }, + view::RenderLayers, + }, +}; +use bevy_egui::{egui, EguiContexts, EguiPlugin, EguiUserTextures}; +use bevy_trackball::prelude::*; +use egui::Widget; + +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_plugins(TrackballPlugin) + .add_plugins(EguiPlugin) + .add_systems(Startup, setup) + .add_systems(Update, render_to_image_example_system) + .add_systems( + Update, + camera_attached_light.after(TrackballSystemSet::Camera), + ) + .run(); +} + +// Marks the preview pass cube. +#[derive(Component)] +struct PreviewPassCube; + +// Marks the main pass cube, to which the material is applied. +#[derive(Component)] +struct MainPassCube; + +#[derive(Deref, Resource)] +struct CubePreviewImage(Handle); + +fn setup( + mut egui_user_textures: ResMut, + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, + mut images: ResMut>, +) { + let size = Extent3d { + width: 512, + height: 512, + ..default() + }; + + // This is the texture that will be rendered to. + let mut image = Image { + texture_descriptor: TextureDescriptor { + label: None, + size, + dimension: TextureDimension::D2, + format: TextureFormat::Bgra8UnormSrgb, + mip_level_count: 1, + sample_count: 1, + usage: TextureUsages::TEXTURE_BINDING + | TextureUsages::COPY_DST + | TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }, + ..default() + }; + + // fill image.data with zeroes + image.resize(size); + + let image_handle = images.add(image); + egui_user_textures.add_image(image_handle.clone()); + commands.insert_resource(CubePreviewImage(image_handle.clone())); + + // Transform of cubes. + let cube_transform = Transform { + rotation: Quat::from_rotation_x(-PI / 5.0), + ..default() + }; + + let cube_handle = meshes.add(Mesh::from(shape::Cube { size: 4.0 })); + let default_material = StandardMaterial { + base_color: Color::rgb(0.8, 0.7, 0.6), + reflectance: 0.02, + unlit: false, + ..default() + }; + let preview_material_handle = materials.add(default_material.clone()); + + // This specifies the layer used for the preview pass, which will be attached to the preview + // pass camera and cube. + let preview_pass_layer = RenderLayers::layer(1); + + // The cube that will be rendered to the texture. + commands + .spawn(PbrBundle { + mesh: cube_handle, + material: preview_material_handle, + transform: cube_transform, + ..default() + }) + .insert(PreviewPassCube) + .insert(preview_pass_layer); + + // Cube parameters. + let cube_size = 4.0; + let cube_handle = meshes.add(Mesh::from(shape::Box::new(cube_size, cube_size, cube_size))); + + // Main pass cube. + let main_material_handle = materials.add(default_material); + commands + .spawn(PbrBundle { + mesh: cube_handle, + material: main_material_handle, + transform: cube_transform, + ..default() + }) + .insert(MainPassCube); + + // Defines initial transform of cameras and light. + let target = Vec3::new(0.0, 0.0, 0.0); + let eye = Vec3::new(0.0, 0.0, 15.0); + let up = Vec3::Y; + + // Light + // + // NOTE: Currently lights are shared between passes, + // see https://github.com/bevyengine/bevy/issues/3462 + commands.spawn(SpotLightBundle { + transform: Transform::from_xyz(eye.x, eye.y, eye.z).looking_at(target, up), + spot_light: SpotLight { + intensity: 4400.0, // lumens + range: 100.0, + color: Color::WHITE, + shadows_enabled: true, + inner_angle: PI / 4.0 * 0.85, + outer_angle: PI / 4.0, + ..default() + }, + ..default() + }); + + // The main pass camera with controller. + let controller = commands + .spawn(( + Camera3dBundle::default(), + TrackballController::default(), + TrackballCamera::look_at(target, eye, up), + )) + .id(); + + // UI camera sensitive to main pass camera's `controller`. + commands + .spawn(( + Camera3dBundle { + camera_3d: Camera3d { + clear_color: ClearColorConfig::Custom(Color::rgba(1.0, 1.0, 1.0, 0.0)), + ..default() + }, + camera: Camera { + // render before the "main pass" camera + order: -1, + target: RenderTarget::Image(image_handle), + ..default() + }, + ..default() + }, + TrackballCamera::look_at(target, eye, up).add_controller(controller, true), + )) + .insert(preview_pass_layer); +} + +fn render_to_image_example_system( + cube_preview_image: Res, + preview_cube_query: Query<&Handle, With>, + main_cube_query: Query<&Handle, With>, + mut materials: ResMut>, + mut contexts: EguiContexts, +) { + let cube_preview_texture_id = contexts.image_id(&cube_preview_image).unwrap(); + let preview_material_handle = preview_cube_query.single(); + let preview_material = materials.get_mut(preview_material_handle).unwrap(); + + let ctx = contexts.ctx_mut(); + let mut apply = false; + egui::Window::new("Cube material preview").show(ctx, |ui| { + ui.image(cube_preview_texture_id, [300.0, 300.0]); + egui::Grid::new("preview").show(ui, |ui| { + ui.label("Base color:"); + color_picker_widget(ui, &mut preview_material.base_color); + ui.end_row(); + + ui.label("Emissive:"); + color_picker_widget(ui, &mut preview_material.emissive); + ui.end_row(); + + ui.label("Perceptual roughness:"); + egui::Slider::new(&mut preview_material.perceptual_roughness, 0.089..=1.0).ui(ui); + ui.end_row(); + + ui.label("Reflectance:"); + egui::Slider::new(&mut preview_material.reflectance, 0.0..=1.0).ui(ui); + ui.end_row(); + + ui.label("Unlit:"); + ui.checkbox(&mut preview_material.unlit, ""); + ui.end_row(); + }); + + apply = ui.button("Apply").clicked(); + }); + + if apply { + let material_clone = preview_material.clone(); + + let main_material_handle = main_cube_query.single(); + let _ = materials.set(main_material_handle, material_clone); + } +} + +fn color_picker_widget(ui: &mut egui::Ui, color: &mut Color) -> egui::Response { + let [r, g, b, a] = color.as_rgba_f32(); + let mut egui_color: egui::Rgba = egui::Rgba::from_srgba_unmultiplied( + (r * 255.0) as u8, + (g * 255.0) as u8, + (b * 255.0) as u8, + (a * 255.0) as u8, + ); + let res = egui::widgets::color_picker::color_edit_button_rgba( + ui, + &mut egui_color, + egui::color_picker::Alpha::Opaque, + ); + let [r, g, b, a] = egui_color.to_srgba_unmultiplied(); + *color = [ + r as f32 / 255.0, + g as f32 / 255.0, + b as f32 / 255.0, + a as f32 / 255.0, + ] + .into(); + res +} + +fn camera_attached_light( + camera_transform: Query< + &Transform, + ( + Changed, + With, + Without, + ), + >, + mut light_transform: Query<&mut Transform, With>, +) { + if let Ok(camera_transform) = camera_transform.get_single() { + *light_transform.single_mut() = *camera_transform; + } +} diff --git a/examples/exponential_map.rs b/examples/exponential_map.rs new file mode 100644 index 0000000000..67cfc7adad --- /dev/null +++ b/examples/exponential_map.rs @@ -0,0 +1,62 @@ +//! A simple 3D scene with light shining over a cube sitting on a plane and a trackball camera +//! waiting for your input to orbit around. +//! +//! This is an alternative trackball technique using exponential map and parallel transport to +//! preserve distances and angles for inducing coherent and intuitive trackball rotations. For +//! instance, displacements on straight radial lines through the screen’s center are carried to arcs +//! of the same length on great circles of the trackball (e.g., dragging the mouse along an eights +//! of the trackball's circumference rolls the camera by 360/8=45 degrees, dragging the mouse from +//! the screen's center to its further edge *linearly* rotates the camera by 1 [radian], where the +//! trackball's diameter is the maximum of the screen's width and height). This is in contrast to +//! state-of-the-art techniques using orthogonal projection which distorts radial distances further +//! away from the screen’s center (e.g., the rotation accelerates towards the edge). +//! +//! [radian]: https://en.wikipedia.org/wiki/Radian + +use bevy::prelude::*; +use bevy_trackball::prelude::*; + +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_plugins(TrackballPlugin) + .add_systems(Startup, setup) + .run(); +} + +/// set up a simple 3D scene +fn setup( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + // plane + commands.spawn(PbrBundle { + mesh: meshes.add(shape::Plane::from_size(5.0).into()), + material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()), + ..default() + }); + // cube + commands.spawn(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(0.0, 0.5, 0.0), + ..default() + }); + // light + commands.spawn(PointLightBundle { + point_light: PointLight { + intensity: 1500.0, + shadows_enabled: true, + ..default() + }, + transform: Transform::from_xyz(4.0, 8.0, 4.0), + ..default() + }); + // camera + commands.spawn(( + TrackballController::default(), + TrackballCamera::look_at(Vec3::Y * 0.25, Vec3::new(-2.0, 2.5, 5.0), Vec3::Y), + Camera3dBundle::default(), + )); +} diff --git a/examples/gliding_clamp.rs b/examples/gliding_clamp.rs new file mode 100644 index 0000000000..6861a1072b --- /dev/null +++ b/examples/gliding_clamp.rs @@ -0,0 +1,127 @@ +//! Demonstrates gliding on the ground plane (currently, only implemented for orbit and slide +//! operations). + +#![allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)] + +use std::f32::consts::PI; + +use bevy::{ + prelude::*, + render::render_resource::{Extent3d, TextureDimension, TextureFormat}, +}; +use bevy_trackball::prelude::*; + +fn main() { + App::new() + .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) + .add_plugins(TrackballPlugin) + .add_systems(Startup, setup) + .run(); +} + +/// A marker component for our shapes so we can query them separately from the ground plane +#[derive(Component)] +struct Shape; + +const X_EXTENT: f32 = 14.5; + +fn setup( + mut commands: Commands, + mut meshes: ResMut>, + mut images: ResMut>, + mut materials: ResMut>, +) { + let debug_material = materials.add(StandardMaterial { + base_color_texture: Some(images.add(uv_debug_texture())), + ..default() + }); + + let shapes = [ + meshes.add(shape::Cube::default().into()), + meshes.add(shape::Box::default().into()), + meshes.add(shape::Capsule::default().into()), + meshes.add(shape::Torus::default().into()), + meshes.add(shape::Cylinder::default().into()), + meshes.add(shape::Icosphere::default().try_into().unwrap()), + meshes.add(shape::UVSphere::default().into()), + ]; + + let num_shapes = shapes.len(); + + for (i, shape) in shapes.into_iter().enumerate() { + commands.spawn(( + PbrBundle { + mesh: shape, + material: debug_material.clone(), + transform: Transform::from_xyz( + (i as f32 / (num_shapes - 1) as f32).mul_add(X_EXTENT, -X_EXTENT / 2.), + 3.0, + 0.0, + ) + .with_rotation(Quat::from_rotation_x(-PI / 4.)), + ..default() + }, + Shape, + )); + } + + // ground plane + commands.spawn(PbrBundle { + mesh: meshes.add(shape::Plane::from_size(50.0).into()), + material: materials.add(Color::SILVER.into()), + ..default() + }); + // light + commands.spawn(PointLightBundle { + point_light: PointLight { + intensity: 9000.0, + range: 100., + shadows_enabled: true, + ..default() + }, + transform: Transform::from_xyz(8.0, 16.0, 8.0), + ..default() + }); + // camera + let [target, eye, up] = [Vec3::Y, Vec3::new(0.0, 6.0, 12.0), Vec3::Y]; + commands.spawn(( + TrackballController::default(), + TrackballCamera::look_at(target, eye, up).with_clamp({ + let mut bound = Bound::default(); + bound.min_target[1] = 0.0; + bound.min_eye[1] = 0.3; + bound.min_distance = 6.0; + bound.max_distance = 50.0; + bound + }), + Camera3dBundle::default(), + )); +} + +/// Creates a colorful test pattern +fn uv_debug_texture() -> Image { + const TEXTURE_SIZE: usize = 8; + + let mut palette: [u8; 32] = [ + 255, 102, 159, 255, 255, 159, 102, 255, 236, 255, 102, 255, 121, 255, 102, 255, 102, 255, + 198, 255, 102, 198, 255, 255, 121, 102, 255, 255, 236, 102, 255, 255, + ]; + + let mut texture_data = [0; TEXTURE_SIZE * TEXTURE_SIZE * 4]; + for y in 0..TEXTURE_SIZE { + let offset = TEXTURE_SIZE * y * 4; + texture_data[offset..(offset + TEXTURE_SIZE * 4)].copy_from_slice(&palette); + palette.rotate_right(4); + } + + Image::new_fill( + Extent3d { + width: TEXTURE_SIZE as u32, + height: TEXTURE_SIZE as u32, + depth_or_array_layers: 1, + }, + TextureDimension::D2, + &texture_data, + TextureFormat::Rgba8UnormSrgb, + ) +} diff --git a/examples/scaling_modes.rs b/examples/scaling_modes.rs new file mode 100644 index 0000000000..7b2ce28f18 --- /dev/null +++ b/examples/scaling_modes.rs @@ -0,0 +1,211 @@ +//! Renders two cameras to the same window to accomplish *split screen*. The left camera +//! uses perspective projection whereas the right camera uses orthographic projection. Spawns three +//! windows each with different scaling modes regarding window resize events: +//! +//! 1. window with fixed vertical field of view. +//! 2. window with fixed horizontal field of view. +//! 3. window with fixed unit per pixels. + +#![allow(clippy::similar_names)] + +use bevy::{ + core_pipeline::clear_color::ClearColorConfig, + prelude::*, + render::camera::{RenderTarget, Viewport}, + window::{PrimaryWindow, WindowRef, WindowResized}, +}; +use bevy_trackball::prelude::*; + +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_plugins(TrackballPlugin) + .add_systems(Startup, setup) + .add_systems(Update, set_camera_viewports) + .run(); +} + +/// set up a simple 3D scene +fn setup( + mut windows: Query<&mut Window>, + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + // Plane + commands.spawn(PbrBundle { + mesh: meshes.add(shape::Plane::from_size(5.0).into()), + material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()), + ..default() + }); + // Cube + commands.spawn(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(0.0, 0.5, 0.0), + ..default() + }); + // Light + commands.spawn(PointLightBundle { + point_light: PointLight { + intensity: 1500.0, + shadows_enabled: true, + ..default() + }, + transform: Transform::from_xyz(4.0, 8.0, 4.0), + ..default() + }); + + // Windows + let mut window1 = windows.single_mut(); + window1.title = "Fixed Vertical Field of View (Perspective vs Orthographic)".to_owned(); + let res = &window1.resolution; + let max = Vec2::new(res.width() * 0.5, res.height()).into(); + // Left and right camera orientation. + let [target, eye, up] = [Vec3::Y * 0.25, Vec3::new(-2.0, 2.5, 5.0), Vec3::Y]; + // Spawn a 2nd window. + let window2 = commands + .spawn(Window { + title: "Fixed Horizontal Field of View (Perspective vs Orthographic)".to_owned(), + ..default() + }) + .id(); + // Spawn a 3rd window. + let window3 = commands + .spawn(Window { + title: "Fixed Unit Per Pixels (Perspective vs Orthographic)".to_owned(), + ..default() + }) + .id(); + + // Cameras + let mut order = 0; + let fov = Fixed::default(); + for (fov, window) in [ + (fov, WindowRef::Primary), + (fov.to_hor(&max), WindowRef::Entity(window2)), + (fov.to_upp(&max), WindowRef::Entity(window3)), + ] { + let mut scope = Scope::default(); + scope.set_fov(fov); + // Left trackball controller and camera 3D bundle. + let left = commands + .spawn(( + TrackballController::default(), + Camera3dBundle { + camera: Camera { + target: RenderTarget::Window(window), + // Renders the right camera after the left camera, + // which has a default priority of 0. + order, + ..default() + }, + ..default() + }, + LeftCamera, + )) + .id(); + order += 1; + // Right trackball controller and camera 3D bundle. + let right = commands + .spawn(( + TrackballController::default(), + Camera3dBundle { + camera: Camera { + target: RenderTarget::Window(window), + // Renders the right camera after the left camera, + // which has a default priority of 0. + order, + ..default() + }, + camera_3d: Camera3d { + // Don't clear on the second camera + // because the first camera already cleared the window. + clear_color: ClearColorConfig::None, + ..default() + }, + ..default() + }, + RightCamera, + )) + .id(); + order += 1; + // Insert left trackball camera and make it sensitive to right trackball controller as well. + commands.entity(left).insert( + TrackballCamera::look_at(target, eye, up) + .with_scope(scope) + .add_controller(right, true), + ); + // Set orthographic projection mode for right camera. + scope.set_ortho(true); + // Insert right trackball camera and make it sensitive to left trackball controller as well. + commands.entity(right).insert( + TrackballCamera::look_at(target, eye, up) + .with_scope(scope) + .add_controller(left, true), + ); + } +} + +#[derive(Component)] +struct LeftCamera; + +#[derive(Component)] +struct RightCamera; + +#[allow(clippy::needless_pass_by_value)] +fn set_camera_viewports( + primary_windows: Query<(Entity, &Window), With>, + windows: Query<(Entity, &Window)>, + mut resize_events: EventReader, + mut left_cameras: Query<&mut Camera, (With, Without)>, + mut right_cameras: Query<&mut Camera, With>, +) { + // We need to dynamically resize the camera's viewports whenever the window size changes, + // so then each camera always takes up half the screen. A `resize_event` is sent when the window + // is first created, allowing us to reuse this system for initial setup. + for resize_event in &mut resize_events { + let (resize_entity, resize_window) = windows.get(resize_event.window).unwrap(); + let resolution = &resize_window.resolution; + for mut left_camera in &mut left_cameras { + if let RenderTarget::Window(window_ref) = left_camera.target { + let Some((target_entity, _target_window)) = (match window_ref { + WindowRef::Primary => primary_windows.get_single().ok(), + WindowRef::Entity(entity) => windows.get(entity).ok(), + }) else { + continue; + }; + if target_entity == resize_entity { + left_camera.viewport = Some(Viewport { + physical_position: UVec2::new(0, 0), + physical_size: UVec2::new( + resolution.physical_width() / 2, + resolution.physical_height(), + ), + ..default() + }); + } + } + } + for mut right_camera in &mut right_cameras { + if let RenderTarget::Window(window_ref) = right_camera.target { + let Some((target_entity, _target_window)) = (match window_ref { + WindowRef::Primary => primary_windows.get_single().ok(), + WindowRef::Entity(entity) => windows.get(entity).ok(), + }) else { + continue; + }; + if target_entity == resize_entity { + right_camera.viewport = Some(Viewport { + physical_position: UVec2::new(resolution.physical_width() / 2, 0), + physical_size: UVec2::new( + resolution.physical_width() / 2, + resolution.physical_height(), + ), + ..default() + }); + } + } + } + } +} diff --git a/examples/wasm/Makefile b/examples/wasm/Makefile new file mode 100644 index 0000000000..97a23d28e1 --- /dev/null +++ b/examples/wasm/Makefile @@ -0,0 +1,63 @@ +EXAMPLES := exponential_map gliding_clamp constellation_clamp egui + +.PHONY: help +help: + @printf "make install Installs required tools.\n" + @printf "make wasm -j Builds optimized WASM examples.\n" + @printf "make serve Runs local HTTP server.\n" + @printf "make clean Removes ./target directory.\n" + +.PHONY: install +install: + command -v apt && sudo apt install binaryen || true + command -v dnf && sudo dnf install binaryen || true + command -v yum && sudo yum install binaryen || true + command -v pacman && sudo pacman -S --needed binaryen || true + rustup target add wasm32-unknown-unknown + cargo install wasm-bindgen-cli basic-http-server + +.PHONY: wasm +wasm: $(EXAMPLES:%=target/%.wasm) + +target: + mkdir -p target + ln -sf $(word 1,$(EXAMPLES)).html target/index.html + +.PHONY: build +build: | target + @for example in $(EXAMPLES); do \ + printf " \033[1;32mChecking\033[0m $$example(example)\n"; \ + features=$$(cargo metadata --no-deps --format-version 1 | \ + jq --raw-output ".packages[] | select(.name==\"bevy_trackball\") | .targets[] | \ + select(.name==\"$$example\") | .\"required-features\" | join(\",\")"); \ + cargo build --profile wasm-release --target wasm32-unknown-unknown \ + --features $${features:-,} --example $$example; \ + jq -Rr @html ../../examples/$$example.rs > target/$$example.code; \ + sed -e 's/{EXAMPLE}/'$$example'/g' -e '/{SOURCE}/{r target/'$$example.code -e 'd}' \ + example.html > target/$$example.html; \ + done + +../../target/wasm32-unknown-unknown/wasm-release/examples/%.wasm: | build + @true + +target/%_bg.wasm: ../../target/wasm32-unknown-unknown/wasm-release/examples/%.wasm + @printf " \033[1;32mBinding\033[0m $*(example)\n"; \ + wasm-bindgen --target web --out-dir target --out-name $* $< + +target/%.wasm: target/%_bg.wasm + @printf " \033[1;32mOptimizing\033[0m $*(example)\n"; \ + mv $< $@ + wasm-opt -Oz --output $< $@ + touch $@ + +.PHONY: +serve: wasm + @printf " \033[1;32mServing\033[0m examples\n"; \ + basic-http-server target + +.PHONY: clean +clean: + rm -rf -- target + +.SECONDARY: +Makefile:; diff --git a/examples/wasm/example.html b/examples/wasm/example.html new file mode 100644 index 0000000000..ab4d43b522 --- /dev/null +++ b/examples/wasm/example.html @@ -0,0 +1,113 @@ + + + + + + + + + + bevy_trackball/examples/{EXAMPLE}.rs + + + + +
+ +
+				
+					{SOURCE}
+				
+			
+
+ + + diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000000..bca63a558d --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,4 @@ +hard_tabs = true +max_width = 100 +format_code_in_doc_comments = true +group_imports = "StdExternalCrate" diff --git a/src/camera.rs b/src/camera.rs new file mode 100644 index 0000000000..902f214492 --- /dev/null +++ b/src/camera.rs @@ -0,0 +1,172 @@ +use std::collections::HashMap; + +use bevy::{prelude::*, render::camera::ScalingMode, transform::components::Transform}; +use trackball::{approx::AbsDiffEq, nalgebra::Point2, Clamp, Delta, Fixed, Frame, Scope}; + +/// Trackball camera component mainly defined by [`Frame`] and [`Scope`]. +#[derive(Component, Debug)] +pub struct TrackballCamera { + /// Camera frame defining [`Transform`]. + /// + /// Comprises following properties: + /// + /// * target position as trackball center + /// * camera eye rotation on trackball surface (incl. roll, gimbal lock-free using quaternion) + /// * trackball radius + pub frame: Frame, + old_frame: Frame, + /// Camera scope defining [`Projection`]. + /// + /// Comprises following properties: + /// + /// * field of view angle (default is 45 degrees) and its mode of either [`Fixed::Ver`] + /// (default), [`Fixed::Hor`], or [`Fixed::Upp`]. + /// * projection mode of either perspective (default) or orthographic (scale preserving) + /// * clip planes either measured from eye (default) or target (object inspection mode) + pub scope: Scope, + old_scope: Scope, + old_max: Point2, + /// Blend ratio between 0 (slow) and 1 (fast) for exponential easy-out. Default is `0.25`. + /// + /// Blend ratio aka sharpness or Lerp/Slerp parameter `t` is exponentially corrected for + /// deviations from reference frame rate of 60 fps. + pub blend: f32, + /// Camera frame to reset to when [`TrackballInput::reset_key`] is pressed. + /// + /// [`TrackballInput::reset_key`]: crate::TrackballInput::reset_key + pub reset: Frame, + /// User boundary conditions clamping camera [`Frame`]. + /// + /// Allows to limit target/eye position or minimal/maximal target/eye distance or up rotation. + pub clamp: Option>>, + pub(crate) delta: Option>, + /// Additional [`TrackballController`] entities to which this camera is sensitive. + /// + /// It is always sensitive to its own controller if it has one. A mapped value of `true` will + /// clamp the active controller as well and hence all other cameras of this group whenever this + /// camera is clamped. If `false`, only this camera is clamped whereas other cameras of this + /// group continue to follow the active controller. + /// + /// [`TrackballController`]: crate::TrackballController + /// [`TrackballEvent`]: crate::TrackballEvent + pub group: HashMap, +} + +impl TrackballCamera { + /// Defines camera with `target` position and `eye` position inclusive its roll attitude (`up`). + #[must_use] + pub fn look_at(target: Vec3, eye: Vec3, up: Vec3) -> Self { + let frame = Frame::look_at(target.into(), &eye.into(), &up.into()); + Self { + frame, + old_frame: Frame::default(), + scope: Scope::default(), + old_scope: Scope::default(), + old_max: Point2::default(), + blend: 0.25, + reset: frame, + clamp: None, + delta: None, + group: HashMap::default(), + } + } + /// Defines scope, see [`Self::scope`]. + #[must_use] + #[allow(clippy::type_complexity)] + pub const fn with_scope(mut self, scope: Scope) -> Self { + self.scope = scope; + self + } + /// Defines blend ratio, see [`Self::blend`]. + #[must_use] + pub const fn with_blend(mut self, blend: f32) -> Self { + self.blend = blend; + self + } + /// Defines reset frame, see [`Self::reset`]. + #[must_use] + #[allow(clippy::type_complexity)] + pub const fn with_reset(mut self, reset: Frame) -> Self { + self.reset = reset; + self + } + /// Defines user boundary conditions, see [`Self::clamp`]. + #[must_use] + #[allow(clippy::type_complexity)] + pub fn with_clamp(mut self, clamp: impl Clamp) -> Self { + self.clamp = Some(Box::new(clamp)); + self + } + /// Adds additional controller to which this camera is sensitive, see [`Self::group`]. + #[must_use] + pub fn add_controller(mut self, id: Entity, rigid: bool) -> Self { + self.group.insert(id, rigid); + self + } +} + +#[allow(clippy::needless_pass_by_value)] +pub fn trackball_camera( + time: Res