mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
effects-w11: net change of 2 commits
- effects-w11: written from its sheet - effects-w11: repair 1
This commit is contained in:
@@ -9,14 +9,23 @@
|
||||
//! readers. The widget edits the panel's fields as the light settings do, so the panel previews a
|
||||
//! drag and records it as one undo step when the pointer is released.
|
||||
|
||||
use egui::{Id, Key, Modifiers, Rect, Sense, Stroke, Vec2, vec2};
|
||||
// PLAN: assumed the app depends on craft-behavior, craft-ui-widgets and craft-ui-patterns (hub-w2 owns Cargo.toml).
|
||||
use craft::behavior::{CursorIcon, HitLevel, HitPriority, HitShape, Metrics, NavMove, PartKey, PointerButton, PressPhase, Sense};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
|
||||
PartsCx, Pointer as _, Props as _, Remember as _, Role, Show as _,
|
||||
};
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleCx};
|
||||
use craft_ui_patterns::patterns::form_dialogs::{CustomContext, DialogFields};
|
||||
use craft_ui_widgets::buttons::Button;
|
||||
use egui::{Pos2, Rect, Response, Stroke, Vec2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_three_d::{DEFAULT_LIGHT, Revolve};
|
||||
|
||||
use super::revolve::{c3, explicit_lights, light_record, set_light_value};
|
||||
use super::revolve_gizmo::{snap_height, wrap};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The sphere's largest radius, in points.
|
||||
@@ -26,8 +35,11 @@ const SUN: f32 = 7.0;
|
||||
/// The arrow keys' steps in degrees, without and with Shift.
|
||||
const STEP: f64 = 1.0;
|
||||
const SHIFT_STEP: f64 = 15.0;
|
||||
/// The keys that move the focused light.
|
||||
const ARROWS: [Key; 4] = [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown];
|
||||
/// One light of the sphere: `LIGHT.at(i)` with `i` its place in the list of lights.
|
||||
const LIGHT: PartKey = PartKey::new("light");
|
||||
|
||||
/// The lights the sphere shows, in the order of the list of lights.
|
||||
pub(crate) type Lights = Vec<Light>;
|
||||
|
||||
/// One light as the widget shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -57,17 +69,17 @@ impl Light {
|
||||
(round(wrap(rotation, snap)), round(snap_height(height, snap)))
|
||||
}
|
||||
|
||||
/// The Rotation and Height after one press of `key` (Left and Right turn the light around the
|
||||
/// The Rotation and Height after one press of `key` (Back and Forward turn the light around the
|
||||
/// object counterclockwise and clockwise, Up and Down raise and lower it). Only the setting the
|
||||
/// key moves changes, rounded to 0.1°. `None` for another key.
|
||||
fn stepped(self, key: Key, step: f64) -> Option<(f64, f64)> {
|
||||
fn stepped(self, key: NavMove, step: f64) -> Option<(f64, f64)> {
|
||||
let turn = |by: f64| round(wrap(self.rotation + by, false));
|
||||
let raise = |by: f64| round(snap_height(self.height + by, false));
|
||||
match key {
|
||||
Key::ArrowLeft => Some((turn(step), self.height)),
|
||||
Key::ArrowRight => Some((turn(-step), self.height)),
|
||||
Key::ArrowUp => Some((self.rotation, raise(step))),
|
||||
Key::ArrowDown => Some((self.rotation, raise(-step))),
|
||||
NavMove::Back => Some((turn(step), self.height)),
|
||||
NavMove::Forward => Some((turn(-step), self.height)),
|
||||
NavMove::Up => Some((self.rotation, raise(step))),
|
||||
NavMove::Down => Some((self.rotation, raise(-step))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -88,16 +100,20 @@ fn round(n: f64) -> f64 {
|
||||
/// the settings a light leaves out or the selected effects hold with different values (null). A 3D
|
||||
/// (Classic) effect's lights are white whatever color a list light carries, since it shades
|
||||
/// without light color.
|
||||
pub(crate) fn lights(d: &Dialog) -> Vec<Light> {
|
||||
let effect = d.str("__effect");
|
||||
let colored = !vectorcraft_effects::is_classic_three_d(&effect);
|
||||
let defaults = vectorcraft_effects::default_params(&effect).unwrap_or(json!({}));
|
||||
let list = explicit_lights(d).cloned().unwrap_or_else(|| vec![light_record(d)]);
|
||||
pub(crate) fn lights(fields: &DialogFields) -> Lights {
|
||||
let classic = vectorcraft_effects::is_classic_three_d(fields.text("__effect").unwrap_or_default());
|
||||
lights_for(fields, classic)
|
||||
}
|
||||
|
||||
/// [`lights`] for a light editor that already knows whether it edits a 3D (Classic) effect.
|
||||
fn lights_for(fields: &DialogFields, classic: bool) -> Lights {
|
||||
let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({}));
|
||||
let list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]);
|
||||
list.iter()
|
||||
.map(|light| {
|
||||
let value =
|
||||
|key: &str, field: &str| light.get(key).filter(|v| !v.is_null()).or_else(|| defaults.get(field)).cloned().unwrap_or(Value::Null);
|
||||
let color = if colored { value("color", "lightColor") } else { Value::Null };
|
||||
let color = if classic { Value::Null } else { value("color", "lightColor") };
|
||||
let [r, g, b] = color
|
||||
.as_str()
|
||||
.filter(|s| s.len() == 7 && s.starts_with('#'))
|
||||
@@ -116,140 +132,287 @@ pub(crate) fn lights(d: &Dialog) -> Vec<Light> {
|
||||
}
|
||||
|
||||
/// The index of the selected light among `count` lights.
|
||||
fn selected(d: &Dialog, count: usize) -> usize {
|
||||
d.fields.get("__light").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).unwrap_or(0).min(count.saturating_sub(1))
|
||||
fn selected(fields: &DialogFields, count: usize) -> usize {
|
||||
fields.int("__light").and_then(|v| usize::try_from(v).ok()).unwrap_or(0).min(count.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Makes light `index` the selected one, as a choice in the list of lights does.
|
||||
fn select(ui: &egui::Ui, d: &mut Dialog, index: usize) {
|
||||
if d.fields.get("__light").and_then(Value::as_u64) != Some(index as u64) {
|
||||
ui.memory_mut(|m| m.stop_text_input());
|
||||
super::revolve_gizmo::clear(ui.ctx());
|
||||
fn select(fields: &mut DialogFields, index: usize) {
|
||||
// PLAN: assumed `FieldValue: From<i64>`
|
||||
fields.set("__light", index as i64);
|
||||
}
|
||||
|
||||
/// Writes the settings of `to` that differ from `from` into the selected light, selecting the light that moved. Only a setting
|
||||
/// that moved is written: a press that leaves a light where it is, or a key at a limit, changes nothing, and a key leaves the
|
||||
/// other setting as each selected effect has it.
|
||||
pub(super) fn write_moved(fields: &mut DialogFields, from: &[Light], to: &[Light]) {
|
||||
for (index, (was, now)) in from.iter().zip(to).enumerate() {
|
||||
for (key, value, old) in [("lightRotation", now.rotation, was.rotation), ("lightHeight", now.height, was.height)] {
|
||||
if (value - old).abs() > 1e-9 {
|
||||
select(fields, index);
|
||||
set_light_value(fields, key, json!(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a part-based dialog row control: nothing beyond the metrics and the focus look.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub(super) struct RowStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
}
|
||||
|
||||
impl RowStyle {
|
||||
/// The style from the theme.
|
||||
pub(super) fn of(cx: &StyleCx<'_>) -> Self {
|
||||
RowStyle { metrics: Metrics::new(), focus: cx.focus_look() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius of the sphere in a row `width` points wide: it stays inside a narrow panel.
|
||||
fn radius_in(width: f32) -> f32 {
|
||||
RADIUS.min((width * 0.5 - SUN - 8.0).max(24.0))
|
||||
}
|
||||
|
||||
/// Where the sphere's centre and radius are in `rect`.
|
||||
fn geometry(rect: Rect) -> (Pos2, f32) {
|
||||
(rect.center(), radius_in(rect.width()))
|
||||
}
|
||||
|
||||
/// What a press on a light holds while it runs: the light and the offset from the press to the light's centre, kept for the
|
||||
/// drag.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Hold {
|
||||
index: usize,
|
||||
grip: Vec2,
|
||||
}
|
||||
|
||||
/// The sphere of the lights: one slider part per light that a drag moves on its side of the object and the arrow keys step.
|
||||
/// The value is the list of lights; a drag proposes it with the dragged light moved and Escape restores the start.
|
||||
///
|
||||
/// - Pointer: a press selects the light and takes the focus; the light follows the pointer once it has left the press point,
|
||||
/// keeping the offset between the press and its centre; Shift snaps to 15°. The selected light is above the others.
|
||||
/// - Keyboard: each light is a Tab stop; Left and Right turn the light, Up and Down raise and lower it, 1° a press and 15°
|
||||
/// with Shift, each press one step.
|
||||
/// - AccessKit: a `Slider` per light named by its number, Rotation, Height and side.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub(crate) struct LightSphere<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
lights: Bind<'a, Lights>,
|
||||
/// The selected light, drawn larger and ringed.
|
||||
#[prop]
|
||||
selected: usize,
|
||||
/// The light a press selected this pass.
|
||||
picked: Option<usize>,
|
||||
/// The light the pointer is over or holds.
|
||||
hot: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a> LightSphere<'a> {
|
||||
/// A sphere named `label` showing `lights`.
|
||||
pub(crate) fn new(label: impl Into<craft_ui::runtime::env::Label>, lights: Bind<'a, Lights>) -> Self {
|
||||
LightSphere { common: Common::new(), lights, selected: 0, picked: None, hot: None }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`LightSphere`] returns.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct LightSphereOutput {
|
||||
/// The edit of the lights.
|
||||
pub edit: EditResponse<Lights>,
|
||||
/// The light a press or the keyboard focus took this pass.
|
||||
pub picked: Option<usize>,
|
||||
}
|
||||
|
||||
impl Outcome for LightSphereOutput {
|
||||
type Value = Lights;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for LightSphere<'_> {
|
||||
const DISABLED: DisabledLook = DisabledLook::Faded;
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const SHOWS_LABEL: bool = false;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither).with_moves();
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = RowStyle;
|
||||
type Output = LightSphereOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: LightSphereStyleKey) -> RowStyle {
|
||||
RowStyle::of(cx)
|
||||
}
|
||||
|
||||
/// The row's width and the height of the sphere that fits it, with its suns.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let width = cx.picture_width((24.0 + SUN + 8.0) * 2.0, f32::INFINITY);
|
||||
Vec2::new(width, (radius_in(width) + SUN + 6.0) * 2.0)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let (center, radius) = geometry(rect);
|
||||
let lights: Lights = cx.value().cloned().unwrap_or_default();
|
||||
for (index, light) in lights.iter().enumerate() {
|
||||
// The selected light wins an overlap, as it is drawn last.
|
||||
let level = u8::from(index == self.selected);
|
||||
cx.part(LIGHT.at(index as u64), HitShape::circle(center + light.offset() * radius, SUN + 4.0))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.priority(HitPriority::new(HitLevel::Handle, level.into()))
|
||||
.cursor(CursorIcon::Grab)
|
||||
.drag_cursor(CursorIcon::Grabbing)
|
||||
.tooltip(tl!("Drag a light to move it. The arrow keys move the focused light; Shift steps 15°."))
|
||||
.focusable();
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, Lights>> {
|
||||
Some(self.lights.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let (center, radius) = geometry(cx.rect);
|
||||
let lights: Lights = cx.value().cloned().unwrap_or_default();
|
||||
let mut held = *cx.press_slot::<Hold>();
|
||||
for (index, light) in lights.iter().enumerate() {
|
||||
let part = LIGHT.at(index as u64);
|
||||
let Some(result) = cx.part_if_declared(part) else { continue };
|
||||
let (press, hovered) = (result.press, result.hovered);
|
||||
if hovered {
|
||||
self.hot = Some(index);
|
||||
}
|
||||
// The light goes where the pointer carries it, by the offset the press had from its centre.
|
||||
let moved = |hold: &Hold, pos: Pos2| {
|
||||
let to = light.moved_to((pos + hold.grip - center) / radius, press.mods.shift);
|
||||
let mut next = lights.clone();
|
||||
if let Some(l) = next.get_mut(index) {
|
||||
(l.rotation, l.height) = to;
|
||||
}
|
||||
next
|
||||
};
|
||||
match press.phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
|
||||
cx.focus_part(part);
|
||||
self.picked = Some(index);
|
||||
held = Some(Hold { index, grip: center + light.offset() * radius - start.origin });
|
||||
}
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
|
||||
let Some(hold) = held.filter(|h| h.index == index) else { continue };
|
||||
if matches!(press.phase, PressPhase::DragStart { .. }) {
|
||||
cx.begin();
|
||||
}
|
||||
self.hot = Some(index);
|
||||
cx.propose(moved(&hold, pos));
|
||||
}
|
||||
PressPhase::Release { pos, .. } => {
|
||||
let Some(hold) = held.filter(|h| h.index == index) else { continue };
|
||||
// A click that never left the press point moves nothing: no gesture ran.
|
||||
if cx.gesture().is_some() {
|
||||
cx.propose(moved(&hold, pos));
|
||||
cx.commit();
|
||||
}
|
||||
held = None;
|
||||
}
|
||||
PressPhase::Cancel { .. } => held = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
*cx.press_slot::<Hold>() = held;
|
||||
if let Some(arrived) = cx.focus_arrived().filter(|part| part.key == LIGHT) {
|
||||
self.picked = arrived.index.and_then(|i| usize::try_from(i).ok());
|
||||
}
|
||||
let focused = cx.active_part().filter(|part| part.key == LIGHT).and_then(|part| part.index).and_then(|i| usize::try_from(i).ok());
|
||||
let mut next = lights.clone();
|
||||
while let Some((key, mods)) = cx.intents().take_move() {
|
||||
// Only a plain or Shift press steps; every press of the pass moves the light in turn.
|
||||
if mods.lead || mods.fine || cx.gesture().is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(index) = focused else { continue };
|
||||
let step = if mods.extend { SHIFT_STEP } else { STEP };
|
||||
if let Some(light) = next.get_mut(index)
|
||||
&& let Some((rotation, height)) = light.stepped(key, step)
|
||||
{
|
||||
(light.rotation, light.height) = (rotation, height);
|
||||
cx.set(next.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
for (index, light) in cx.value().map(Vec::as_slice).unwrap_or_default().iter().enumerate() {
|
||||
access.node(LIGHT.at(index as u64), Role::SLIDER).name = Name::Text(light.name(index));
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (center, radius) = geometry(cx.rect);
|
||||
let content = ui.content_painter(cx);
|
||||
let painter = &content.painter;
|
||||
let t = Tokens::get(painter.ctx());
|
||||
// The sphere: its rim is Height 0, its center Height 90°, and the ring between them 45°.
|
||||
painter.circle(center, radius, t.input, Stroke::new(1.0, t.input_border));
|
||||
painter.circle_stroke(center, radius * std::f32::consts::FRAC_1_SQRT_2, Stroke::new(1.0, t.input_border.gamma_multiply(0.5)));
|
||||
for axis in [vec2(radius, 0.0), vec2(0.0, radius)] {
|
||||
painter.line_segment([center - axis, center + axis], Stroke::new(1.0, t.input_border.gamma_multiply(0.5)));
|
||||
}
|
||||
painter.circle(center, 4.0, t.panel, Stroke::new(1.0, t.text_dim));
|
||||
let lights: &[Light] = cx.value().map(Vec::as_slice).unwrap_or_default();
|
||||
// The selected light last, so it is drawn above the others.
|
||||
let order = (0..lights.len()).filter(|&i| i != self.selected).chain([self.selected]);
|
||||
for index in order {
|
||||
let Some(&light) = lights.get(index) else { continue };
|
||||
let focused = cx.is_focused() && cx.active_part() == Some(LIGHT.at(index as u64));
|
||||
paint_light(painter, &t, center + light.offset() * radius, light, index == self.selected, focused, self.hot == Some(index));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> LightSphereOutput {
|
||||
LightSphereOutput { edit: cx.edit_response(), picked: self.picked }
|
||||
}
|
||||
d.fields.insert("__light".into(), json!(index));
|
||||
}
|
||||
|
||||
/// Draws the sphere with the lights and the button that moves the selected light to the back or
|
||||
/// the front, editing `d.fields`.
|
||||
pub(super) fn show(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let lights = lights(d);
|
||||
let Some(&first) = lights.first() else { return };
|
||||
let current = selected(d, lights.len());
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let radius = RADIUS.min((ui.available_width() * 0.5 - SUN - 8.0).max(24.0));
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), (radius + SUN + 6.0) * 2.0), Sense::hover());
|
||||
let center = rect.center();
|
||||
let painter = ui.painter_at(rect);
|
||||
// The sphere: its rim is Height 0, its center Height 90°, and the ring between them 45°.
|
||||
painter.circle(center, radius, t.input, Stroke::new(1.0, t.input_border));
|
||||
painter.circle_stroke(center, radius * std::f32::consts::FRAC_1_SQRT_2, Stroke::new(1.0, t.input_border.gamma_multiply(0.5)));
|
||||
for axis in [vec2(radius, 0.0), vec2(0.0, radius)] {
|
||||
painter.line_segment([center - axis, center + axis], Stroke::new(1.0, t.input_border.gamma_multiply(0.5)));
|
||||
/// the front, editing `fields`. `classic` is whether the effect is a 3D (Classic) one, whose lights are white. The control's
|
||||
/// events go to the rows through `cx`, so the panel and the dialog's preview follow a drag.
|
||||
pub(crate) fn sphere(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext, classic: bool) -> Response {
|
||||
let list = lights_for(fields, classic);
|
||||
let current = selected(fields, list.len());
|
||||
let out = LightSphere::new(tl!("Lights"), Bind::given(list.clone())).selected(current).show(ui);
|
||||
cx.gesture(&out.edit.events);
|
||||
if let Some(index) = out.picked {
|
||||
select(fields, index);
|
||||
}
|
||||
painter.circle(center, 4.0, t.panel, Stroke::new(1.0, t.text_dim));
|
||||
// The selected light last, so it is drawn above the others and a press there takes it.
|
||||
let order = (0..lights.len()).filter(|&i| i != current).chain([current]);
|
||||
let mut moved = None;
|
||||
let enabled = ui.is_enabled();
|
||||
// The panel and a 3D (Classic) options dialog can both show the sphere at once.
|
||||
let panel = d.bool("__panel");
|
||||
for index in order {
|
||||
let light = lights.get(index).copied().unwrap_or(first);
|
||||
let at = center + light.offset() * radius;
|
||||
let id = Id::unique(("three-d-lighting-widget", panel, index));
|
||||
let response = ui.interact(Rect::from_center_size(at, Vec2::splat((SUN + 4.0) * 2.0)), id, Sense::click_and_drag());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, enabled, light.name(index)));
|
||||
// A light the pointer took, or that the keyboard focus reached, becomes the selected light and
|
||||
// keeps the focus, so the arrow keys move it next. Selecting another light stops the editor
|
||||
// that had the focus, which clears the focus, so the light asks for it after that.
|
||||
if response.drag_started() || response.clicked() || response.gained_focus() {
|
||||
select(ui, d, index);
|
||||
response.request_focus();
|
||||
}
|
||||
let origin = ui.input(|i| i.pointer.press_origin());
|
||||
if response.drag_started()
|
||||
&& let Some(origin) = origin
|
||||
{
|
||||
// The offset from the press to the light's center, kept for the drag, and whether the
|
||||
// pointer has left the press yet.
|
||||
ui.data_mut(|m| m.insert_temp(id, (at - origin, false)));
|
||||
}
|
||||
// The frame that releases the pointer can also move it: the light goes where it was dropped,
|
||||
// the point of the press included once the pointer has left it.
|
||||
if (response.dragged() || response.drag_stopped())
|
||||
&& let Some(p) = response.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))
|
||||
{
|
||||
let (grip, left): (Vec2, bool) = ui.data(|m| m.get_temp(id)).unwrap_or_default();
|
||||
let left = left || origin != Some(p);
|
||||
ui.data_mut(|m| m.insert_temp(id, (grip, left)));
|
||||
if left {
|
||||
let snap = ui.input(|i| i.modifiers.shift);
|
||||
moved = Some((index, light.moved_to((p + grip - center) / radius, snap)));
|
||||
}
|
||||
}
|
||||
if response.has_focus() {
|
||||
ui.memory_mut(|m| {
|
||||
m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
|
||||
});
|
||||
// Every arrow-key press in the frame moves the light in turn, in the order it came.
|
||||
let presses = ui.input_mut(|i| {
|
||||
let mut presses = vec![];
|
||||
i.events.retain(|e| match e {
|
||||
egui::Event::Key { key, pressed: true, modifiers, .. }
|
||||
if ARROWS.contains(key) && (modifiers.matches_exact(Modifiers::NONE) || modifiers.matches_exact(Modifiers::SHIFT)) =>
|
||||
{
|
||||
presses.push((*key, if modifiers.shift { SHIFT_STEP } else { STEP }));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
presses
|
||||
});
|
||||
let mut next = light;
|
||||
for (key, step) in presses {
|
||||
if let Some((rotation, height)) = next.stepped(key, step) {
|
||||
(next.rotation, next.height) = (rotation, height);
|
||||
}
|
||||
}
|
||||
if next != light {
|
||||
moved = Some((index, (next.rotation, next.height)));
|
||||
}
|
||||
}
|
||||
paint_light(ui, at, light, index == current, response.has_focus(), response.hovered() || response.dragged());
|
||||
if response.hovered() || response.dragged() {
|
||||
ui.ctx().set_cursor_icon(if response.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
|
||||
}
|
||||
response.on_hover_text(tl!("Drag a light to move it. The arrow keys move the focused light; Shift steps 15°."));
|
||||
// What each event leaves in the lights, a cancel's restored start included.
|
||||
for lights in out.edit.events.iter().filter_map(|event| event.landed()) {
|
||||
write_moved(fields, &list, lights);
|
||||
}
|
||||
// Only a setting that moved is written: a press that leaves a light where it is, or a key at a
|
||||
// limit, changes nothing, and a key leaves the other setting as each selected effect has it.
|
||||
if let Some((index, (rotation, height))) = moved
|
||||
&& let Some(light) = lights.get(index)
|
||||
{
|
||||
for (key, value, was) in [("lightRotation", rotation, light.rotation), ("lightHeight", height, light.height)] {
|
||||
if (value - was).abs() > 1e-9 {
|
||||
select(ui, d, index);
|
||||
set_light_value(d, key, json!(value));
|
||||
}
|
||||
}
|
||||
let current = selected(fields, list.len());
|
||||
let behind = list.get(current).is_some_and(|l| l.behind);
|
||||
let text = if behind { tl!("Move Light to Front") } else { tl!("Move Light to Back") };
|
||||
if Button::new(text).show(ui).clicks > 0 {
|
||||
select(fields, current);
|
||||
set_light_value(fields, "lightBehind", json!(!behind));
|
||||
}
|
||||
let index = selected(d, lights.len());
|
||||
let behind = lights.get(index).is_some_and(|l| l.behind);
|
||||
ui.horizontal(|ui| {
|
||||
let text = if behind { tl!("Move Light to Front") } else { tl!("Move Light to Back") };
|
||||
if ui.button(text).clicked() {
|
||||
select(ui, d, index);
|
||||
set_light_value(d, "lightBehind", json!(!behind));
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
out.edit.response
|
||||
}
|
||||
|
||||
/// A light's sun: filled with its color in front of the object, hollow behind it, larger and
|
||||
/// ringed when it is the selected light, with a second ring while it has the keyboard focus.
|
||||
fn paint_light(ui: &egui::Ui, at: egui::Pos2, light: Light, selected: bool, focused: bool, hot: bool) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let painter = ui.painter();
|
||||
fn paint_light(painter: &egui::Painter, t: &Tokens, at: Pos2, light: Light, selected: bool, focused: bool, hot: bool) {
|
||||
let r = if selected { SUN } else { SUN - 2.0 };
|
||||
let outline = Stroke::new(if hot { 2.5 } else { 1.5 }, if selected { t.warning } else { t.warning.gamma_multiply(0.7) });
|
||||
if light.behind {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The track cube's rotations, grips and gestures.
|
||||
//! The track cube's rotations and grips.
|
||||
use super::*;
|
||||
use egui::pos2;
|
||||
use vectorcraft_effects::ROTATION_PRESETS;
|
||||
@@ -49,8 +49,7 @@ fn angles_stay_in_the_fields_range_to_a_hundredth() {
|
||||
}
|
||||
|
||||
fn drag(grip: Grip, angles: [f64; 3], from: Pos2, to: Pos2, shift: bool) -> [f64; 3] {
|
||||
let mut g =
|
||||
CubeDrag { grip, matrix: rotation(angles), origin: from, last: from, lock: None, fields: Default::default(), pass: 0, owner: Id::NULL };
|
||||
let mut g = CubeDrag { grip, matrix: rotation(angles), origin: from, last: from, lock: None };
|
||||
// In five steps, as a pointer moves.
|
||||
let mut near = angles;
|
||||
for k in 1..=5 {
|
||||
@@ -109,64 +108,6 @@ fn a_face_drag_turns_the_front_toward_the_pointer_and_shift_keeps_one_axis() {
|
||||
assert!(free[0].abs() > 1.0, "without Shift a slanted drag also tilts: {free:?}");
|
||||
}
|
||||
|
||||
/// A gesture ends when the cube stops being drawn during it (its dialog closed, or the Rotation tab
|
||||
/// was left), so Escape is not held back for a cube that is no longer there.
|
||||
#[test]
|
||||
fn a_drag_ends_when_the_cube_is_no_longer_drawn() {
|
||||
let ctx = egui::Context::default();
|
||||
let run = |draw: &mut dyn FnMut(&mut egui::Ui)| ctx.run_ui(Default::default(), draw).textures_delta.clear();
|
||||
run(&mut |ui| {
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
let drag = CubeDrag {
|
||||
grip: Grip::Face,
|
||||
matrix: rotation([0.0; 3]),
|
||||
origin: Pos2::ZERO,
|
||||
last: Pos2::ZERO,
|
||||
lock: None,
|
||||
fields: Default::default(),
|
||||
pass,
|
||||
owner: Id::NULL,
|
||||
};
|
||||
ui.data_mut(|m| m.insert_temp(cube_drag_id(), drag));
|
||||
assert!(cube_dragging(ui.ctx()));
|
||||
});
|
||||
assert!(cube_dragging(&ctx), "the next pass still sees the gesture");
|
||||
for _ in 0..2 {
|
||||
run(&mut |_| {});
|
||||
}
|
||||
assert!(!cube_dragging(&ctx), "two passes without the cube end the gesture");
|
||||
}
|
||||
|
||||
/// With the 3D and Materials panel and a 3D dialog both showing a cube, a gesture on one cube is
|
||||
/// left alone by the other: Escape there does not put the first cube's settings into it.
|
||||
#[test]
|
||||
fn a_cube_leaves_a_gesture_on_the_other_cube_alone() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut d = Dialog::new("effect", json!({ "rotationX": 10.0, "rotationY": 0.0, "rotationZ": 0.0 }));
|
||||
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
let input = egui::RawInput { events: vec![escape], ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
let other = CubeDrag {
|
||||
grip: Grip::Face,
|
||||
matrix: rotation([50.0, 0.0, 0.0]),
|
||||
origin: Pos2::ZERO,
|
||||
last: Pos2::ZERO,
|
||||
lock: None,
|
||||
fields: json!({ "rotationX": 50.0, "rotationY": 0.0, "rotationZ": 0.0 }).as_object().cloned().unwrap_or_default(),
|
||||
pass,
|
||||
owner: cube_id(crate::panels::three_d::ID),
|
||||
};
|
||||
assert_ne!(cube_id(crate::panels::three_d::ID), cube_id(&d.kind), "each cube has its own focus");
|
||||
ui.data_mut(|m| m.insert_temp(cube_drag_id(), other));
|
||||
track_cube(ui, &mut d);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(d.f64("rotationX", 0.0), 10.0, "the dialog keeps its own rotation");
|
||||
// The button is up in that pass, and the other cube, drawn later, still has the release to handle.
|
||||
assert!(ctx.data(|m| m.get_temp::<CubeDrag>(cube_drag_id())).is_some(), "the other cube's gesture is still there");
|
||||
}
|
||||
|
||||
/// The centre is on the front face, the ring's band on the ring, and an edge's middle on that edge.
|
||||
#[test]
|
||||
fn grips_follow_what_is_under_the_pointer() {
|
||||
@@ -182,37 +123,3 @@ fn grips_follow_what_is_under_the_pointer() {
|
||||
let m = rotation([0.0, 0.0, 0.0]);
|
||||
assert_eq!(edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)).count(), 4);
|
||||
}
|
||||
|
||||
/// Map Art lists each document's own surfaces: after a switch to another document whose object has
|
||||
/// the same id, effect settings and revision, the surfaces are those of the other document's object.
|
||||
#[test]
|
||||
fn map_art_surfaces_follow_the_active_document() {
|
||||
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
for d in ["M50 50L150 50L150 150L50 150Z", "M50 50L80 50L80 200L50 200Z"] {
|
||||
app.run("file.new", json!({"width":300,"height":300})).unwrap();
|
||||
app.run("path.create", json!({"d": d})).unwrap();
|
||||
}
|
||||
app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap();
|
||||
let d = app.ui.dialog.take().unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let key = |app: &crate::VectorcraftApp| {
|
||||
let st = app.session.active().unwrap();
|
||||
(st.selection.objects.first().copied(), st.revision)
|
||||
};
|
||||
let second = surfaces(&app, &ctx, &d).unwrap();
|
||||
let at_second = key(&app);
|
||||
assert!(app.session.set_active(0));
|
||||
assert_eq!(key(&app), at_second, "both documents' objects have the same id and revision");
|
||||
let first = surfaces(&app, &ctx, &d).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let id = st.selection.objects[0];
|
||||
let own = vectorcraft_effects::map_surfaces_with(
|
||||
Some(&st.doc),
|
||||
st.doc.node(id).unwrap(),
|
||||
(None, None),
|
||||
CLASSIC_EXTRUDE,
|
||||
&super::super::form::params(&d),
|
||||
);
|
||||
assert_ne!(first, second, "the two objects' solids differ in size");
|
||||
assert_eq!(Some(first.as_ref()), own.as_ref(), "the first document's surfaces");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
//! The track cube on the Rotation tab of Extrude & Bevel (Classic), Revolve (Classic) and Rotate
|
||||
//! (Classic): a cube drawn at the current X, Y and Z rotation inside a ring, dragged or keyed to turn the object.
|
||||
|
||||
// PLAN: assumed the app depends on craft-behavior and craft-ui-patterns (hub-w2 owns Cargo.toml).
|
||||
use craft::behavior::{CursorIcon, CursorPriority, Metrics as _, Mixed, PartKey, PointerButton, PressPhase, Sense};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Remember as _, Role, Show as _,
|
||||
};
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui_patterns::patterns::form_dialogs::Param;
|
||||
use egui::{Color32, Pos2, Rect, Stroke, Vec2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::revolve_lights::RowStyle;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The settings the track cube turns, as every 3D effect names them.
|
||||
const ROTATION_KEYS: [&str; 3] = ["rotationX", "rotationY", "rotationZ"];
|
||||
/// The track cube's box side, its cube's half edge, and its ring's inner and outer radius (points).
|
||||
const CUBE_BOX: f32 = 124.0;
|
||||
const CUBE_HALF: f32 = 25.0;
|
||||
const RING_IN: f32 = 47.0;
|
||||
const RING_OUT: f32 = 60.0;
|
||||
/// How far an edge reaches for the pointer (points).
|
||||
const EDGE_REACH: f32 = 5.0;
|
||||
/// Degrees one point of pointer movement turns the cube.
|
||||
const DEGREES_PER_POINT: f64 = 0.5;
|
||||
/// The cube's one part: its box. The grip a press takes is chosen from the pointer, as edges, faces and the ring overlap.
|
||||
const CUBE: PartKey = PartKey::new("cube");
|
||||
|
||||
/// A 3×3 rotation, rows first.
|
||||
type M3 = [[f64; 3]; 3];
|
||||
|
||||
/// The rotation that X, Y and Z angles in degrees make, as the 3D effects apply them: X first, then
|
||||
/// Y, then Z, in view space (x right, y down, z toward the viewer).
|
||||
fn rotation(angles: [f64; 3]) -> M3 {
|
||||
let [(sx, cx), (sy, cy), (sz, cz)] = angles.map(|a| a.to_radians().sin_cos());
|
||||
[[cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx], [sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx], [-sy, cy * sx, cy * cx]]
|
||||
}
|
||||
|
||||
fn multiply(a: M3, b: M3) -> M3 {
|
||||
std::array::from_fn(|i| std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum()))
|
||||
}
|
||||
|
||||
/// The unit vector along axis `axis` (0 X, 1 Y, 2 Z).
|
||||
fn unit(axis: usize) -> [f64; 3] {
|
||||
std::array::from_fn(|i| if i == axis { 1.0 } else { 0.0 })
|
||||
}
|
||||
|
||||
/// A turn of `degrees` about the unit vector `axis`.
|
||||
fn turn(axis: [f64; 3], degrees: f64) -> M3 {
|
||||
let (s, c) = degrees.to_radians().sin_cos();
|
||||
let t = 1.0 - c;
|
||||
let [x, y, z] = axis;
|
||||
[
|
||||
[t * x * x + c, t * x * y - s * z, t * x * z + s * y],
|
||||
[t * x * y + s * z, t * y * y + c, t * y * z - s * x],
|
||||
[t * x * z - s * y, t * y * z + s * x, t * z * z + c],
|
||||
]
|
||||
}
|
||||
|
||||
/// An angle as the rotation fields hold it: above -180° up to 180°, to a hundredth of a degree.
|
||||
fn tidy(degrees: f64) -> f64 {
|
||||
let wrapped = 180.0 - (180.0 - degrees).rem_euclid(360.0);
|
||||
(wrapped * 100.0).round() / 100.0 + 0.0
|
||||
}
|
||||
|
||||
/// The X, Y and Z angles of rotation `m`. Of the two sets of angles that make it, the one nearest
|
||||
/// `near` (so a turn moves the fields as little as it can); with Y at ±90°, where X and Z turn about
|
||||
/// the same axis, X keeps its value from `near`.
|
||||
fn angles_of(m: M3, near: [f64; 3]) -> [f64; 3] {
|
||||
let y = (-m[2][0]).clamp(-1.0, 1.0).asin().to_degrees();
|
||||
let candidates = if m[2][1].hypot(m[2][2]) < 1e-9 {
|
||||
let x = near[0];
|
||||
let z = if y > 0.0 { x - m[0][1].atan2(m[1][1]).to_degrees() } else { (-m[0][1]).atan2(m[1][1]).to_degrees() - x };
|
||||
[Some([x, y, z]), None]
|
||||
} else {
|
||||
let x = m[2][1].atan2(m[2][2]).to_degrees();
|
||||
let z = m[1][0].atan2(m[0][0]).to_degrees();
|
||||
[Some([x, y, z]), Some([x + 180.0, 180.0 - y, z + 180.0])]
|
||||
};
|
||||
let distance = |a: &[f64; 3]| a.iter().zip(near).map(|(a, b)| tidy(a - b).abs()).sum::<f64>();
|
||||
candidates.into_iter().flatten().min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap_or(near).map(tidy)
|
||||
}
|
||||
|
||||
/// Where corner `i` of the cube (bit 0 for +X, bit 1 for +Y, bit 2 for +Z) is drawn.
|
||||
fn corner(m: M3, center: Pos2, i: usize) -> Pos2 {
|
||||
let p: [f64; 3] = std::array::from_fn(|b| if i >> b & 1 == 1 { 1.0 } else { -1.0 });
|
||||
let v: [f64; 3] = std::array::from_fn(|r| (0..3).map(|k| m[r][k] * p[k]).sum());
|
||||
center + vec2(v[0] as f32, v[1] as f32) * CUBE_HALF
|
||||
}
|
||||
|
||||
/// The corners of the face square to `axis` on its positive or negative side, in order round it.
|
||||
fn face_corners(axis: usize, positive: bool) -> [usize; 4] {
|
||||
let (b, c) = (1 << ((axis + 1) % 3), 1 << ((axis + 2) % 3));
|
||||
let side = if positive { 1 << axis } else { 0 };
|
||||
[0, b, b | c, c].map(|k| side | k)
|
||||
}
|
||||
|
||||
/// Does the face square to `axis` on that side face the viewer?
|
||||
fn face_visible(m: M3, axis: usize, positive: bool) -> bool {
|
||||
m[2][axis] * if positive { 1.0 } else { -1.0 } > 1e-6
|
||||
}
|
||||
|
||||
/// The 12 edges: (from corner, to corner, the object axis it runs along).
|
||||
fn edges() -> impl Iterator<Item = (usize, usize, usize)> {
|
||||
(0..3).flat_map(|axis| (0..8).filter(move |i| i >> axis & 1 == 0).map(move |i| (i, i | 1 << axis, axis)))
|
||||
}
|
||||
|
||||
/// Is the edge from corner `i` along `axis` on a face the viewer sees?
|
||||
fn edge_visible(m: M3, i: usize, axis: usize) -> bool {
|
||||
[(axis + 1) % 3, (axis + 2) % 3].into_iter().any(|other| face_visible(m, other, i >> other & 1 == 1))
|
||||
}
|
||||
|
||||
/// What a press on the track cube takes hold of.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Grip {
|
||||
/// A face: a free turn, or with Shift about the screen's horizontal or vertical axis.
|
||||
Face,
|
||||
/// An edge: a turn about the object axis the edge runs along.
|
||||
Edge(usize),
|
||||
/// The ring round the cube: a turn in the plane of the screen.
|
||||
Ring,
|
||||
}
|
||||
|
||||
/// The z of the cross product of two screen vectors: positive when `b` is clockwise from `a`.
|
||||
fn cross(a: Vec2, b: Vec2) -> f32 {
|
||||
a.x * b.y - a.y * b.x
|
||||
}
|
||||
|
||||
fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 {
|
||||
let line = b - a;
|
||||
let t = ((p - a).dot(line) / line.length_sq().max(1e-6)).clamp(0.0, 1.0);
|
||||
p.distance(a + line * t)
|
||||
}
|
||||
|
||||
/// What the pointer at `p` takes hold of on a cube drawn at `m` about `center`: the nearest edge
|
||||
/// within reach, else a face, else the ring, else (in the box's corners) a face's free turn.
|
||||
fn grip_at(m: M3, center: Pos2, p: Pos2) -> Grip {
|
||||
let edge = edges()
|
||||
.filter(|&(i, _, axis)| edge_visible(m, i, axis))
|
||||
.map(|(i, j, axis)| (segment_distance(p, corner(m, center, i), corner(m, center, j)), axis))
|
||||
.filter(|(distance, _)| *distance <= EDGE_REACH)
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((_, axis)) = edge {
|
||||
return Grip::Edge(axis);
|
||||
}
|
||||
let on_face = (0..3).flat_map(|axis| [(axis, true), (axis, false)]).filter(|&(axis, side)| face_visible(m, axis, side)).any(|(axis, side)| {
|
||||
let points = face_corners(axis, side).map(|i| corner(m, center, i));
|
||||
let sides: [f32; 4] = std::array::from_fn(|k| cross(points[(k + 1) % 4] - points[k], p - points[k]));
|
||||
sides.iter().all(|s| *s >= 0.0) || sides.iter().all(|s| *s <= 0.0)
|
||||
});
|
||||
let distance = p.distance(center);
|
||||
if !on_face && (RING_IN - 3.0..=RING_OUT + 3.0).contains(&distance) { Grip::Ring } else { Grip::Face }
|
||||
}
|
||||
|
||||
/// The turn in degrees, clockwise on the screen, from `from` to `to` about `center`.
|
||||
fn sweep(from: Pos2, to: Pos2, center: Pos2) -> f64 {
|
||||
let (a, b) = (from - center, to - center);
|
||||
if a.length() < 2.0 || b.length() < 2.0 {
|
||||
return 0.0;
|
||||
}
|
||||
f64::from(cross(a, b)).atan2(f64::from(a.dot(b))).to_degrees()
|
||||
}
|
||||
|
||||
/// A track cube gesture in progress.
|
||||
#[derive(Clone, Copy)]
|
||||
struct CubeDrag {
|
||||
grip: Grip,
|
||||
/// The rotation so far, kept unrounded so a long drag does not drift.
|
||||
matrix: M3,
|
||||
origin: Pos2,
|
||||
last: Pos2,
|
||||
/// With Shift, the screen axis the drag keeps to (0 X, 1 Y), chosen once it has moved 3 points.
|
||||
lock: Option<usize>,
|
||||
}
|
||||
|
||||
/// The rotation after the pointer moves from `drag.last` to `p` on a cube about `center`.
|
||||
fn drag_turn(drag: &mut CubeDrag, p: Pos2, center: Pos2, shift: bool) -> M3 {
|
||||
let m = drag.matrix;
|
||||
let delta = p - drag.last;
|
||||
let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y));
|
||||
match drag.grip {
|
||||
Grip::Face => {
|
||||
if shift {
|
||||
let total = p - drag.origin;
|
||||
if drag.lock.is_none() && total.length() >= 3.0 {
|
||||
drag.lock = Some(usize::from(total.x.abs() >= total.y.abs()));
|
||||
}
|
||||
match drag.lock {
|
||||
// Across the screen turns about its vertical (Y) axis, up and down about X.
|
||||
Some(1) => dy = 0.0,
|
||||
Some(_) => dx = 0.0,
|
||||
None => return m,
|
||||
}
|
||||
}
|
||||
let length = dx.hypot(dy);
|
||||
if length < 1e-9 {
|
||||
return m;
|
||||
}
|
||||
// The front follows the pointer: right turns it toward +X, down toward +Y.
|
||||
multiply(turn([-dy / length, dx / length, 0.0], length * DEGREES_PER_POINT), m)
|
||||
}
|
||||
Grip::Ring => multiply(turn(unit(2), sweep(drag.last, p, center)), m),
|
||||
Grip::Edge(axis) => {
|
||||
let w = [m[0][axis], m[1][axis], m[2][axis]];
|
||||
let across = w[0].hypot(w[1]);
|
||||
// An axis pointing at the viewer turns like the ring, on the side it points to.
|
||||
let degrees =
|
||||
if w[2].abs() > 0.9 { sweep(drag.last, p, center) * w[2].signum() } else { (dx * w[1] - dy * w[0]) / across * DEGREES_PER_POINT };
|
||||
multiply(m, turn(unit(axis), degrees))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The angles a cube value holds; a mixed one reads 0, as the cube is off while any is mixed.
|
||||
fn degrees(value: &[Mixed<f64>; 3]) -> [f64; 3] {
|
||||
value.each_ref().map(|m| if let Mixed::Same(v) = m { *v } else { 0.0 })
|
||||
}
|
||||
|
||||
/// The cube's value for `angles`.
|
||||
fn same(angles: [f64; 3]) -> [Mixed<f64>; 3] {
|
||||
angles.map(Mixed::Same)
|
||||
}
|
||||
|
||||
/// The cube turned by the pointer at `p`, as the value the gesture proposes.
|
||||
fn dragged(drag: &mut CubeDrag, p: Pos2, center: Pos2, shift: bool, near: [f64; 3]) -> [Mixed<f64>; 3] {
|
||||
drag.matrix = drag_turn(drag, p, center, shift);
|
||||
drag.last = p;
|
||||
same(angles_of(drag.matrix, near))
|
||||
}
|
||||
|
||||
/// The track cube: a cube drawn at the current X, Y and Z rotation (the object's front blue, its top and bottom light gray,
|
||||
/// its sides mid gray and its back dark gray) inside a ring. The value is the three angles; it is off while any is mixed
|
||||
/// (the 3D and Materials panel's selected effects differ).
|
||||
///
|
||||
/// - Pointer: dragging a face turns the object freely; with Shift the turn keeps to the screen's vertical axis (a drag
|
||||
/// across) or its horizontal axis (a drag up or down), whichever the drag follows first. Dragging an edge turns it about
|
||||
/// the object axis the edge runs along (the edge takes its axis's color while hovered or dragged), and dragging in the
|
||||
/// ring turns it in the plane of the screen. A click that does not drag changes nothing. Escape puts the angles back.
|
||||
/// - Keyboard: one Tab stop; the arrows turn the cube about the screen's axes and Page Up and Page Down in the screen
|
||||
/// plane, 1° a press (15° with Shift), every press of a pass in turn.
|
||||
/// - AccessKit: a `Slider` named by the label with the three angles as its value text.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub(crate) struct TrackCube<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
angles: Bind<'a, [Mixed<f64>; 3]>,
|
||||
/// The grip the pointer is over or holds.
|
||||
active: Option<Grip>,
|
||||
}
|
||||
|
||||
impl<'a> TrackCube<'a> {
|
||||
/// A cube named `label` showing `angles`.
|
||||
pub(crate) fn new(label: impl Into<craft_ui::runtime::env::Label>, angles: Bind<'a, [Mixed<f64>; 3]>) -> Self {
|
||||
TrackCube { common: Common::new(), angles, active: None }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for TrackCube<'_> {
|
||||
const DISABLED: DisabledLook = DisabledLook::Faded;
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const SHOWS_LABEL: bool = false;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither).with_moves();
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = RowStyle;
|
||||
type Output = EditResponse<[Mixed<f64>; 3]>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: TrackCubeStyleKey) -> RowStyle {
|
||||
RowStyle::of(cx)
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(CUBE_BOX)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.part(CUBE, rect)
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.tooltip(tl!("Drag a face, an edge or the ring to rotate. Shift turns about one screen axis."))
|
||||
.focusable();
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, [Mixed<f64>; 3]>> {
|
||||
Some(self.angles.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let now = cx.value().map(degrees).unwrap_or_default();
|
||||
let center = cx.rect.center();
|
||||
let mut held = *cx.press_slot::<CubeDrag>();
|
||||
let result = cx.part(CUBE);
|
||||
let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered));
|
||||
match press.phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
|
||||
cx.focus_part(CUBE);
|
||||
let matrix = rotation(now);
|
||||
held = Some(CubeDrag { grip: grip_at(matrix, center, start.origin), matrix, origin: start.origin, last: start.origin, lock: None });
|
||||
}
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
|
||||
if let Some(drag) = held.as_mut() {
|
||||
if matches!(press.phase, PressPhase::DragStart { .. }) {
|
||||
cx.begin();
|
||||
}
|
||||
cx.propose(dragged(drag, pos, center, press.mods.shift, now));
|
||||
}
|
||||
}
|
||||
PressPhase::Release { pos, .. } => {
|
||||
// A click that never dragged ran no gesture and changes nothing.
|
||||
if let Some(drag) = held.as_mut()
|
||||
&& cx.gesture().is_some()
|
||||
{
|
||||
cx.propose(dragged(drag, pos, center, press.mods.shift, now));
|
||||
cx.commit();
|
||||
}
|
||||
held = None;
|
||||
}
|
||||
PressPhase::Cancel { .. } => held = None,
|
||||
_ => {}
|
||||
}
|
||||
*cx.press_slot::<CubeDrag>() = held;
|
||||
self.active = held.map(|drag| drag.grip).or_else(|| hover.map(|p| grip_at(rotation(now), center, p)));
|
||||
match (held, self.active) {
|
||||
(Some(drag), _) => {
|
||||
let icon = if matches!(drag.grip, Grip::Edge(_)) { CursorIcon::ResizeHorizontal } else { CursorIcon::Grabbing };
|
||||
cx.cursor(icon, CursorPriority::Drag);
|
||||
}
|
||||
(None, Some(grip)) if hover.is_some() => {
|
||||
let icon = if matches!(grip, Grip::Edge(_)) { CursorIcon::ResizeHorizontal } else { CursorIcon::Grab };
|
||||
cx.cursor(icon, CursorPriority::Part);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if cx.gesture().is_none() && cx.active_part() == Some(CUBE.into()) {
|
||||
let mut m = rotation(now);
|
||||
let mut turned = false;
|
||||
while let Some((key, mods)) = cx.intents().take_move() {
|
||||
use craft::behavior::NavMove;
|
||||
let (axis, sign) = match key {
|
||||
NavMove::Forward => (1, 1.0),
|
||||
NavMove::Back => (1, -1.0),
|
||||
NavMove::Up => (0, 1.0),
|
||||
NavMove::Down => (0, -1.0),
|
||||
NavMove::PageDown => (2, 1.0),
|
||||
NavMove::PageUp => (2, -1.0),
|
||||
_ => continue,
|
||||
};
|
||||
if mods.lead || mods.fine {
|
||||
continue;
|
||||
}
|
||||
m = multiply(turn(unit(axis), sign * if mods.extend { 15.0 } else { 1.0 }), m);
|
||||
turned = true;
|
||||
}
|
||||
let next = angles_of(m, now);
|
||||
if turned && next.iter().zip(now).any(|(a, b)| (a - b).abs() > 1e-9) {
|
||||
cx.set(same(next));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let [x, y, z] = cx.value().map(degrees).unwrap_or_default();
|
||||
access.node(CUBE, Role::SLIDER).name = Name::Text(tl!("Track cube").to_owned());
|
||||
access.node(CUBE, Role::SLIDER).value(format!("X {x:.2}°, Y {y:.2}°, Z {z:.2}°"));
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let m = rotation(cx.value().map(degrees).unwrap_or_default());
|
||||
let content = ui.content_painter(cx);
|
||||
paint_cube(&content.painter, cx.rect, m, self.active, cx.is_focused());
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<[Mixed<f64>; 3]> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// The track cube's row on the Rotation page of the 3D (Classic) effects. It reads and writes `rotationX`, `rotationY` and
|
||||
/// `rotationZ` (a missing one reads the effect's default) and only writes an angle that changes; the dialog's preview applies
|
||||
/// them and OK records them as one undo step. Its control's events go to the rows, so a drag previews and Escape restores.
|
||||
pub(crate) fn row() -> Param {
|
||||
Param::custom("__trackCube", tl!("Track cube"), |ui, fields, cx| {
|
||||
let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({}));
|
||||
let now = ROTATION_KEYS.map(|key| {
|
||||
if fields.is_mixed(key) {
|
||||
Mixed::Mixed
|
||||
} else {
|
||||
Mixed::Same(fields.number(key).unwrap_or_else(|| defaults.get(key).and_then(serde_json::Value::as_f64).unwrap_or(0.0)))
|
||||
}
|
||||
});
|
||||
let mixed = now.iter().any(|m| matches!(m, Mixed::Mixed));
|
||||
let out = TrackCube::new(tl!("Track cube"), Bind::given(now.clone())).enabled(!mixed).show(ui);
|
||||
cx.gesture(&out.events);
|
||||
let was = degrees(&now);
|
||||
// What each event leaves in the cube, a cancel's restored start included.
|
||||
for next in out.events.iter().filter_map(|event| event.landed()) {
|
||||
for ((key, angle), old) in ROTATION_KEYS.into_iter().zip(degrees(next)).zip(was) {
|
||||
if (angle - old).abs() > 1e-9 {
|
||||
fields.set(key, angle);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.response
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws the track cube at rotation `m` in `rect`, with the grip under the pointer or in hand lit.
|
||||
fn paint_cube(painter: &egui::Painter, rect: Rect, m: M3, active: Option<Grip>, focused: bool) {
|
||||
let t = Tokens::get(painter.ctx());
|
||||
let center = rect.center();
|
||||
painter.rect_filled(rect, 2.0, t.input);
|
||||
let ring = if active == Some(Grip::Ring) { 0.6 } else { 0.3 };
|
||||
painter.circle_stroke(center, (RING_IN + RING_OUT) / 2.0, Stroke::new(RING_OUT - RING_IN, t.axis_z.gamma_multiply(ring)));
|
||||
// Front blue; top and bottom light, sides mid and back dark gray. Only faces turned to the
|
||||
// viewer are drawn, and on a cube those never overlap.
|
||||
for (axis, side) in (0..3).flat_map(|axis| [(axis, true), (axis, false)]) {
|
||||
if !face_visible(m, axis, side) {
|
||||
continue;
|
||||
}
|
||||
// PLAN: the gray steps are literals; the data tokens of area plan §2 w3 were not visible to this writer.
|
||||
let fill = match (axis, side) {
|
||||
(2, true) => t.axis_z,
|
||||
(2, false) => Color32::from_gray(90),
|
||||
(1, _) => Color32::from_gray(205),
|
||||
_ => Color32::from_gray(155),
|
||||
};
|
||||
let points: Vec<Pos2> = face_corners(axis, side).iter().map(|&i| corner(m, center, i)).collect();
|
||||
painter.add(egui::Shape::convex_polygon(points, fill, Stroke::NONE));
|
||||
}
|
||||
let colors = [t.axis_x, t.axis_y, t.axis_z];
|
||||
for (i, j, axis) in edges() {
|
||||
if !edge_visible(m, i, axis) {
|
||||
continue;
|
||||
}
|
||||
let lit = active == Some(Grip::Edge(axis));
|
||||
let stroke = if lit { Stroke::new(2.5, colors[axis]) } else { Stroke::new(1.0, t.text_dim) };
|
||||
painter.line_segment([corner(m, center, i), corner(m, center, j)], stroke);
|
||||
}
|
||||
let border = if focused { t.accent } else { t.input_border };
|
||||
painter.rect_stroke(rect, 2.0, Stroke::new(1.0, border), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_track_cube.rs"]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user