mirror of
https://github.com/storytold/storyteller-bevy.git
synced 2026-10-17 00:13:17 +00:00
Transform gizmos (#10)
This PR adds functional transform gizmos, along with some new frontend UI to configure their state. ## Work Done - [x] Global / Local space toggling - [x] Gizmo type toggling - [x] Translation gizmo - [x] Axis-constrained translation - [x] Plane-constrained translation - [x] Screen-space translation - [x] Rotation gizmo - [x] Axis-constrained rotation - [x] Screen-space rotation - [x] "Trackball" rotation - [ ] Scale gizmo - [ ] Single-axis non-uniform scaling - [ ] Two-axis non-uniform scaling - [ ] Uniform scaling - [ ] Combination gizmos - [x] Translation + Rotation - [ ] Translation + Scale - [ ] Rotation + Scale - [ ] Translation + Rotation + Scale ## Future Enhancements ### Better visual feedback during transformations Most DCCs update the visual representation of the transform gizmo while it's in the process of being actively manipulated. (For example, Blender draws lines in world-space to indicate that the transformation is constrained to a particular axis or plane, hides widgets that aren't participating in the current transformation, and illustrates the angle of difference between the original and updated rotation.) At a minimum, we should indicate the current widget being manipulated with a color change (like we already do when the widget is being hovered). This requires a bit of additional state management effort but shouldn't be overly difficult to add in a future PR. ### Better visual representation for rotation widgets Currently, each axis of rotation is represented on the gizmo with a full-circle, unlit "ring" shape. This can make it difficult to tell which half of the ring is closer to the viewer, and thus to get an accurate understanding of how the transform is currently oriented, without moving the camera around. A [previous version of this work](#4) bisected the rings along a view-oriented plane and rendered the "back-side" ring halves with reduced opacity. This PR uses static meshes instead of an immediate-mode drawing API to render the gizmos, so a custom shader would be the ideal way to reproduce that effect. That effort should be deferred until after upgrading to Bevy 0.12, as it brings some changes which would likely require some updates to that code. ### Better visual representation for translation arrows A [previous version of this work](#4) faded the opacity of the translation arrows when they were very close to parallel with the view direction — an idea that was borrowed from Blender. It's a nice UX enhancement because translating along an axis that's very close to parallel with the view direction can be janky and error-prone, so it makes sense to disallow it and instead provide an unobstructed view of the screen-space translation widget. This would also require a custom shader, in addition to some extra state management logic (to disable the widgets when their opacity is zeroed out). Given that it's only a "nice-to-have," I think it makes sense to backlog this for the time being. ## Known Issues ### Picking There's currently a bug in `bevy_mod_picking` that affects the hit-testing of the gizmo widgets. The gizmos are currently _rendering_ on top of everything else (via a second camera and render-layer configurations), but the picking behavior doesn't take the rendering order into account. This means that portions of the gizmo widgets which are occluded by geometry in the world cannot be interacted with (because the occluding geometry interrupts the picking raycast). > Update: This is fixed in the new release of `bevy_mod_picking` for Bevy 0.12. ### Delay on first-render The first time a new widget shape is spawned, there's a noticeable delay (of 1 to several seconds) before the widget is rendered, during which the UI becomes unresponsive. This is likely the same issue that triggers a much longer delay when the glTF scene is being spawned. I'd like to see if Bevy 0.12 resolves or mitigates this issue before addressing it on our end, but if it doesn't, I think we can simply spawn an instance of each of the gizmo widgets off-screen on application startup to prevent lag spikes from happening while a user is interacting with the scene. ### Non-deterministic hover states The widget colors are currently being updated by, e.g., multiplying on mouser-over and dividing on mouse-out. Occasionally those events happen in quick enough succession that our mouse-out listener is not invoked, so a widget gets "stuck" in its hovered state. The fix for this is trivial but fairly annoying, so I haven't gotten around to it yet. 🙂 > Update: This issue mostly occurs when in world-space mode. The gizmo is torn > down and re-built from scratch once a drag event completes, which can despawn > the gizmo while an element is still hovered. The solution will likely involve > completely separate materials for default and hover states, similar to how > `bevy_mod_picking`'s highlight plugin works. ### Object Selection There's still some jank happening with object selection and camera orbiting, as mentioned in #8. I don't anticipate this being overly difficult to resolve, but I'm deferring that work until more of the core functionality is built out since it's not a blocker for now. ### Skinned Mesh Selection There's also still the issue of the skinned mesh being unselectable — which, it turns out, is [technically not actually the case](https://github.com/bevyengine/bevy/issues/4971). Rather, the picking raycast "sees" the mesh as if it were still in its original rest pose, because the mesh deformations are processed on the GPU and not reflected back to the CPU-side representation. I think the ideal workaround for this will be to attach capsule-shaped Rapier colliders to the skeleton (similar to Unreal Engine's auto-generated "physics assets" for skeletal meshes) and use those for picking instead. This would automatically enable skeletal pose manipulation (by transforming the individual joints), which is already a long term goal. It also makes more sense from a practical standpoint, as the mesh itself cannot be independently transformed while it's bound to the skeleton, so there's little point in directly selecting it.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
use bevy::{
|
||||
core_pipeline::{clear_color::ClearColorConfig, fxaa::Fxaa},
|
||||
prelude::*,
|
||||
render::view::RenderLayers,
|
||||
};
|
||||
|
||||
use crate::MainCamera;
|
||||
|
||||
use super::GIZMO_RENDER_LAYER;
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) struct GizmoCamera;
|
||||
|
||||
pub(super) fn spawn_gizmo_camera(
|
||||
mut cmd: Commands,
|
||||
q_main_camera: Query<Entity, With<MainCamera>>,
|
||||
) {
|
||||
let ent = q_main_camera.single();
|
||||
|
||||
cmd.entity(ent).with_children(|cmd| {
|
||||
cmd.spawn((
|
||||
Name::new("Gizmo Camera"),
|
||||
GizmoCamera,
|
||||
Camera3dBundle {
|
||||
camera_3d: Camera3d {
|
||||
clear_color: ClearColorConfig::None,
|
||||
..default()
|
||||
},
|
||||
camera: Camera {
|
||||
hdr: true,
|
||||
order: 1,
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
Fxaa::default(),
|
||||
));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use bevy::{math::vec3, pbr::NotShadowCaster, prelude::*, render::view::RenderLayers};
|
||||
use bevy_mod_picking::prelude::*;
|
||||
|
||||
use crate::interaction::TransformSpace;
|
||||
|
||||
use super::{
|
||||
on_gizmo_element_hover, on_gizmo_element_unhover,
|
||||
rotation::{on_rotate, on_rotation_end, on_rotation_start, RotationWidget},
|
||||
translation::{on_translate, on_translation_end, on_translation_start, TranslationWidget},
|
||||
GizmoMats, GizmoMeshes, TransformGizmoBundle, TransformGizmoRoot, GIZMO_RENDER_LAYER,
|
||||
};
|
||||
|
||||
#[inline]
|
||||
pub(super) fn spawn_combo_translation_rotation_gizmo(
|
||||
cmd: &mut Commands,
|
||||
ent: Entity,
|
||||
xform: &GlobalTransform,
|
||||
space: TransformSpace,
|
||||
normalizing_scale: f32,
|
||||
meshes: &GizmoMeshes,
|
||||
mats: &GizmoMats,
|
||||
) {
|
||||
cmd.entity(ent)
|
||||
.insert(TransformGizmoRoot)
|
||||
.with_children(|cmd| {
|
||||
cmd.spawn(TransformGizmoBundle::new(xform, space, normalizing_scale))
|
||||
.with_children(|cmd| {
|
||||
use super::{ROT_X, ROT_Y, ROT_Z};
|
||||
|
||||
// Center sphere
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::ScreenSpace,
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_ss.clone(),
|
||||
material: mats.translate_ss.clone(),
|
||||
transform: Transform::IDENTITY,
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_translation_start),
|
||||
On::<Pointer<Drag>>::run(on_translate),
|
||||
On::<Pointer<DragEnd>>::target_commands_mut(on_translation_end),
|
||||
));
|
||||
|
||||
// Rotate X
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_x.clone(),
|
||||
transform: Transform::from_rotation(ROT_X),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_rotation_start),
|
||||
On::<Pointer<Drag>>::run(on_rotate),
|
||||
On::<Pointer<DragEnd>>::run(on_rotation_end),
|
||||
));
|
||||
// Translate X
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_x.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_X,
|
||||
translation: vec3(1.2, 0., 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_translation_start),
|
||||
On::<Pointer<Drag>>::run(on_translate),
|
||||
On::<Pointer<DragEnd>>::target_commands_mut(on_translation_end),
|
||||
));
|
||||
|
||||
// Rotate Y
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_y.clone(),
|
||||
transform: Transform::from_rotation(ROT_Y),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_rotation_start),
|
||||
On::<Pointer<Drag>>::run(on_rotate),
|
||||
On::<Pointer<DragEnd>>::run(on_rotation_end),
|
||||
));
|
||||
// Translate Y
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_y.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Y,
|
||||
translation: vec3(0., 1.2, 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_translation_start),
|
||||
On::<Pointer<Drag>>::run(on_translate),
|
||||
On::<Pointer<DragEnd>>::target_commands_mut(on_translation_end),
|
||||
));
|
||||
|
||||
// Rotate Z
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_z.clone(),
|
||||
transform: Transform::from_rotation(ROT_Z),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_rotation_start),
|
||||
On::<Pointer<Drag>>::run(on_rotate),
|
||||
On::<Pointer<DragEnd>>::run(on_rotation_end),
|
||||
));
|
||||
// Translate Z
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_z.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Z,
|
||||
translation: vec3(0., 0., 1.2),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_translation_start),
|
||||
On::<Pointer<Drag>>::run(on_translate),
|
||||
On::<Pointer<DragEnd>>::target_commands_mut(on_translation_end),
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
use bevy::{math::Affine3A, prelude::*};
|
||||
use bevy_mod_picking::prelude::*;
|
||||
|
||||
use crate::{
|
||||
interaction::TransformSpace,
|
||||
math::{IsNonUniform, MatrixExtras, VecExtras},
|
||||
};
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) struct TransformGizmoRoot;
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) struct TransformGizmo;
|
||||
|
||||
#[derive(Event)]
|
||||
pub(super) struct RebuildGizmo;
|
||||
|
||||
#[derive(Bundle)]
|
||||
pub(super) struct TransformGizmoBundle {
|
||||
name: Name,
|
||||
marker: TransformGizmo,
|
||||
spatial: SpatialBundle,
|
||||
scale: NaturalScale,
|
||||
}
|
||||
|
||||
#[derive(Component, Deref, Reflect)]
|
||||
pub(super) struct NaturalScale(pub Vec3);
|
||||
|
||||
#[derive(Component, Deref)]
|
||||
pub(super) struct InitialTransform(pub GlobalTransform);
|
||||
|
||||
impl TransformGizmoBundle {
|
||||
pub fn new(
|
||||
parent_xform: &GlobalTransform,
|
||||
space: TransformSpace,
|
||||
normalizing_scale: f32,
|
||||
) -> Self {
|
||||
let name = Name::new("TransformGizmo");
|
||||
let marker = TransformGizmo;
|
||||
|
||||
let Affine3A {
|
||||
matrix3,
|
||||
translation,
|
||||
} = parent_xform.affine();
|
||||
|
||||
let (scale, rotation) = matrix3.decompose_scale_rotation();
|
||||
let inv_scale = scale.inverse();
|
||||
let nat_scale = NaturalScale(Vec3::from_scale_mat(inv_scale));
|
||||
|
||||
match space {
|
||||
TransformSpace::Local => {
|
||||
let global_transform = GlobalTransform::from(Affine3A {
|
||||
matrix3: rotation,
|
||||
translation,
|
||||
});
|
||||
|
||||
let transform = Transform::from_scale(*nat_scale * normalizing_scale);
|
||||
|
||||
Self {
|
||||
name,
|
||||
marker,
|
||||
spatial: SpatialBundle {
|
||||
global_transform,
|
||||
transform,
|
||||
..default()
|
||||
},
|
||||
scale: nat_scale,
|
||||
}
|
||||
}
|
||||
TransformSpace::World => {
|
||||
// FIXME: I'm struggling to figure out how to eliminate the
|
||||
// "shear" from a fully inverted local transform when the
|
||||
// object is non-uniformly scaled. As a workaround, we'll
|
||||
// force these objects to operate in local-space mode.
|
||||
// TODO: If this turns into a long-term solution, update the UI
|
||||
// to reflect that world-space transformation is not
|
||||
// possible for this object (e.g., by disabling the
|
||||
// world-space toggle button, maybe with an explanatory
|
||||
// tooltip).
|
||||
let local_matrix = if nat_scale.is_non_uniform() {
|
||||
inv_scale
|
||||
} else {
|
||||
matrix3.inverse()
|
||||
};
|
||||
|
||||
let global_transform = GlobalTransform::from(Affine3A {
|
||||
matrix3,
|
||||
translation,
|
||||
});
|
||||
|
||||
let mat4 = Mat4::from_mat3a(local_matrix * normalizing_scale);
|
||||
let transform = Transform::from_matrix(mat4);
|
||||
|
||||
Self {
|
||||
name,
|
||||
marker,
|
||||
spatial: SpatialBundle {
|
||||
global_transform,
|
||||
transform,
|
||||
..default()
|
||||
},
|
||||
scale: nat_scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_gizmo_element_hover(
|
||||
ev: Listener<Pointer<Over>>,
|
||||
mut ra_mats: ResMut<Assets<StandardMaterial>>,
|
||||
q_target: Query<&Handle<StandardMaterial>>,
|
||||
) {
|
||||
let mat = ra_mats.get_mut(q_target.get(ev.target).unwrap()).unwrap();
|
||||
mat.base_color *= 2.;
|
||||
}
|
||||
|
||||
pub(super) fn on_gizmo_element_unhover(
|
||||
ev: Listener<Pointer<Out>>,
|
||||
mut ra_mats: ResMut<Assets<StandardMaterial>>,
|
||||
q_target: Query<&Handle<StandardMaterial>>,
|
||||
) {
|
||||
let mat = ra_mats.get_mut(q_target.get(ev.target).unwrap()).unwrap();
|
||||
mat.base_color *= 0.5;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
use bevy::{prelude::*, transform::TransformSystem};
|
||||
|
||||
use crate::{camera_controller::CameraMotionSystem, MainCamera};
|
||||
|
||||
use self::{
|
||||
camera::{spawn_gizmo_camera, GizmoCamera},
|
||||
combo::spawn_combo_translation_rotation_gizmo,
|
||||
common::*,
|
||||
resources::{init_resources, GizmoMats, GizmoMeshes},
|
||||
rotation::{spawn_rotation_gizmo, update_ss_ring_rotation},
|
||||
translation::spawn_translation_gizmo,
|
||||
};
|
||||
|
||||
use super::{Selection, TransformMode, TransformType};
|
||||
|
||||
mod camera;
|
||||
mod combo;
|
||||
mod common;
|
||||
mod resources;
|
||||
mod rotation;
|
||||
mod translation;
|
||||
|
||||
const GIZMO_RENDER_LAYER: u8 = 1;
|
||||
|
||||
/// (sin|cos)(pi / 4)
|
||||
const CIRC_45: f32 = 0.70710677;
|
||||
/// Mat3 ((0 -1 0) (1 0 0) (0 0 1))
|
||||
const ROT_X: Quat = Quat::from_xyzw(0., 0., CIRC_45, -CIRC_45);
|
||||
/// Mat3 ((1 0 0) (0 1 0) (0 0 1))
|
||||
const ROT_Y: Quat = Quat::IDENTITY;
|
||||
/// Mat3 ((1 0 0) (0 0 1) (0 -1 0))
|
||||
const ROT_Z: Quat = Quat::from_xyzw(CIRC_45, 0., 0., CIRC_45);
|
||||
|
||||
pub struct GizmoPlugin;
|
||||
|
||||
impl Plugin for GizmoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.register_type::<NaturalScale>();
|
||||
app.add_event::<RebuildGizmo>();
|
||||
app.add_systems(Startup, init_resources);
|
||||
app.add_systems(
|
||||
PreUpdate,
|
||||
spawn_gizmo_camera.run_if(
|
||||
any_with_component::<MainCamera>()
|
||||
.and_then(not(any_with_component::<GizmoCamera>())),
|
||||
),
|
||||
);
|
||||
app.add_systems(
|
||||
Update,
|
||||
(
|
||||
despawn_existing_gizmo.run_if(
|
||||
resource_changed_or_removed::<Selection>()
|
||||
.or_else(resource_changed::<TransformMode>())
|
||||
.or_else(on_event::<RebuildGizmo>()),
|
||||
),
|
||||
spawn_gizmo.after(despawn_existing_gizmo).run_if(
|
||||
resource_exists::<Selection>()
|
||||
.and_then(not(any_with_component::<TransformGizmoRoot>())),
|
||||
),
|
||||
normalize_gizmo_scale.after(CameraMotionSystem),
|
||||
),
|
||||
);
|
||||
app.add_systems(
|
||||
PostUpdate,
|
||||
update_ss_ring_rotation.after(TransformSystem::TransformPropagate),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn despawn_existing_gizmo(
|
||||
mut cmd: Commands,
|
||||
q_gizmo_root: Query<(Entity, &Children), With<TransformGizmoRoot>>,
|
||||
q_gizmos: Query<Entity, With<TransformGizmo>>,
|
||||
) {
|
||||
if let Ok((ent, children)) = q_gizmo_root.get_single() {
|
||||
if let Some(child) = children.iter().find_map(|ent| q_gizmos.get(*ent).ok()) {
|
||||
cmd.entity(child).despawn_recursive();
|
||||
}
|
||||
|
||||
cmd.entity(ent).remove::<TransformGizmoRoot>();
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_gizmo(
|
||||
mut cmd: Commands,
|
||||
r_selection: Res<Selection>,
|
||||
r_xform_mode: Res<TransformMode>,
|
||||
q_xform: Query<&GlobalTransform>,
|
||||
q_cam_xform: Query<&Transform, With<MainCamera>>,
|
||||
r_meshes: Res<GizmoMeshes>,
|
||||
r_mats: Res<GizmoMats>,
|
||||
) {
|
||||
let ent = **r_selection;
|
||||
let Ok(xform) = q_xform.get(ent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(cam_xform) = q_cam_xform.get_single() else {
|
||||
return;
|
||||
};
|
||||
let dist = Vec3::distance(cam_xform.translation, xform.translation());
|
||||
let normalizing_scale = dist / 15.;
|
||||
|
||||
// TODO: Look into using the new one-shot systems feature here
|
||||
// https://bevyengine.org/news/bevy-0-12/#one-shot-systems
|
||||
match r_xform_mode.ttype {
|
||||
TransformType::TRANSLATE => {
|
||||
spawn_translation_gizmo(
|
||||
&mut cmd,
|
||||
ent,
|
||||
xform,
|
||||
r_xform_mode.space,
|
||||
normalizing_scale,
|
||||
&r_meshes,
|
||||
&r_mats,
|
||||
);
|
||||
}
|
||||
TransformType::ROTATE => {
|
||||
spawn_rotation_gizmo(
|
||||
&mut cmd,
|
||||
ent,
|
||||
xform,
|
||||
r_xform_mode.space,
|
||||
normalizing_scale,
|
||||
&r_meshes,
|
||||
&r_mats,
|
||||
);
|
||||
}
|
||||
ttype if ttype.contains(TransformType::TRANSLATE | TransformType::ROTATE) => {
|
||||
spawn_combo_translation_rotation_gizmo(
|
||||
&mut cmd,
|
||||
ent,
|
||||
xform,
|
||||
r_xform_mode.space,
|
||||
normalizing_scale,
|
||||
&r_meshes,
|
||||
&r_mats,
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_gizmo_scale(
|
||||
q_cam_xform: Query<&Transform, With<MainCamera>>,
|
||||
mut q_gizmo: Query<
|
||||
(&mut Transform, &GlobalTransform, &NaturalScale),
|
||||
(With<TransformGizmo>, Without<MainCamera>),
|
||||
>,
|
||||
) {
|
||||
let Ok(cam_xform) = q_cam_xform.get_single() else {
|
||||
return;
|
||||
};
|
||||
let Ok((mut xform, world_xform, nat_scale)) = q_gizmo.get_single_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let dist = Vec3::distance(cam_xform.translation, world_xform.translation());
|
||||
xform.scale = **nat_scale * (dist / 15.);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{design_system, math::geo};
|
||||
|
||||
#[derive(Resource, Reflect, Debug, Default)]
|
||||
#[reflect(Resource)]
|
||||
pub(super) struct GizmoMeshes {
|
||||
pub translate_line: Handle<Mesh>,
|
||||
pub translate_arrow: Handle<Mesh>,
|
||||
pub translate_plane: Handle<Mesh>,
|
||||
pub translate_ss: Handle<Mesh>,
|
||||
pub rotate_ring: Handle<Mesh>,
|
||||
pub rotate_ball: Handle<Mesh>,
|
||||
pub rotate_ss: Handle<Mesh>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Reflect, Debug, Default)]
|
||||
#[reflect(Resource)]
|
||||
pub(super) struct GizmoMats {
|
||||
pub translate_x: Handle<StandardMaterial>,
|
||||
pub translate_y: Handle<StandardMaterial>,
|
||||
pub translate_z: Handle<StandardMaterial>,
|
||||
pub translate_yz: Handle<StandardMaterial>,
|
||||
pub translate_xz: Handle<StandardMaterial>,
|
||||
pub translate_xy: Handle<StandardMaterial>,
|
||||
pub translate_ss: Handle<StandardMaterial>,
|
||||
pub rotate_x: Handle<StandardMaterial>,
|
||||
pub rotate_y: Handle<StandardMaterial>,
|
||||
pub rotate_z: Handle<StandardMaterial>,
|
||||
pub rotate_trackball: Handle<StandardMaterial>,
|
||||
pub rotate_ss: Handle<StandardMaterial>,
|
||||
}
|
||||
|
||||
pub(super) fn init_resources(
|
||||
mut cmd: Commands,
|
||||
mut ra_meshes: ResMut<Assets<Mesh>>,
|
||||
mut ra_mats: ResMut<Assets<StandardMaterial>>,
|
||||
) {
|
||||
let translate_line = ra_meshes.add(Mesh::from(shape::Cylinder {
|
||||
radius: 0.03,
|
||||
height: 0.8,
|
||||
resolution: 6,
|
||||
segments: 1,
|
||||
}));
|
||||
let translate_arrow = ra_meshes.add(Mesh::from(geo::Cone {
|
||||
radius: 0.115,
|
||||
length: 0.4,
|
||||
resolution: 12,
|
||||
}));
|
||||
let translate_plane = ra_meshes.add(Mesh::from(geo::Plane2Sided { size: 0.25 }));
|
||||
let translate_ss = ra_meshes.add(
|
||||
Mesh::try_from(shape::Icosphere {
|
||||
radius: 0.2,
|
||||
subdivisions: 3,
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let rotate_ring = ra_meshes.add(Mesh::from(shape::Torus {
|
||||
radius: 1.,
|
||||
ring_radius: 0.04,
|
||||
subdivisions_segments: 40,
|
||||
subdivisions_sides: 6,
|
||||
}));
|
||||
let rotate_ball = ra_meshes.add(
|
||||
Mesh::try_from(shape::Icosphere {
|
||||
radius: 0.96,
|
||||
subdivisions: 4,
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
let rotate_ss = ra_meshes.add(Mesh::from(shape::Torus {
|
||||
radius: 1.2,
|
||||
ring_radius: 0.03,
|
||||
subdivisions_segments: 40,
|
||||
subdivisions_sides: 6,
|
||||
}));
|
||||
|
||||
cmd.insert_resource(GizmoMeshes {
|
||||
translate_line,
|
||||
translate_arrow,
|
||||
translate_plane,
|
||||
translate_ss,
|
||||
rotate_ring,
|
||||
rotate_ball,
|
||||
rotate_ss,
|
||||
});
|
||||
|
||||
let translate_x = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::RED,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let translate_yz = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::RED,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
let translate_y = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::GREEN,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let translate_xz = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::GREEN,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
let translate_z = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::BLUE,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let translate_xy = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::BLUE,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
let translate_ss = ra_mats.add(StandardMaterial {
|
||||
base_color: Color::WHITE,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
let rotate_x = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::RED,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let rotate_y = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::GREEN,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let rotate_z = ra_mats.add(StandardMaterial {
|
||||
base_color: design_system::Color::BLUE,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
let rotate_trackball = ra_mats.add(StandardMaterial {
|
||||
base_color: Color::NONE,
|
||||
emissive: Color::WHITE,
|
||||
alpha_mode: AlphaMode::Add,
|
||||
..default()
|
||||
});
|
||||
let rotate_ss = ra_mats.add(StandardMaterial {
|
||||
base_color: Color::WHITE,
|
||||
unlit: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
cmd.insert_resource(GizmoMats {
|
||||
translate_x,
|
||||
translate_y,
|
||||
translate_z,
|
||||
translate_yz,
|
||||
translate_xz,
|
||||
translate_xy,
|
||||
translate_ss,
|
||||
rotate_x,
|
||||
rotate_y,
|
||||
rotate_z,
|
||||
rotate_trackball,
|
||||
rotate_ss,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
use bevy::{
|
||||
math::{vec3, Affine3A, DVec3, Mat3A, Vec3A},
|
||||
pbr::NotShadowCaster,
|
||||
prelude::*,
|
||||
render::view::RenderLayers,
|
||||
};
|
||||
use bevy_mod_picking::prelude::*;
|
||||
use bevy_mod_raycast::prelude::{Raycast, RaycastSettings};
|
||||
|
||||
use crate::{
|
||||
interaction::{TransformMode, TransformSpace},
|
||||
math::{MatrixExtras, NearlyZero},
|
||||
MainCamera,
|
||||
};
|
||||
|
||||
use super::{
|
||||
on_gizmo_element_hover, on_gizmo_element_unhover, GizmoMats, GizmoMeshes, InitialTransform,
|
||||
RebuildGizmo, TransformGizmo, TransformGizmoBundle, TransformGizmoRoot, GIZMO_RENDER_LAYER,
|
||||
};
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) enum RotationWidget {
|
||||
Axis(Vec3),
|
||||
ScreenSpace,
|
||||
Trackball,
|
||||
}
|
||||
|
||||
#[derive(Component, Deref)]
|
||||
pub(super) struct InitialHitPoint(pub Vec3);
|
||||
|
||||
#[derive(Component, Deref, DerefMut)]
|
||||
pub(super) struct LastHitPoint(pub Vec3);
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) struct LastRotation {
|
||||
pub axis: Vec3,
|
||||
pub theta: f32,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn spawn_rotation_gizmo(
|
||||
cmd: &mut Commands,
|
||||
ent: Entity,
|
||||
xform: &GlobalTransform,
|
||||
space: TransformSpace,
|
||||
normalizing_scale: f32,
|
||||
meshes: &GizmoMeshes,
|
||||
mats: &GizmoMats,
|
||||
) {
|
||||
cmd.entity(ent)
|
||||
.insert(TransformGizmoRoot)
|
||||
.with_children(|cmd| {
|
||||
cmd.spawn((
|
||||
TransformGizmoBundle::new(xform, space, normalizing_scale),
|
||||
On::<Pointer<DragStart>>::run(on_rotation_start),
|
||||
On::<Pointer<Drag>>::run(on_rotate),
|
||||
On::<Pointer<DragEnd>>::run(on_rotation_end),
|
||||
))
|
||||
.with_children(|cmd| {
|
||||
use super::{ROT_X, ROT_Y, ROT_Z};
|
||||
|
||||
// Trackball
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Trackball,
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ball.clone(),
|
||||
material: mats.rotate_trackball.clone(),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_trackball_hover),
|
||||
On::<Pointer<Out>>::run(on_trackball_unhover),
|
||||
));
|
||||
|
||||
// Screen-space
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::ScreenSpace,
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ss.clone(),
|
||||
material: mats.rotate_ss.clone(),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
));
|
||||
|
||||
// X
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_x.clone(),
|
||||
transform: Transform::from_rotation(ROT_X),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
));
|
||||
// Y
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_y.clone(),
|
||||
transform: Transform::from_rotation(ROT_Y),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
));
|
||||
// Z
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
RotationWidget::Axis(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.rotate_ring.clone(),
|
||||
material: mats.rotate_z.clone(),
|
||||
transform: Transform::from_rotation(ROT_Z),
|
||||
..default()
|
||||
},
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn update_ss_ring_rotation(
|
||||
q_camera: Query<&GlobalTransform, With<MainCamera>>,
|
||||
mut q_ring: Query<(&mut GlobalTransform, &RotationWidget), Without<MainCamera>>,
|
||||
) {
|
||||
let Ok(cam_xform) = q_camera.get_single() else {
|
||||
return;
|
||||
};
|
||||
|
||||
for (mut world_xform, widget) in q_ring.iter_mut() {
|
||||
if matches!(*widget, RotationWidget::ScreenSpace) {
|
||||
// Find basis vector to rotate the flat side of the ring toward the camera
|
||||
let origin: Vec3A = world_xform.translation().into();
|
||||
let normal = (Vec3A::from(cam_xform.translation()) - origin).normalize();
|
||||
let (tangent, binormal) = normal.any_orthonormal_pair();
|
||||
let rotation = Mat3A::from_cols(tangent, normal, binormal);
|
||||
|
||||
// Since we're overriding the local transform propagation, we need
|
||||
// to manually re-apply the normalization scale
|
||||
let scale = world_xform.affine().matrix3.decompose_scale();
|
||||
|
||||
*world_xform = GlobalTransform::from(Affine3A {
|
||||
matrix3: rotation * scale,
|
||||
translation: origin,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_trackball_hover(
|
||||
ev: Listener<Pointer<Over>>,
|
||||
mut ra_mats: ResMut<Assets<StandardMaterial>>,
|
||||
q_target: Query<&Handle<StandardMaterial>>,
|
||||
) {
|
||||
let mat = ra_mats.get_mut(q_target.get(ev.target).unwrap()).unwrap();
|
||||
mat.base_color.set_a(0.2);
|
||||
}
|
||||
|
||||
fn on_trackball_unhover(
|
||||
ev: Listener<Pointer<Out>>,
|
||||
mut ra_mats: ResMut<Assets<StandardMaterial>>,
|
||||
q_target: Query<&Handle<StandardMaterial>>,
|
||||
) {
|
||||
let mat = ra_mats.get_mut(q_target.get(ev.target).unwrap()).unwrap();
|
||||
mat.base_color.set_a(0.);
|
||||
}
|
||||
|
||||
pub(super) fn on_rotation_start(
|
||||
event: Listener<Pointer<DragStart>>,
|
||||
mut cmd: Commands,
|
||||
q_xform: Query<(Entity, &GlobalTransform), With<TransformGizmoRoot>>,
|
||||
) {
|
||||
info!("Rotation start");
|
||||
|
||||
if let Ok((ent, &world_xform)) = q_xform.get_single() {
|
||||
let hit_point = event.hit.position.unwrap();
|
||||
|
||||
cmd.entity(ent).insert((
|
||||
InitialTransform(world_xform),
|
||||
InitialHitPoint(hit_point),
|
||||
LastHitPoint(hit_point),
|
||||
LastRotation {
|
||||
axis: Vec3::ZERO,
|
||||
theta: 0.,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_rotation_end(
|
||||
event: Listener<Pointer<DragEnd>>,
|
||||
mut cmd: Commands,
|
||||
r_xform_mode: Res<TransformMode>,
|
||||
mut ev_rebuild_gizmo: EventWriter<RebuildGizmo>,
|
||||
) {
|
||||
info!("Rotation end");
|
||||
|
||||
cmd.entity(event.target)
|
||||
.remove::<InitialTransform>()
|
||||
.remove::<InitialHitPoint>()
|
||||
.remove::<LastHitPoint>()
|
||||
.remove::<LastRotation>();
|
||||
|
||||
if matches!(r_xform_mode.space, TransformSpace::World) {
|
||||
ev_rebuild_gizmo.send(RebuildGizmo);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_rotate(
|
||||
event: Listener<Pointer<Drag>>,
|
||||
mut raycast: Raycast,
|
||||
mut q_root: Query<
|
||||
(
|
||||
&mut Transform,
|
||||
Option<&Parent>,
|
||||
&InitialTransform,
|
||||
&InitialHitPoint,
|
||||
&mut LastHitPoint,
|
||||
&mut LastRotation,
|
||||
),
|
||||
With<TransformGizmoRoot>,
|
||||
>,
|
||||
q_camera: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
|
||||
q_gizmo: Query<&GlobalTransform, (With<TransformGizmo>, Without<MainCamera>)>,
|
||||
q_world_xforms: Query<&GlobalTransform, (With<Children>, Without<MainCamera>)>,
|
||||
q_widget: Query<&RotationWidget>,
|
||||
) {
|
||||
// Components from the gizmo root (the entity being transformed)
|
||||
let (mut xform, parent, init_xform, init_point, mut last_point, mut last_rotation) =
|
||||
q_root.single_mut();
|
||||
|
||||
let gizmo_xform = q_gizmo.single();
|
||||
let (cam, cam_xform) = q_camera.single();
|
||||
|
||||
// `Transform::rotate_axis` takes an axis vector relative to the transform's
|
||||
// _parent_. We'll use the gizmo root's parent's global transform (if it
|
||||
// exists) to move the world-space axis of rotation into the parent space
|
||||
// when applying the rotation.
|
||||
let identity_xform = GlobalTransform::default();
|
||||
let root_parent_xform = parent
|
||||
.and_then(|parent| q_world_xforms.get(parent.get()).ok())
|
||||
.unwrap_or(&identity_xform);
|
||||
|
||||
// We compute the rotation by finding a triangle (in world-space) where:
|
||||
// p0 = the gizmo/object origin
|
||||
// p1,p2 = the intersections of a camera-to-world raycast, where p1 is the
|
||||
// previous pointer location and p2 is the current.
|
||||
let p1 = **last_point;
|
||||
let p0 = init_xform.translation();
|
||||
|
||||
// Find the screen-space p2 by adding the total drag distance to the pointer
|
||||
// location recorded on `DragStart`
|
||||
let p_init_ss = cam.world_to_viewport(cam_xform, **init_point).unwrap();
|
||||
let p2_ss = p_init_ss + event.distance;
|
||||
|
||||
// Create a camera-to-world ray that passes through that point. In trackball
|
||||
// mode, we'll trace this against the surface of the trackball sphere to
|
||||
// find the world-space point. In all other modes, we'll trace against a
|
||||
// plane whose origin is p0 and whose normal is the axis of the "ring"
|
||||
// that's being dragged.
|
||||
let ray = cam.viewport_to_world(cam_xform, p2_ss).unwrap();
|
||||
|
||||
use RotationWidget::*;
|
||||
|
||||
match q_widget.get(event.target) {
|
||||
Ok(Trackball) => {
|
||||
// Raycast against the trackball sphere to find p2
|
||||
let filter = |ent: Entity| ent == event.target;
|
||||
let early_exit_test = |ent: Entity| ent != event.target;
|
||||
let settings = RaycastSettings {
|
||||
filter: &filter,
|
||||
early_exit_test: &early_exit_test,
|
||||
..default()
|
||||
};
|
||||
let hits = raycast.cast_ray(ray.into(), &settings);
|
||||
|
||||
// If the pointer is no longer in the vicinity of the sphere, we'll
|
||||
// invoke this closure to extrapolate additional rotation from the
|
||||
// last recorded axis and angle
|
||||
let mut extrapolate = || {
|
||||
use std::f32::consts::PI;
|
||||
|
||||
let axis_parent_space = last_rotation.axis;
|
||||
if axis_parent_space.nearly_zero() {
|
||||
return;
|
||||
}
|
||||
|
||||
let view_plane_normal = (cam_xform.translation() - p1).normalize();
|
||||
let hit_dist = ray.intersect_plane(p1, view_plane_normal).unwrap();
|
||||
let p2 = ray.origin + ray.direction * hit_dist;
|
||||
let drag_dist = (p2 - p1).length();
|
||||
// TODO: Sensitivity could use some tuning
|
||||
let theta = last_rotation.theta + drag_dist * PI * 0.5;
|
||||
|
||||
let mut init_xform_local = init_xform.reparented_to(root_parent_xform);
|
||||
init_xform_local.rotate_axis(axis_parent_space, theta);
|
||||
|
||||
*xform = init_xform_local;
|
||||
};
|
||||
|
||||
if hits.is_empty() {
|
||||
return extrapolate();
|
||||
}
|
||||
let (_, hit) = &hits[0];
|
||||
|
||||
// Use 64-bit precision for all of these vectors to derive an
|
||||
// accurate axis of rotation even at very small theta values
|
||||
let p0 = DVec3::from(p0);
|
||||
let p1 = DVec3::from(**init_point);
|
||||
let p2 = DVec3::from(hit.position());
|
||||
|
||||
let a = (p1 - p0).normalize_or_zero();
|
||||
let b = (p2 - p0).normalize_or_zero();
|
||||
if a.nearly_zero() || b.nearly_zero() {
|
||||
return extrapolate();
|
||||
}
|
||||
|
||||
// Find the angle @ p0
|
||||
let theta = a.dot(b).acos() as f32;
|
||||
|
||||
// Derive the axis of rotation by finding the vector perpendicular
|
||||
// to (p1-p0) and (p2-p0)
|
||||
let axis_ws = a.cross(b).normalize_or_zero();
|
||||
if axis_ws.nearly_zero() {
|
||||
return extrapolate();
|
||||
}
|
||||
|
||||
// Transform the world-space axis into the parent space
|
||||
let axis_parent_space = root_parent_xform
|
||||
.affine()
|
||||
.inverse()
|
||||
.transform_vector3(vec3(axis_ws.x as f32, axis_ws.y as f32, axis_ws.z as f32))
|
||||
.normalize();
|
||||
|
||||
// Apply the rotation and update our local state
|
||||
let mut init_xform_local = init_xform.reparented_to(root_parent_xform);
|
||||
init_xform_local.rotate_axis(axis_parent_space, theta);
|
||||
|
||||
*xform = init_xform_local;
|
||||
**last_point = vec3(p2.x as f32, p2.y as f32, p2.z as f32);
|
||||
last_rotation.axis = axis_parent_space;
|
||||
last_rotation.theta = theta;
|
||||
}
|
||||
Ok(axis) => {
|
||||
// Find the world-space axis of rotation
|
||||
let axis_ws = match axis {
|
||||
ScreenSpace => (p0 - cam_xform.translation()).normalize(),
|
||||
Axis(normal) => gizmo_xform.affine().transform_vector3(*normal).normalize(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
// Find the world-space p2, if possible
|
||||
let Some(hit_dist) = ray.intersect_plane(p0, axis_ws) else {
|
||||
// This could fail if the axis of rotation is nearly
|
||||
// perpendicular to the view direction
|
||||
return;
|
||||
};
|
||||
let p2 = ray.origin + ray.direction * hit_dist;
|
||||
|
||||
// Find the angle @ p0
|
||||
let a = p1 - p0;
|
||||
let b = p2 - p0;
|
||||
let theta = (a.dot(b) / (a.length() * b.length())).acos();
|
||||
if theta.is_nan() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the _direction_ of the rotation by comparing the canonical
|
||||
// axis of rotation with (p1-p0) x (p2-p0).
|
||||
//
|
||||
// In theory, we could just use that cross-product directly as our
|
||||
// axis of rotation, but floating-point errors at very small theta
|
||||
// values make that unfeasible in practice, so instead we just flip
|
||||
// the canonical axis when appropriate.
|
||||
let diff = axis_ws - a.cross(b).normalize();
|
||||
let axis_ws = if diff.length() > 1. {
|
||||
-axis_ws
|
||||
} else {
|
||||
axis_ws
|
||||
};
|
||||
|
||||
// Transform the world-space axis into the parent space
|
||||
let axis_parent_space = root_parent_xform
|
||||
.affine()
|
||||
.inverse()
|
||||
.transform_vector3(axis_ws)
|
||||
.normalize();
|
||||
|
||||
// Apply the rotation and update our local state
|
||||
xform.rotate_axis(axis_parent_space, theta);
|
||||
**last_point = p2;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
use bevy::{
|
||||
ecs::system::EntityCommands, math::vec3, pbr::NotShadowCaster, prelude::*,
|
||||
render::view::RenderLayers,
|
||||
};
|
||||
use bevy_mod_picking::prelude::{
|
||||
Drag, DragEnd, DragStart, Listener, ListenerInput, On, Out, Over, Pointer,
|
||||
};
|
||||
|
||||
use crate::{interaction::TransformSpace, MainCamera};
|
||||
|
||||
use super::{
|
||||
on_gizmo_element_hover, on_gizmo_element_unhover, GizmoMats, GizmoMeshes, InitialTransform,
|
||||
TransformGizmo, TransformGizmoBundle, TransformGizmoRoot, GIZMO_RENDER_LAYER,
|
||||
};
|
||||
|
||||
#[derive(Component)]
|
||||
pub(super) enum TranslationWidget {
|
||||
Axis(Vec3),
|
||||
Plane(Vec3),
|
||||
ScreenSpace,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn spawn_translation_gizmo(
|
||||
cmd: &mut Commands,
|
||||
ent: Entity,
|
||||
xform: &GlobalTransform,
|
||||
space: TransformSpace,
|
||||
normalizing_scale: f32,
|
||||
meshes: &GizmoMeshes,
|
||||
mats: &GizmoMats,
|
||||
) {
|
||||
cmd.entity(ent)
|
||||
.insert(TransformGizmoRoot)
|
||||
.with_children(|cmd| {
|
||||
cmd.spawn((
|
||||
TransformGizmoBundle::new(xform, space, normalizing_scale),
|
||||
On::<Pointer<Over>>::run(on_gizmo_element_hover),
|
||||
On::<Pointer<Out>>::run(on_gizmo_element_unhover),
|
||||
On::<Pointer<DragStart>>::run(on_translation_start),
|
||||
On::<Pointer<Drag>>::run(on_translate),
|
||||
On::<Pointer<DragEnd>>::target_commands_mut(on_translation_end),
|
||||
))
|
||||
.with_children(|cmd| {
|
||||
use super::{CIRC_45, ROT_X, ROT_Y, ROT_Z};
|
||||
|
||||
// Center sphere
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::ScreenSpace,
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_ss.clone(),
|
||||
material: mats.translate_ss.clone(),
|
||||
transform: Transform::IDENTITY,
|
||||
..default()
|
||||
},
|
||||
));
|
||||
|
||||
// X
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_line.clone(),
|
||||
material: mats.translate_x.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_X,
|
||||
translation: vec3(0.6, 0., 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_x.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_X,
|
||||
translation: vec3(1., 0., 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
|
||||
// Y
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_line.clone(),
|
||||
material: mats.translate_y.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Y,
|
||||
translation: vec3(0., 0.6, 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_y.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Y,
|
||||
translation: vec3(0., 1., 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
|
||||
// Z
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_line.clone(),
|
||||
material: mats.translate_z.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Z,
|
||||
translation: vec3(0., 0., 0.6),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Axis(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_arrow.clone(),
|
||||
material: mats.translate_z.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Z,
|
||||
translation: vec3(0., 0., 1.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
|
||||
// YZ Plane
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Plane(Vec3::X),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_plane.clone(),
|
||||
material: mats.translate_yz.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_X,
|
||||
translation: vec3(0., CIRC_45, CIRC_45),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
// XZ Plane
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Plane(Vec3::Y),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_plane.clone(),
|
||||
material: mats.translate_xz.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Y,
|
||||
translation: vec3(CIRC_45, 0., CIRC_45),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
// XY Plane
|
||||
cmd.spawn((
|
||||
NotShadowCaster,
|
||||
RenderLayers::layer(GIZMO_RENDER_LAYER),
|
||||
TranslationWidget::Plane(Vec3::Z),
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.translate_plane.clone(),
|
||||
material: mats.translate_xy.clone(),
|
||||
transform: Transform {
|
||||
rotation: ROT_Z,
|
||||
translation: vec3(CIRC_45, CIRC_45, 0.),
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn on_translation_start(
|
||||
_: Listener<Pointer<DragStart>>,
|
||||
mut cmd: Commands,
|
||||
q_xform: Query<(Entity, &GlobalTransform), With<TransformGizmoRoot>>,
|
||||
) {
|
||||
if let Ok((ent, &world_xform)) = q_xform.get_single() {
|
||||
cmd.entity(ent).insert(InitialTransform(world_xform));
|
||||
};
|
||||
}
|
||||
|
||||
pub(super) fn on_translation_end(
|
||||
_: &ListenerInput<Pointer<DragEnd>>,
|
||||
cmd: &mut EntityCommands<'_, '_, '_>,
|
||||
) {
|
||||
cmd.remove::<InitialTransform>();
|
||||
}
|
||||
|
||||
pub(super) fn on_translate(
|
||||
event: Listener<Pointer<Drag>>,
|
||||
mut q_root: Query<(&mut Transform, &InitialTransform), With<TransformGizmoRoot>>,
|
||||
q_camera: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
|
||||
q_gizmo: Query<&GlobalTransform, (With<TransformGizmo>, Without<MainCamera>)>,
|
||||
q_widget: Query<&TranslationWidget>,
|
||||
) {
|
||||
let (mut xform, init_xform) = q_root.single_mut();
|
||||
let gizmo_xform = q_gizmo.single();
|
||||
let (cam, cam_xform) = q_camera.single();
|
||||
|
||||
// Find the initial origin point in screen-space and add the total screen-space drag distance
|
||||
let origin_ws = init_xform.translation();
|
||||
let origin_ss = cam.world_to_viewport(cam_xform, origin_ws).unwrap();
|
||||
let target_ss = origin_ss + event.distance;
|
||||
|
||||
// Create a camera-to-world ray that passes through the screen-space target point
|
||||
let ray = cam.viewport_to_world(cam_xform, target_ss).unwrap();
|
||||
|
||||
use TranslationWidget::*;
|
||||
|
||||
match q_widget.get(event.target) {
|
||||
Ok(Axis(axis)) => {
|
||||
// Transform the translation axis into world-space
|
||||
let axis_ws = gizmo_xform.affine().transform_vector3(*axis).normalize();
|
||||
|
||||
// Find the plane vector that's orthogonal to the translation axis
|
||||
// and closest to parallel with the view direction
|
||||
let axis_tan = axis_ws.cross(cam_xform.back());
|
||||
let plane_vector = axis_ws.cross(axis_tan);
|
||||
|
||||
// Find the intersection of the camera-to-world ray against that plane
|
||||
let Some(hit_dist) = ray.intersect_plane(origin_ws, plane_vector) else {
|
||||
return;
|
||||
};
|
||||
let hit_point = ray.origin + ray.direction * hit_dist;
|
||||
|
||||
// Project the vector from origin -> hit point onto the translation
|
||||
// axis to constrain the translation
|
||||
let drag_vector = hit_point - origin_ws;
|
||||
let projection_length = drag_vector.dot(axis_ws);
|
||||
let target_ws = origin_ws + axis_ws * projection_length;
|
||||
|
||||
xform.translation = target_ws;
|
||||
}
|
||||
Ok(plane) => {
|
||||
// Find the world-space normal of the plane we're translating on
|
||||
let plane_normal = match plane {
|
||||
ScreenSpace => cam_xform.back(),
|
||||
Plane(normal) => gizmo_xform.affine().transform_vector3(*normal),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
// Find the intersection of the camera-to-world ray against that plane
|
||||
let Some(hit_dist) = ray.intersect_plane(origin_ws, plane_normal) else {
|
||||
return;
|
||||
};
|
||||
let target_ws = ray.origin + ray.direction * hit_dist;
|
||||
|
||||
xform.translation = target_ws;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
mod gizmos;
|
||||
pub mod selection;
|
||||
pub mod transformation;
|
||||
|
||||
pub use selection::*;
|
||||
pub use transformation::*;
|
||||
|
||||
pub struct InteractionPlugin;
|
||||
impl Plugin for InteractionPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_plugins((SelectionPlugin, TransformationPlugin));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy_mod_outline::{
|
||||
AutoGenerateOutlineNormalsPlugin, OutlineBundle, OutlinePlugin, OutlineVolume,
|
||||
};
|
||||
use bevy_mod_picking::{prelude::Pointer, selection::Select};
|
||||
|
||||
use crate::input::{self, Action, InputAction, Lifecycle};
|
||||
|
||||
pub struct SelectionPlugin;
|
||||
impl Plugin for SelectionPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_plugins((OutlinePlugin, AutoGenerateOutlineNormalsPlugin))
|
||||
.add_systems(Update, update_selection)
|
||||
.add_systems(
|
||||
PostUpdate,
|
||||
draw_selection_outline.run_if(resource_changed_or_removed::<Selection>()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy)]
|
||||
pub struct Selectable;
|
||||
|
||||
#[derive(Component, Clone, Copy)]
|
||||
pub struct Selected;
|
||||
|
||||
#[derive(Resource, Deref, DerefMut)]
|
||||
pub struct Selection(Entity);
|
||||
|
||||
fn update_selection(
|
||||
mut cmd: Commands,
|
||||
// FIXME: These events aren't aware of our input actions, so we receive a
|
||||
// selection event when LMB is released after orbiting the camera.
|
||||
// Should drop bevy_mod_picking's Selection plugin/feature and just
|
||||
// use our own conditional click listener.
|
||||
mut ev_select: EventReader<Pointer<Select>>,
|
||||
mut ev_input: EventReader<InputAction>,
|
||||
q_parents: Query<&Parent>,
|
||||
q_selectable: Query<&Selectable>,
|
||||
q_selected: Query<Entity, With<Selected>>,
|
||||
) {
|
||||
if let Some(event) = ev_select.iter().last() {
|
||||
// Clear any existing `Selected` components
|
||||
for ent in q_selected.iter() {
|
||||
cmd.entity(ent).remove::<Selected>();
|
||||
}
|
||||
|
||||
// Find the nearest Selectable parent of the target entity
|
||||
let mut ent = event.target;
|
||||
let ent_selected = loop {
|
||||
if q_selectable.get(ent).is_ok() {
|
||||
break Some(ent);
|
||||
}
|
||||
|
||||
if let Ok(parent) = q_parents.get(ent) {
|
||||
ent = parent.get();
|
||||
} else {
|
||||
break None;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(ent) = ent_selected {
|
||||
cmd.insert_resource(Selection(ent));
|
||||
cmd.entity(ent).insert(Selected);
|
||||
} else {
|
||||
cmd.remove_resource::<Selection>();
|
||||
}
|
||||
} else if ev_input.iter().any(|action| {
|
||||
matches!(
|
||||
action,
|
||||
InputAction(Lifecycle::Stop, Action::Selection(input::Selection::Clear))
|
||||
)
|
||||
}) {
|
||||
cmd.remove_resource::<Selection>();
|
||||
|
||||
for ent in q_selected.iter() {
|
||||
cmd.entity(ent).remove::<Selected>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_selection_outline(
|
||||
mut cmd: Commands,
|
||||
q_selected: Query<&Children, With<Selected>>,
|
||||
q_meshes: Query<Entity, (With<Handle<Mesh>>, Without<OutlineVolume>)>,
|
||||
q_outlines: Query<Entity, With<OutlineVolume>>,
|
||||
) {
|
||||
// Remove existing outlines
|
||||
for ent in q_outlines.iter() {
|
||||
cmd.entity(ent).remove::<OutlineBundle>();
|
||||
}
|
||||
|
||||
for children in q_selected.iter() {
|
||||
for &child in children.iter() {
|
||||
if q_meshes.contains(child) {
|
||||
cmd.entity(child).insert(OutlineBundle {
|
||||
outline: OutlineVolume {
|
||||
visible: true,
|
||||
width: 4.,
|
||||
colour: Color::YELLOW,
|
||||
},
|
||||
..default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use core::fmt;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bitflags::bitflags;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
use super::gizmos::GizmoPlugin;
|
||||
|
||||
pub struct TransformationPlugin;
|
||||
|
||||
impl Plugin for TransformationPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(TransformMode::default());
|
||||
app.add_plugins(GizmoPlugin);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
app.add_systems(PreUpdate, wasm::update_transform_mode);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct TransformMode {
|
||||
pub ttype: TransformType,
|
||||
pub space: TransformSpace,
|
||||
}
|
||||
|
||||
impl Default for TransformMode {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
ttype: TransformType::TRANSLATE,
|
||||
space: default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[wasm_bindgen]
|
||||
pub enum TransformSpace {
|
||||
#[default]
|
||||
Local,
|
||||
World,
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TransformType : u8 {
|
||||
const TRANSLATE = 0b001;
|
||||
const ROTATE = 0b010;
|
||||
const SCALE = 0b100;
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for TransformType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "TransformType(")?;
|
||||
|
||||
let mut written = false;
|
||||
if self.contains(TransformType::TRANSLATE) {
|
||||
if written {
|
||||
write!(f, " | ")?;
|
||||
}
|
||||
write!(f, "TRANSLATE")?;
|
||||
written = true;
|
||||
}
|
||||
if self.contains(TransformType::ROTATE) {
|
||||
if written {
|
||||
write!(f, " | ")?;
|
||||
}
|
||||
write!(f, "ROTATE")?;
|
||||
written = true;
|
||||
}
|
||||
if self.contains(TransformType::SCALE) {
|
||||
if written {
|
||||
write!(f, " | ")?;
|
||||
}
|
||||
write!(f, "SCALE")?;
|
||||
}
|
||||
|
||||
if self.bits() == 0 {
|
||||
write!(f, "None")?;
|
||||
}
|
||||
|
||||
write!(f, ")")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod wasm {
|
||||
use bevy::prelude::*;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use crate::wasm::{self, WasmMessageBuffer};
|
||||
|
||||
use super::{TransformMode, TransformSpace, TransformType};
|
||||
|
||||
#[wasm_bindgen(js_name = TransformType)]
|
||||
#[rustfmt::skip]
|
||||
pub enum JsTransformType {
|
||||
Translate = 0b001,
|
||||
Rotate = 0b010,
|
||||
Scale = 0b100,
|
||||
}
|
||||
|
||||
impl From<u8> for TransformType {
|
||||
fn from(value: u8) -> Self {
|
||||
TransformType::from_bits_retain(value)
|
||||
}
|
||||
}
|
||||
|
||||
static TRANSFORM_TYPE_BUF: WasmMessageBuffer<TransformType> = WasmMessageBuffer::new();
|
||||
static TRANSFORM_SPACE_BUF: WasmMessageBuffer<TransformSpace> = WasmMessageBuffer::new();
|
||||
|
||||
#[wasm_bindgen(js_name = setTransformType)]
|
||||
pub fn set_transform_type(flags: u8) {
|
||||
wasm::write_message!(TRANSFORM_TYPE_BUF, flags.into());
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = setTransformSpace)]
|
||||
pub fn set_transform_space(space: TransformSpace) {
|
||||
wasm::write_message!(TRANSFORM_SPACE_BUF, space);
|
||||
}
|
||||
|
||||
pub(super) fn update_transform_mode(mut xform_mode: ResMut<TransformMode>) {
|
||||
wasm::read_buffer!(TRANSFORM_TYPE_BUF, |ttype| {
|
||||
info!("Setting transform type: {ttype:?}");
|
||||
xform_mode.ttype = ttype;
|
||||
});
|
||||
wasm::read_buffer!(TRANSFORM_SPACE_BUF, |space| {
|
||||
info!("Setting transform space: {space:?}");
|
||||
xform_mode.space = space;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user