3D mouse calibration in Preferences (#2326)

Adds a 3D mouse calibration section to Preferences (#1463).
This commit is contained in:
The Nomad
2026-10-19 16:07:38 -04:00
committed by GitHub
parent 45ae7c00e0
commit d3fa22e987
26 changed files with 2461 additions and 52 deletions
Generated
+4
View File
@@ -4268,6 +4268,9 @@ dependencies = [
[[package]]
name = "solidcraft-space-mouse"
version = "0.16.2"
dependencies = [
"serde",
]
[[package]]
name = "solidcraft-ui-egui"
@@ -4286,6 +4289,7 @@ dependencies = [
"sha2 0.10.9",
"solidcraft-engine",
"solidcraft-gpu",
"solidcraft-space-mouse",
"tiny-skia",
"toml",
"ttf-parser",
+99 -17
View File
@@ -7,7 +7,7 @@
//! navigation takes them with 3DxWare's object-mode mapping, as the Linux app does without a
//! profile.
use solidcraft_ui_egui::space_mouse::{Axes, FULL_SCALE};
use solidcraft_ui_egui::space_mouse::{Axes, Calibration, FULL_SCALE, calibrated};
/// Logitech's vendor id, which older 3Dconnexion devices carry, and those devices' product ids
/// (usb.ids). Logitech's own gamepads and wheels carry the same vendor id.
@@ -60,9 +60,43 @@ pub fn axes(values: &[f64]) -> Option<Axes> {
Some(Axes { translation: [raw(0)?, raw(1)?, raw(2)?], rotation: [raw(3)?, raw(4)?, raw(5)?] })
}
/// What a calibration of the gamepad with this id is saved under: `web` and its vendor and
/// product ids.
pub fn device_key(id: &str) -> Option<String> {
vendor_product(id).map(|(vendor, product)| format!("web {vendor:04x}:{product:04x}"))
}
/// The 3D mouse to read among the ones listed: the first device, else the first joystick.
pub fn choose(found: impl IntoIterator<Item = (Source, Axes)>) -> Option<Axes> {
found.into_iter().min_by_key(|(source, _)| *source).map(|(_, axes)| axes)
pub fn choose<T>(found: impl IntoIterator<Item = (Source, T)>) -> Option<T> {
found.into_iter().min_by_key(|(source, _)| *source).map(|(_, reading)| reading)
}
/// Whether the cap is moving as the next frame will see it: through the device's calibration
/// (as of the last frame) when it has one. The idle page wakes for a short-range device's push,
/// and not for a device resting off zero; the wheel filter goes by the same.
pub fn moving(axes: Axes, calibration: Option<Calibration>) -> bool {
calibrated(axes, calibration).moving()
}
/// The calibration as of the last frame, and the device it was for.
pub type Cached = (Option<String>, Option<Calibration>);
/// Whether the cap of `device` is moving, judged with the calibration kept from the last frame:
/// `None` when that was for another device, so another's calibration never judges this one. The
/// waker then lets a frame look, which brings the cache up to date.
pub fn moving_as_cached(device: &Option<String>, axes: Axes, cached: &Cached) -> Option<bool> {
(*device == cached.0).then(|| moving(axes, cached.1))
}
/// Whether the idle page's timer redraws: when the cap is moving as the last frame's calibration
/// judges it, when the device read isn't the one that calibration was for (a frame then judges
/// it with its own), and once when the device the last frame read is gone, so the page shows
/// that. With no device, and none last frame, it stays quiet.
pub fn wakes(reading: Option<(Option<String>, Axes)>, cached: &Cached) -> bool {
match reading {
Some((device, axes)) => moving_as_cached(&device, axes, cached).unwrap_or(true),
None => cached.0.is_some(),
}
}
#[cfg(target_arch = "wasm32")]
@@ -70,29 +104,29 @@ pub use browser::SpaceMouse;
#[cfg(target_arch = "wasm32")]
mod browser {
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use solidcraft_ui_egui::SolveApp;
use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, navigate_frame};
use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, calibration, navigate_frame};
use wasm_bindgen::JsCast as _;
use wasm_bindgen::closure::Closure;
use solidcraft_ui_egui::space_mouse::WheelGuard;
use super::{axes, choose, source};
use super::{Cached, axes, choose, device_key, moving_as_cached, source, wakes};
/// How often the page looks for the cap starting to move while nothing else redraws.
const WAKE_MS: i32 = 50;
/// The 3D mouse the browser lists, if any.
fn read() -> Option<Axes> {
/// The 3D mouse the browser lists, if any: its calibration key and its axes.
fn read() -> Option<(Option<String>, Axes)> {
let pads = web_sys::window()?.navigator().get_gamepads().ok()?;
choose(pads.iter().filter_map(|pad| {
let pad = pad.dyn_into::<web_sys::Gamepad>().ok().filter(web_sys::Gamepad::connected)?;
let source = source(&pad.id())?;
let values: Vec<f64> = pad.axes().iter().map(|v| v.as_f64().unwrap_or(f64::NAN)).collect();
Some((source, axes(&values)?))
Some((source, (device_key(&pad.id()), axes(&values)?)))
}))
}
@@ -100,6 +134,8 @@ mod browser {
#[derive(Default)]
pub struct SpaceMouse {
axes: Axes,
/// The 3D mouse being read, as `SolveApp::space_mouse` keeps it.
device: Option<String>,
/// The previous frame's time and the step since it (seconds).
last: Option<f64>,
seconds: f64,
@@ -111,6 +147,8 @@ mod browser {
waking: bool,
/// Navigation is on (the waker reads it).
enabled: Rc<Cell<bool>>,
/// The calibration as of the last frame and its device (the waker and the wheel filter read it).
cached: Rc<RefCell<Cached>>,
}
impl SpaceMouse {
@@ -131,14 +169,18 @@ mod browser {
}
let reading = read();
if reading.is_some() && !self.waking {
self.waking = wake(ctx, &self.enabled);
self.waking = wake(ctx, &self.enabled, &self.cached);
}
// Inside the dead zone is rest: a cap resting just off zero doesn't keep redrawing.
self.axes = reading.filter(|axes| axes.moving()).unwrap_or_default();
self.wheel.filter(self.axes.moving(), now, &mut raw.events);
// As read: calibration needs the readings at rest too, and `navigate_frame` leaves a
// cap resting inside the dead zone alone.
(self.device, self.axes) = reading.unwrap_or_default();
let moving = moving_as_cached(&self.device, self.axes, &self.cached.borrow()).unwrap_or_else(|| self.axes.moving());
self.wheel.filter(moving, now, &mut raw.events);
}
pub fn logic(&self, app: &mut SolveApp, ctx: &egui::Context) {
app.space_mouse.device.clone_from(&self.device);
*self.cached.borrow_mut() = (self.device.clone(), calibration(app));
navigate_frame(app, ctx, DriverMapping::object_mode(), self.axes, self.seconds);
}
}
@@ -156,11 +198,11 @@ mod browser {
/// The browser sends no event when a gamepad moves, so a timer looks while the app is idle and
/// redraws when the cap starts moving; the frames that follow keep going on their own.
fn wake(ctx: &egui::Context, enabled: &Rc<Cell<bool>>) -> bool {
fn wake(ctx: &egui::Context, enabled: &Rc<Cell<bool>>, cached: &Rc<RefCell<Cached>>) -> bool {
let Some(window) = web_sys::window() else { return false };
let (ctx, enabled) = (ctx.clone(), Rc::clone(enabled));
let (ctx, enabled, cached) = (ctx.clone(), Rc::clone(enabled), Rc::clone(cached));
let tick = Closure::<dyn FnMut()>::new(move || {
if enabled.get() && read().is_some_and(Axes::moving) {
if enabled.get() && wakes(read(), &cached.borrow()) {
ctx.request_repaint();
}
});
@@ -192,6 +234,46 @@ mod tests {
}
}
#[test]
fn a_calibration_is_saved_under_the_ids_whichever_browser_lists_it() {
assert_eq!(device_key("SpaceMouse Pro (Vendor: 046d Product: c62b)").as_deref(), Some("web 046d:c62b"));
assert_eq!(device_key("46d-c62b-SpaceMouse Pro").as_deref(), Some("web 046d:c62b"));
assert_eq!(device_key("Xbox Wireless Controller"), None);
}
#[test]
fn the_idle_page_wakes_for_motion_as_calibrated_not_as_read() {
let axis =
|source, rest, full| solidcraft_ui_egui::space_mouse::AxisCalibration { source, reversed: false, rest, dead_zone: 0, full: [full; 2] };
// A short-range device: 15 of its 50 is under the raw dead zone, but 105 of 350 calibrated.
let short = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 0, 50)) };
let push = Axes { translation: [15, 0, 0], rotation: [0; 3] };
assert!(!push.moving() && moving(push, Some(short)));
// A device resting at 100 on every axis: past the raw dead zone, but at rest calibrated.
let offset = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 100, 350)) };
let resting = Axes { translation: [100; 3], rotation: [100; 3] };
assert!(resting.moving() && !moving(resting, Some(offset)));
// Without a calibration, as read.
assert!(!moving(push, None) && moving(resting, None));
// Kept from the last frame: only for the device it was for.
let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string()));
assert_eq!(moving_as_cached(&b, push, &(b.clone(), Some(short))), Some(true));
assert_eq!(moving_as_cached(&b, push, &(a.clone(), Some(offset))), None, "A's calibration doesn't judge B");
assert_eq!(moving_as_cached(&b, push, &(None, None)), None);
assert_eq!(moving_as_cached(&a, resting, &(a.clone(), None)), Some(true), "A was read without a calibration");
}
#[test]
fn the_idle_page_wakes_once_for_a_device_change_and_stays_quiet_without_one() {
let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string()));
let still = Axes::default();
let last_frame_read_a: Cached = (a.clone(), None);
assert!(!wakes(Some((a.clone(), still)), &last_frame_read_a), "A, at rest");
assert!(wakes(Some((b.clone(), still)), &last_frame_read_a), "A to B: a frame looks at B");
assert!(wakes(None, &last_frame_read_a), "A to none: a frame shows it's gone");
assert!(!wakes(None, &(None, None)), "none to none: quiet");
}
#[test]
fn gamepads_and_other_logitech_devices_are_not_3d_mice() {
for id in [
@@ -280,6 +362,6 @@ mod tests {
assert_eq!(choose([(Source::VirtualJoystick, other)]), Some(other));
// Two devices: the first listed.
assert_eq!(choose([(Source::Device, moving), (Source::Device, other)]), Some(moving));
assert_eq!(choose([]), None);
assert_eq!(choose::<Axes>([]), None);
}
}
+172 -26
View File
@@ -19,7 +19,7 @@ use quick_xml::Reader;
use quick_xml::events::Event;
use solidcraft_space_mouse::Layout;
use solidcraft_ui_egui::SolveApp;
use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, WheelGuard, navigate_frame};
use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, Calibration, DriverMapping, WheelGuard, calibrated, calibration, navigate_frame};
const STALE_AFTER: Duration = Duration::from_millis(150);
/// Whether the 3Dconnexion driver (macOS) has the device: it then reports the cap, and reading
@@ -165,8 +165,36 @@ fn load_driver_mapping() -> Option<DriverMapping> {
parse_driver_mapping(&xml)
}
/// Where the reading comes from, which a calibration is saved under (`Source::key`).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Source {
/// The device itself, with its vendor and product ids when known.
Hid(Option<(u16, u16)>),
/// spacenavd, which may have swapped or inverted axes on its own (`spnavcfg`).
#[cfg(target_os = "linux")]
Spacenavd,
/// The 3Dconnexion driver (macOS), which applies its own settings first.
#[cfg(target_os = "macos")]
Driver,
}
impl Source {
fn key(self) -> String {
match self {
Self::Hid(Some((vendor, product))) => format!("hid {vendor:04x}:{product:04x}"),
Self::Hid(None) => "hid".into(),
#[cfg(target_os = "linux")]
Self::Spacenavd => "spacenavd".into(),
#[cfg(target_os = "macos")]
Self::Driver => "3dxware".into(),
}
}
}
#[derive(Clone, Copy)]
struct Reading {
/// The device being read; none between devices.
device: Option<Source>,
axes: Axes,
/// When each of X, Y, Z, Rx, Ry and Rz last arrived. Each ages on its own: a device may send
/// translation and rotation in separate reports, or spread even one group over several.
@@ -179,15 +207,18 @@ struct Reading {
impl Reading {
fn new(now: Instant) -> Self {
Self { axes: Axes::default(), at: [now; 6], held: false }
Self { device: None, axes: Axes::default(), at: [now; 6], held: false }
}
fn current(self, now: Instant) -> Axes {
/// The axes at `now`. One with nothing fresh reads as `rest`: the device's own rest when it
/// is calibrated, so a device that rests off zero calibrates to no motion rather than drifting.
fn current(self, now: Instant, rest: Axes) -> Axes {
let mut axes = self.axes;
if !self.held {
for (value, at) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at) {
let rest = rest.translation.into_iter().chain(rest.rotation);
for ((value, at), rest) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at).zip(rest) {
if now.duration_since(at) >= STALE_AFTER {
*value = 0;
*value = rest;
}
}
}
@@ -195,6 +226,11 @@ impl Reading {
}
}
/// The raw axes at the device's rest, which calibrate to no motion; 0 without a calibration.
fn at_rest(calibration: Option<Calibration>) -> Axes {
calibration.map(|calibration| calibration.raw_rest().into()).unwrap_or_default()
}
/// The Generic Desktop "Multi-Axis Controller" usage names a 3D mouse's motion interface, whoever
/// made it, and excludes ordinary mice and the keyboard interfaces of 3D mice.
#[cfg(any(target_os = "windows", target_os = "macos"))]
@@ -233,11 +269,22 @@ fn publish(ctx: &Context, shared: &Mutex<Reading>, layout: Layout, report: &[u8]
#[cfg(target_os = "linux")]
fn publish_held(ctx: &Context, shared: &Mutex<Reading>, axes: Axes) {
if let Ok(mut reading) = shared.lock() {
*reading = Reading { axes, held: true, ..Reading::new(Instant::now()) };
*reading = Reading { device: reading.device, axes, held: true, ..Reading::new(Instant::now()) };
ctx.request_repaint();
}
}
/// A device is open: say which, so its calibration applies.
fn connected(ctx: &Context, shared: &Mutex<Reading>, source: Source) {
if let Ok(mut reading) = shared.lock() {
// Nothing has arrived from it yet, so every axis starts out stale.
let now = Instant::now();
let stale = now.checked_sub(STALE_AFTER).unwrap_or(now);
*reading = Reading { device: Some(source), at: [stale; 6], ..Reading::new(now) };
}
ctx.request_repaint();
}
/// The device is gone: stop reporting its last position.
fn reset(ctx: &Context, shared: &Mutex<Reading>) {
if let Ok(mut reading) = shared.lock() {
@@ -255,7 +302,7 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
loop {
if let Err(error) = api.refresh_devices() {
log::warn!("3D mouse: device scan failed: {error}");
} else if let Some((device, layout)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| {
} else if let Some((device, layout, ids)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| {
let device = info
.open_device(&api)
.inspect_err(|error| {
@@ -267,8 +314,9 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
})
.ok()?;
let layout = device_layout(&device, info.vendor_id())?;
Some((device, layout))
Some((device, layout, (info.vendor_id(), info.product_id())))
}) {
connected(&ctx, &shared, Source::Hid(Some(ids)));
let mut report = [0_u8; REPORT_BUFFER_BYTES];
loop {
match device.read_timeout(&mut report, 100) {
@@ -323,6 +371,7 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
loop {
if let Some(daemon) = spacenavd::connect() {
log::info!("3D mouse: reading spacenavd, which applies the spnavcfg settings");
connected(&ctx, &shared, Source::Spacenavd);
spacenavd::read(daemon, |axes| publish_held(&ctx, &shared, axes));
reset(&ctx, &shared);
} else if let Some(device) = hidraw::find() {
@@ -330,6 +379,7 @@ fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
Ok(mut file) => {
denied = None;
log::info!("3D mouse: reading {}", device.path.display());
connected(&ctx, &shared, Source::Hid(device.ids));
let mut report = [0_u8; REPORT_BUFFER_BYTES];
loop {
match file.read(&mut report) {
@@ -365,7 +415,10 @@ fn start_driver_client(ctx: &Context, shared: &Arc<Mutex<Reading>>) {
let started = solidcraft_3dx_client::start(
"SolidCraft",
move |event| match event {
Event::DeviceAdded => DRIVER_CONNECTED.store(true, Ordering::Relaxed),
Event::DeviceAdded => {
DRIVER_CONNECTED.store(true, Ordering::Relaxed);
connected(&ctx, &shared, Source::Driver);
}
Event::DeviceRemoved => {
DRIVER_CONNECTED.store(false, Ordering::Relaxed);
reset(&ctx, &shared);
@@ -398,6 +451,9 @@ pub struct SpaceMouse {
/// Drops 3DxWare's emulated wheel while the cap moves (#1380).
wheel: WheelGuard,
started: Instant,
/// The calibration as of the last frame and the device it is for, for the wheel filter, which
/// runs before the app sees the frame.
calibration: Option<(Source, Calibration)>,
}
impl SpaceMouse {
@@ -418,6 +474,7 @@ impl SpaceMouse {
mapping_checked_at: now,
wheel: WheelGuard::default(),
started: now,
calibration: None,
}
}
@@ -431,7 +488,15 @@ impl SpaceMouse {
if !enabled {
return;
}
let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false);
let moving = self
.shared
.lock()
.map(|reading| {
// Only the calibration of the device being read: another's would misjudge it.
let calibration = self.calibration.filter(|(source, _)| Some(*source) == reading.device).map(|(_, calibration)| calibration);
calibrated(reading.current(now, at_rest(calibration)), calibration).moving()
})
.unwrap_or(false);
self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events);
}
@@ -451,11 +516,16 @@ impl SpaceMouse {
}
self.mapping_checked_at = now;
}
let axes = match self.shared.lock() {
Ok(reading) => reading.current(now),
Err(_) => return,
};
navigate_frame(app, ctx, self.driver_mapping, axes, seconds);
let Ok(reading) = self.shared.lock().map(|reading| *reading) else { return };
app.space_mouse.device = reading.device.map(Source::key);
let calibration = calibration(app);
self.calibration = reading.device.zip(calibration);
// While this device is being calibrated, an axis with nothing fresh reads 0, as a HID
// device's silence means: the old calibration's rest isn't fed back into the new one. A
// calibration of another device doesn't count; it ends in `navigate_frame`.
let calibrating = app.space_mouse.calibrating.as_ref().is_some_and(|(device, _)| app.space_mouse.device.as_ref() == Some(device));
let rest = if calibrating { Axes::default() } else { at_rest(calibration) };
navigate_frame(app, ctx, self.driver_mapping, reading.current(now, rest), seconds);
}
}
@@ -477,14 +547,14 @@ mod tests {
let mut reading = Reading::new(now);
let layout = Layout::default();
assert!(!decode_report(&[1, 1, 2], layout, &mut reading, now));
assert_eq!(reading.current(now), Axes::default());
assert_eq!(reading.current(now, Axes::default()), Axes::default());
assert!(decode_report(&[1, 0x9c, 0xff, 0x2c, 0x01, 0, 0], layout, &mut reading, now));
assert!(decode_report(&[2, 0, 0, 1, 0, 0xff, 0xff], layout, &mut reading, now));
assert_eq!(reading.current(now), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] });
assert_eq!(reading.current(now, Axes::default()), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] });
// Only rotation arrives again: translation goes stale, rotation stays current.
let later = now + STALE_AFTER + Duration::from_millis(1);
assert!(decode_report(&[2, 4, 0, 5, 0, 6, 0], layout, &mut reading, later));
assert_eq!(reading.current(later), Axes { translation: [0; 3], rotation: [4, 5, 6] });
assert_eq!(reading.current(later, Axes::default()), Axes { translation: [0; 3], rotation: [4, 5, 6] });
// A device sending all six in one report updates both at once.
let combined = solidcraft_space_mouse::Descriptor::parse(&[
0x05, 0x01, 0x09, 0x08, 0xA1, 0x01, 0x85, 0x01, 0x16, 0xA2, 0xFE, 0x26, 0x5E, 0x01, 0x75, 0x10, 0x95, 0x06, 0x19, 0x30, 0x29, 0x35, 0x81,
@@ -494,7 +564,7 @@ mod tests {
.expect("six axes declared");
let mut both = Reading::new(now);
assert!(decode_report(&[1, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0], combined, &mut both, now));
assert_eq!(both.current(now), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] });
assert_eq!(both.current(now, Axes::default()), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] });
}
#[test]
@@ -513,11 +583,11 @@ mod tests {
let mut reading = Reading::new(now);
assert!(decode_report(&[1, 100, 0], split_x_y, &mut reading, now));
assert!(decode_report(&[2, 200, 0], split_x_y, &mut reading, now));
assert_eq!(reading.current(now).translation, [100, 200, 0]);
assert_eq!(reading.current(now, Axes::default()).translation, [100, 200, 0]);
// Then only X keeps coming: Y goes stale on its own.
let later = now + STALE_AFTER + Duration::from_millis(1);
assert!(decode_report(&[1, 50, 0], split_x_y, &mut reading, later));
assert_eq!(reading.current(later).translation, [50, 0, 0]);
assert_eq!(reading.current(later, Axes::default()).translation, [50, 0, 0]);
}
#[test]
@@ -530,8 +600,8 @@ mod tests {
let mut reading = Reading::new(now);
assert!(decode_report(&[1, 100, 0, 0, 0, 0, 0], layout, &mut reading, now));
// Just before the timeout X is still there; at exactly the timeout it's stale.
assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1)).translation, [100, 0, 0]);
assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]);
assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1), Axes::default()).translation, [100, 0, 0]);
assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]);
// Button reports and reports with an id the layout doesn't know keep coming, but neither
// refreshes X: it goes stale on time all the same.
for step in 1..=10 {
@@ -539,7 +609,7 @@ mod tests {
assert!(decode_report(&[3, 1], layout, &mut reading, at));
assert!(!decode_report(&[0x17, 80], layout, &mut reading, at));
}
assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]);
assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]);
}
#[test]
@@ -549,10 +619,10 @@ mod tests {
let later = now + STALE_AFTER * 20;
// spacenavd sends nothing while the values stay the same: the push lasts.
let held = Reading { axes, held: true, ..Reading::new(now) };
assert_eq!(held.current(later), axes);
assert_eq!(held.current(later, Axes::default()), axes);
// A HID device repeats its report: silence means the cap, or the device, is gone.
let hid = Reading { axes, ..Reading::new(now) };
assert_eq!(hid.current(later), Axes::default());
assert_eq!(hid.current(later, Axes::default()), Axes::default());
}
#[test]
@@ -624,6 +694,7 @@ mod tests {
mapping_checked_at: now,
wheel: WheelGuard::default(),
started: now,
calibration: None,
};
// A window that has run a frame with focus, as the app's always has by now.
let ctx = Context::default();
@@ -651,9 +722,84 @@ mod tests {
mapping_checked_at: now,
wheel: WheelGuard::default(),
started: now,
calibration: None,
}
}
const DEVICE: Source = Source::Hid(Some((0x1234, 0x5678)));
/// A device whose raw axes all rest at 100, calibrated as such.
fn resting_at_100() -> Calibration {
Calibration {
dead_zone_share: 0.0,
axes: std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration {
source,
reversed: false,
rest: 100,
dead_zone: 0,
full: [350; 2],
}),
}
}
#[test]
fn a_calibrated_device_resting_off_zero_leaves_the_wheel_alone() {
// Read raw, X at 100 is the cap pushed past the dead zone: the wheel is dropped.
let now = Instant::now();
let mut resting = Reading::new(now);
resting.device = Some(DEVICE);
resting.axes = Axes { translation: [100; 3], rotation: [100; 3] };
let wheel_kept = |calibration| {
let mut mouse = mouse(resting, now);
mouse.calibration = calibration;
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
mouse.raw_input_hook_at(true, &mut raw, now);
raw.events.len() == 1
};
assert!(!wheel_kept(None));
// Calibrated, it's at rest, so the wheel is the user's.
assert!(wheel_kept(Some((DEVICE, resting_at_100()))));
// Another device's calibration, kept from the last frame, isn't used for this one.
assert!(!wheel_kept(Some((Source::Hid(Some((0x256f, 0xc63a))), resting_at_100()))));
}
#[test]
fn a_calibrated_device_resting_off_zero_doesnt_drift_when_nothing_fresh_arrives() {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
app.home.open = false;
app.preferences.space_mouse_calibrations.insert(DEVICE.key(), resting_at_100());
// A window that has run a frame with focus, as the app's always has by now.
let ctx = Context::default();
let mut frame = ctx.run_ui(egui::RawInput::default(), |_| {});
frame.textures_delta.clear();
let motion = |app: &mut SolveApp, reading: Reading, now: Instant| {
let mut mouse = mouse(reading, now);
mouse.last_frame = now - Duration::from_millis(20);
app.viewport.device_motion = None;
mouse.tick_at(app, &ctx, now);
app.viewport.device_motion.is_some()
};
// Connected, and nothing reported yet.
let shared = Mutex::new(Reading::new(Instant::now()));
connected(&Context::default(), &shared, DEVICE);
let fresh = *shared.lock().unwrap();
let now = Instant::now();
assert!(!motion(&mut app, fresh, now), "connected, nothing reported yet");
// The same, while another device's calibration window was open: it ends, and this one
// doesn't move on the first frame either.
app.space_mouse.calibrating = Some(("hid 256f:c63a".into(), solidcraft_space_mouse::Wizard::default()));
assert!(!motion(&mut app, fresh, now), "connected mid-calibration of another device");
assert!(app.space_mouse.calibrating.is_none());
// Translation reported at rest, rotation not for a while.
let old = now - STALE_AFTER - Duration::from_millis(1);
let partly = Reading { axes: Axes { translation: [100; 3], rotation: [0; 3] }, at: [now, now, now, old, old, old], ..fresh };
assert!(!motion(&mut app, partly, now), "translation at rest, rotation stale");
// Pushed, then the reports stopped.
let pushed = Reading { axes: Axes { translation: [450, 100, 100], rotation: [100; 3] }, at: [old; 6], ..fresh };
assert!(!motion(&mut app, pushed, now), "the push timed out");
assert!(motion(&mut app, Reading { at: [now; 6], ..pushed }, now), "a fresh push moves the view");
}
#[test]
fn the_wheel_3dxware_makes_from_the_cap_is_dropped() {
// The cap tilted forward: 3DxWare also sends wheel turns (#1380). They are dropped.
+27 -3
View File
@@ -1,6 +1,6 @@
//! Finding a 3D mouse on Linux. The kernel exposes every HID interface as `/dev/hidrawN`, with
//! its report descriptor under `/sys/class/hidraw/hidrawN/device/`. Reading it is plain file
//! I/O, so no udev or hidapi library is needed.
//! its report descriptor and ids under `/sys/class/hidraw/hidrawN/device/`. Reading them is plain
//! file I/O, so no udev or hidapi library is needed.
use std::path::{Path, PathBuf};
@@ -12,6 +12,8 @@ const DEV: &str = "/dev";
pub struct Device {
pub path: PathBuf,
pub layout: Layout,
/// Its vendor and product ids, when the kernel gives them.
pub ids: Option<(u16, u16)>,
}
/// The first hidraw interface that is a multi-axis controller with motion axes, whoever made it.
@@ -25,5 +27,27 @@ fn probe(sysfs: &Path, path: PathBuf) -> Option<Device> {
let descriptor = Descriptor::parse(&std::fs::read(sysfs.join("device/report_descriptor")).ok()?);
// A controller that declares no motion axis (buttons only, say) isn't read.
let layout = descriptor.is_multi_axis_controller().then(|| descriptor.layout()).flatten()?;
Some(Device { path, layout })
let ids = std::fs::read_to_string(sysfs.join("device/uevent")).ok().as_deref().and_then(ids);
Some(Device { path, layout, ids })
}
/// The vendor and product ids in a HID device's uevent: `HID_ID=bus:vendor:product`, in hex.
fn ids(uevent: &str) -> Option<(u16, u16)> {
let id = uevent.lines().find_map(|line| line.strip_prefix("HID_ID="))?;
let mut hex = id.split(':').skip(1).map(|part| u32::from_str_radix(part, 16).ok().and_then(|v| u16::try_from(v).ok()));
Some((hex.next()??, hex.next()??))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_come_from_the_uevent() {
let wireless = "DRIVER=hid-generic\nHID_ID=0005:0000256F:0000C63A\nHID_NAME=SpaceMouse Wireless BT\n";
assert_eq!(ids(wireless), Some((0x256f, 0xc63a)));
assert_eq!(ids("HID_ID=0003:0000046D\n"), None);
assert_eq!(ids("HID_ID=0003:0001046D:0000C62B\n"), None, "a vendor past 16 bits isn't a USB id");
assert_eq!(ids("HID_NAME=keyboard\n"), None);
}
}
+28
View File
@@ -993,6 +993,7 @@
"ui.autosave_every": "Automaticky ukládat každých",
"ui.axes": "Osy",
"ui.axis": "Osa",
"ui.back": "Zpět",
"ui.base_point": "Základní bod",
"ui.blocked": "Blokováno",
"ui.bodies": "Tělesa",
@@ -1398,8 +1399,34 @@
"ui.smooth_wheel_zoom": "Plynulé přiblížení kolečkem",
"ui.smooth_wheel_zoom_tip": "Vypnutím se každý pohyb kolečka projeví okamžitě, bez dobíhání",
"ui.snap": "Přichytávání",
"ui.space_mouse_calibrate": "Kalibrovat…",
"ui.space_mouse_calibrate_tip": "Pohybujte hlavicí podle pokynů v okně, aby se SolidCraft naučil, kterým směrem a jak daleko se pohybuje každá osa této 3D myši. Uloží se pro tuto 3D myš.",
"ui.space_mouse_calibrate_title": "Kalibrace 3D myši",
"ui.space_mouse_calibrated": "Zkalibrováno",
"ui.space_mouse_calibration": "Kalibrace 3D myši",
"ui.space_mouse_calibration_done": "Hotovo. Uložte ji a použije se vždy, když bude tato 3D myš připojená.",
"ui.space_mouse_calibration_no_response": "Jedna osa se skoro nepohnula, takže ji nelze zkalibrovat. Začněte znovu a pokaždé hlavicí pohněte dál.",
"ui.space_mouse_dead_zone": "Mrtvá zóna",
"ui.space_mouse_dead_zone_tip": "Jak daleko se musí hlavice pohnout, než se pohne pohled, jako podíl jejího plného rozsahu. Zvyšte ji, pokud pohled ujíždí, i když je hlavice v klidu.",
"ui.space_mouse_forget": "Zapomenout kalibraci",
"ui.space_mouse_hint": "Posun a otáčení pohledu současně; náčrty používají jen posun a přiblížení.",
"ui.space_mouse_navigate": "Navigace pomocí SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "3D myš nenalezena",
"ui.space_mouse_not_calibrated": "Nezkalibrováno",
"ui.space_mouse_reading": "Hodnoty",
"ui.space_mouse_step_lift": "Zvedněte hlavici nahoru, podržte a pusťte.",
"ui.space_mouse_step_press": "Zatlačte hlavici dolů, podržte a pusťte.",
"ui.space_mouse_step_pull": "Přitáhněte hlavici k sobě, podržte a pusťte.",
"ui.space_mouse_step_push": "Odtlačte hlavici od sebe, podržte a pusťte.",
"ui.space_mouse_step_rest": "Dejte ruku z hlavice a nechte ji v klidu.",
"ui.space_mouse_step_slide_left": "Posuňte hlavici doleva, podržte a pusťte.",
"ui.space_mouse_step_slide_right": "Posuňte hlavici doprava, podržte a pusťte.",
"ui.space_mouse_step_tilt_back": "Nakloňte hlavici dozadu (přední hrana nahoru), podržte a pusťte.",
"ui.space_mouse_step_tilt_forward": "Nakloňte hlavici dopředu (přední hrana dolů), podržte a pusťte.",
"ui.space_mouse_step_tilt_left": "Nakloňte hlavici doleva (levá hrana dolů), podržte a pusťte.",
"ui.space_mouse_step_tilt_right": "Nakloňte hlavici doprava (pravá hrana dolů), podržte a pusťte.",
"ui.space_mouse_step_twist_clockwise": "Otočte hlavici po směru hodinových ručiček, podržte a pusťte.",
"ui.space_mouse_step_twist_counterclockwise": "Otočte hlavici proti směru hodinových ručiček, podržte a pusťte.",
"ui.spacing": "Rozteč",
"ui.spacing_2": "Rozteč 2",
"ui.sphere": "Koule",
@@ -1407,6 +1434,7 @@
"ui.split_body": "Rozdělit těleso",
"ui.stand_up_tip": "Když se soubor STEP nebo IGES otevře s osou Z nahoru, nabídnout otočení o čtvrt otáčky kolem X",
"ui.start": "Start",
"ui.start_over": "Začít znovu",
"ui.start_radius": "Počáteční poloměr",
"ui.supersampling": "Supersampling (SSAA)",
"ui.supersampling_adaptive": "Jen když je pohled v klidu",
+28
View File
@@ -782,6 +782,7 @@
"ui.autosave_every": "Autospeichern alle",
"ui.axes": "Achsen",
"ui.axis": "Achse",
"ui.back": "Zurück",
"ui.base_point": "Basispunkt",
"ui.blocked": "Verdeckt",
"ui.bodies": "Körper",
@@ -1177,12 +1178,39 @@
"ui.slot": "Langloch",
"ui.smooth": "Glatt",
"ui.snap": "Einrasten",
"ui.space_mouse_calibrate": "Kalibrieren…",
"ui.space_mouse_calibrate_tip": "Bewegen Sie die Kappe so, wie das Fenster es verlangt. So lernt SolidCraft, in welche Richtung und wie weit jede Achse dieser 3D-Maus geht. Wird für diese 3D-Maus gespeichert.",
"ui.space_mouse_calibrate_title": "3D-Maus kalibrieren",
"ui.space_mouse_calibrated": "Kalibriert",
"ui.space_mouse_calibration": "3D-Maus-Kalibrierung",
"ui.space_mouse_calibration_done": "Fertig. Speichern Sie die Kalibrierung, damit sie immer gilt, wenn diese 3D-Maus angeschlossen ist.",
"ui.space_mouse_calibration_no_response": "Eine Achse hat sich kaum bewegt und lässt sich nicht kalibrieren. Beginnen Sie von vorn und bewegen Sie die Kappe jedes Mal weiter.",
"ui.space_mouse_dead_zone": "Totzone",
"ui.space_mouse_dead_zone_tip": "Wie weit sich die Kappe bewegen muss, bevor sich die Ansicht bewegt, als Anteil ihres vollen Wegs. Erhöhen Sie sie, wenn die Ansicht wandert, obwohl die Kappe ruht.",
"ui.space_mouse_forget": "Kalibrierung vergessen",
"ui.space_mouse_none": "Keine 3D-Maus gefunden",
"ui.space_mouse_not_calibrated": "Nicht kalibriert",
"ui.space_mouse_reading": "Werte",
"ui.space_mouse_step_lift": "Kappe nach oben ziehen, halten, dann loslassen.",
"ui.space_mouse_step_press": "Kappe nach unten drücken, halten, dann loslassen.",
"ui.space_mouse_step_pull": "Kappe zu sich heranziehen, halten, dann loslassen.",
"ui.space_mouse_step_push": "Kappe von sich wegschieben, halten, dann loslassen.",
"ui.space_mouse_step_rest": "Nehmen Sie die Hand von der Kappe und lassen Sie sie ruhen.",
"ui.space_mouse_step_slide_left": "Kappe nach links schieben, halten, dann loslassen.",
"ui.space_mouse_step_slide_right": "Kappe nach rechts schieben, halten, dann loslassen.",
"ui.space_mouse_step_tilt_back": "Kappe nach hinten kippen (Vorderkante hoch), halten, dann loslassen.",
"ui.space_mouse_step_tilt_forward": "Kappe nach vorn kippen (Vorderkante runter), halten, dann loslassen.",
"ui.space_mouse_step_tilt_left": "Kappe nach links kippen (linke Kante runter), halten, dann loslassen.",
"ui.space_mouse_step_tilt_right": "Kappe nach rechts kippen (rechte Kante runter), halten, dann loslassen.",
"ui.space_mouse_step_twist_clockwise": "Kappe im Uhrzeigersinn drehen, halten, dann loslassen.",
"ui.space_mouse_step_twist_counterclockwise": "Kappe gegen den Uhrzeigersinn drehen, halten, dann loslassen.",
"ui.spacing": "Abstand",
"ui.spacing_2": "Abstand 2",
"ui.sphere": "Sphäre",
"ui.spline": "Spline",
"ui.split_body": "Körper trennen",
"ui.start": "Start",
"ui.start_over": "Von vorn beginnen",
"ui.start_radius": "Startradius",
"ui.stretch": "Strecken",
"ui.supersampling": "Supersampling (SSAA)",
+28
View File
@@ -1074,6 +1074,7 @@
"ui.autosave_every": "Autosave every",
"ui.axes": "Axes",
"ui.axis": "Axis",
"ui.back": "Back",
"ui.base_point": "Base point",
"ui.blocked": "Blocked",
"ui.bodies": "Bodies",
@@ -1508,8 +1509,34 @@
"ui.smooth_wheel_zoom": "Smooth wheel zoom",
"ui.smooth_wheel_zoom_tip": "Turn off to apply each wheel event immediately, without a smoothing tail",
"ui.snap": "Snap",
"ui.space_mouse_calibrate": "Calibrate…",
"ui.space_mouse_calibrate_tip": "Move the cap as the window asks, so SolidCraft learns which way each axis of this 3D mouse goes and how far. Saved for this 3D mouse.",
"ui.space_mouse_calibrate_title": "Calibrate 3D mouse",
"ui.space_mouse_calibrated": "Calibrated",
"ui.space_mouse_calibration": "3D mouse calibration",
"ui.space_mouse_calibration_done": "Done. Save it to use it whenever this 3D mouse is connected.",
"ui.space_mouse_calibration_no_response": "One axis barely moved, so it can't be calibrated. Start over and move the cap further each time.",
"ui.space_mouse_dead_zone": "Dead zone",
"ui.space_mouse_dead_zone_tip": "How far the cap has to move before the view does, as a share of its full travel. Raise it if the view drifts while the cap is at rest.",
"ui.space_mouse_forget": "Forget calibration",
"ui.space_mouse_hint": "Move and rotate the view together; sketches use pan and zoom only.",
"ui.space_mouse_navigate": "Navigate with SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "No 3D mouse found",
"ui.space_mouse_not_calibrated": "Not calibrated",
"ui.space_mouse_reading": "Reading",
"ui.space_mouse_step_lift": "Lift the cap up, hold it, then let go.",
"ui.space_mouse_step_press": "Press the cap down, hold it, then let go.",
"ui.space_mouse_step_pull": "Pull the cap toward you, hold it, then let go.",
"ui.space_mouse_step_push": "Push the cap away from you, hold it, then let go.",
"ui.space_mouse_step_rest": "Take your hand off the cap and leave it still.",
"ui.space_mouse_step_slide_left": "Slide the cap left, hold it, then let go.",
"ui.space_mouse_step_slide_right": "Slide the cap right, hold it, then let go.",
"ui.space_mouse_step_tilt_back": "Tilt the cap back (front edge up), hold it, then let go.",
"ui.space_mouse_step_tilt_forward": "Tilt the cap forward (front edge down), hold it, then let go.",
"ui.space_mouse_step_tilt_left": "Tilt the cap left (left edge down), hold it, then let go.",
"ui.space_mouse_step_tilt_right": "Tilt the cap right (right edge down), hold it, then let go.",
"ui.space_mouse_step_twist_clockwise": "Twist the cap clockwise, hold it, then let go.",
"ui.space_mouse_step_twist_counterclockwise": "Twist the cap anticlockwise, hold it, then let go.",
"ui.spacing": "Spacing",
"ui.spacing_2": "Spacing 2",
"ui.sphere": "Sphere",
@@ -1517,6 +1544,7 @@
"ui.split_body": "Split Body",
"ui.stand_up_tip": "After a STEP or IGES file opens with Z up, offer a quarter turn about X",
"ui.start": "Start",
"ui.start_over": "Start over",
"ui.start_radius": "Start Radius",
"ui.stretch": "Stretch",
"ui.supersampling": "Supersampling (SSAA)",
+28
View File
@@ -1012,6 +1012,7 @@
"ui.autosave_every": "Guardar automáticamente cada",
"ui.axes": "Ejes",
"ui.axis": "Eje",
"ui.back": "Atrás",
"ui.base_point": "Punto base",
"ui.blocked": "Bloqueado",
"ui.bodies": "Cuerpos",
@@ -1425,8 +1426,34 @@
"ui.smooth_wheel_zoom": "Zoom suave con la rueda",
"ui.smooth_wheel_zoom_tip": "Desactívalo para aplicar cada movimiento de la rueda inmediatamente, sin suavizado posterior",
"ui.snap": "Referencia a objetos",
"ui.space_mouse_calibrate": "Calibrar…",
"ui.space_mouse_calibrate_tip": "Mueve el capuchón como pide la ventana para que SolidCraft aprenda hacia dónde y hasta dónde va cada eje de este ratón 3D. Se guarda para este ratón 3D.",
"ui.space_mouse_calibrate_title": "Calibrar ratón 3D",
"ui.space_mouse_calibrated": "Calibrado",
"ui.space_mouse_calibration": "Calibración del ratón 3D",
"ui.space_mouse_calibration_done": "Listo. Guárdala para usarla siempre que este ratón 3D esté conectado.",
"ui.space_mouse_calibration_no_response": "Un eje apenas se movió, así que no se puede calibrar. Vuelve a empezar y mueve el capuchón más lejos cada vez.",
"ui.space_mouse_dead_zone": "Zona muerta",
"ui.space_mouse_dead_zone_tip": "Cuánto tiene que moverse el capuchón antes de que se mueva la vista, como parte de su recorrido completo. Auméntala si la vista se desplaza con el capuchón en reposo.",
"ui.space_mouse_forget": "Olvidar calibración",
"ui.space_mouse_hint": "Desplaza y gira la vista a la vez; los bocetos solo permiten desplazamiento y zoom.",
"ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "No se encontró ningún ratón 3D",
"ui.space_mouse_not_calibrated": "Sin calibrar",
"ui.space_mouse_reading": "Lectura",
"ui.space_mouse_step_lift": "Levanta el capuchón, mantenlo y suéltalo.",
"ui.space_mouse_step_press": "Presiona el capuchón hacia abajo, mantenlo y suéltalo.",
"ui.space_mouse_step_pull": "Tira del capuchón hacia ti, mantenlo y suéltalo.",
"ui.space_mouse_step_push": "Empuja el capuchón lejos de ti, mantenlo y suéltalo.",
"ui.space_mouse_step_rest": "Suelta el capuchón y déjalo quieto.",
"ui.space_mouse_step_slide_left": "Desliza el capuchón a la izquierda, mantenlo y suéltalo.",
"ui.space_mouse_step_slide_right": "Desliza el capuchón a la derecha, mantenlo y suéltalo.",
"ui.space_mouse_step_tilt_back": "Inclina el capuchón hacia atrás (borde delantero arriba), mantenlo y suéltalo.",
"ui.space_mouse_step_tilt_forward": "Inclina el capuchón hacia delante (borde delantero abajo), mantenlo y suéltalo.",
"ui.space_mouse_step_tilt_left": "Inclina el capuchón a la izquierda (borde izquierdo abajo), mantenlo y suéltalo.",
"ui.space_mouse_step_tilt_right": "Inclina el capuchón a la derecha (borde derecho abajo), mantenlo y suéltalo.",
"ui.space_mouse_step_twist_clockwise": "Gira el capuchón en sentido horario, mantenlo y suéltalo.",
"ui.space_mouse_step_twist_counterclockwise": "Gira el capuchón en sentido antihorario, mantenlo y suéltalo.",
"ui.spacing": "Espaciado",
"ui.spacing_2": "Espaciado 2",
"ui.sphere": "Esfera",
@@ -1434,6 +1461,7 @@
"ui.split_body": "Dividir cuerpo",
"ui.stand_up_tip": "Tras abrir un archivo STEP o IGES con Z hacia arriba, ofrecer un cuarto de vuelta alrededor de X",
"ui.start": "Iniciar",
"ui.start_over": "Volver a empezar",
"ui.start_radius": "Radio inicial",
"ui.stretch": "Estirar",
"ui.supersampling": "Supermuestreo (SSAA)",
+28
View File
@@ -1021,6 +1021,7 @@
"ui.autosave_every": "Enregistrement automatique toutes les",
"ui.axes": "Axes",
"ui.axis": "Axe",
"ui.back": "Retour",
"ui.base_point": "Point de base",
"ui.blocked": "Inaccessible",
"ui.bodies": "Corps",
@@ -1441,8 +1442,34 @@
"ui.smooth_wheel_zoom": "Zoom fluide à la molette",
"ui.smooth_wheel_zoom_tip": "Désactiver pour appliquer chaque cran de molette immédiatement, sans lissage",
"ui.snap": "Accrochage",
"ui.space_mouse_calibrate": "Calibrer…",
"ui.space_mouse_calibrate_tip": "Déplacez le capuchon comme la fenêtre le demande, pour que SolidCraft apprenne dans quel sens et jusqu'où va chaque axe de cette souris 3D. Enregistré pour cette souris 3D.",
"ui.space_mouse_calibrate_title": "Calibrer la souris 3D",
"ui.space_mouse_calibrated": "Calibrée",
"ui.space_mouse_calibration": "Calibrage de la souris 3D",
"ui.space_mouse_calibration_done": "Terminé. Enregistrez-le pour l'utiliser chaque fois que cette souris 3D est connectée.",
"ui.space_mouse_calibration_no_response": "Un axe a à peine bougé, il ne peut donc pas être calibré. Recommencez en déplaçant le capuchon plus loin à chaque fois.",
"ui.space_mouse_dead_zone": "Zone morte",
"ui.space_mouse_dead_zone_tip": "De combien le capuchon doit bouger avant que la vue ne bouge, en part de sa course complète. Augmentez-la si la vue dérive alors que le capuchon est au repos.",
"ui.space_mouse_forget": "Oublier le calibrage",
"ui.space_mouse_hint": "Déplace et fait pivoter la vue en même temps ; dans les esquisses, seuls le panoramique et le zoom sont utilisés.",
"ui.space_mouse_navigate": "Naviguer avec SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "Aucune souris 3D trouvée",
"ui.space_mouse_not_calibrated": "Non calibrée",
"ui.space_mouse_reading": "Lecture",
"ui.space_mouse_step_lift": "Soulevez le capuchon, maintenez, puis relâchez.",
"ui.space_mouse_step_press": "Appuyez sur le capuchon, maintenez, puis relâchez.",
"ui.space_mouse_step_pull": "Tirez le capuchon vers vous, maintenez, puis relâchez.",
"ui.space_mouse_step_push": "Poussez le capuchon loin de vous, maintenez, puis relâchez.",
"ui.space_mouse_step_rest": "Lâchez le capuchon et laissez-le immobile.",
"ui.space_mouse_step_slide_left": "Glissez le capuchon vers la gauche, maintenez, puis relâchez.",
"ui.space_mouse_step_slide_right": "Glissez le capuchon vers la droite, maintenez, puis relâchez.",
"ui.space_mouse_step_tilt_back": "Inclinez le capuchon vers l'arrière (bord avant vers le haut), maintenez, puis relâchez.",
"ui.space_mouse_step_tilt_forward": "Inclinez le capuchon vers l'avant (bord avant vers le bas), maintenez, puis relâchez.",
"ui.space_mouse_step_tilt_left": "Inclinez le capuchon vers la gauche (bord gauche vers le bas), maintenez, puis relâchez.",
"ui.space_mouse_step_tilt_right": "Inclinez le capuchon vers la droite (bord droit vers le bas), maintenez, puis relâchez.",
"ui.space_mouse_step_twist_clockwise": "Tournez le capuchon dans le sens horaire, maintenez, puis relâchez.",
"ui.space_mouse_step_twist_counterclockwise": "Tournez le capuchon dans le sens antihoraire, maintenez, puis relâchez.",
"ui.spacing": "Espacement",
"ui.spacing_2": "Espacement 2",
"ui.sphere": "Sphère",
@@ -1450,6 +1477,7 @@
"ui.split_body": "Scinder le corps",
"ui.stand_up_tip": "Après l'ouverture d'un fichier STEP ou IGES avec Z vers le haut, proposer un quart de tour autour de X",
"ui.start": "Début",
"ui.start_over": "Recommencer",
"ui.start_radius": "Rayon initial",
"ui.stretch": "Étirer",
"ui.supersampling": "Suréchantillonnage (SSAA)",
+28
View File
@@ -984,6 +984,7 @@
"ui.autosave_every": "Gardar automaticamente cada",
"ui.axes": "Eixes",
"ui.axis": "Eixe",
"ui.back": "Atrás",
"ui.base_point": "Punto base",
"ui.blocked": "Bloqueado",
"ui.bodies": "Corpos",
@@ -1389,8 +1390,34 @@
"ui.smooth_wheel_zoom": "Zoom suave coa roda",
"ui.smooth_wheel_zoom_tip": "Desactívao para aplicar cada movemento da roda de inmediato, sen suavizado",
"ui.snap": "Axuste",
"ui.space_mouse_calibrate": "Calibrar…",
"ui.space_mouse_calibrate_tip": "Move o capuchón como pide a xanela para que SolidCraft aprenda cara a onde e ata onde vai cada eixe deste rato 3D. Gárdase para este rato 3D.",
"ui.space_mouse_calibrate_title": "Calibrar o rato 3D",
"ui.space_mouse_calibrated": "Calibrado",
"ui.space_mouse_calibration": "Calibración do rato 3D",
"ui.space_mouse_calibration_done": "Feito. Gárdaa para usala sempre que este rato 3D estea conectado.",
"ui.space_mouse_calibration_no_response": "Un eixe case non se moveu, así que non se pode calibrar. Volve comezar e move o capuchón máis lonxe cada vez.",
"ui.space_mouse_dead_zone": "Zona morta",
"ui.space_mouse_dead_zone_tip": "Canto ten que moverse o capuchón antes de que se mova a vista, como parte do seu percorrido completo. Auméntaa se a vista se despraza co capuchón en repouso.",
"ui.space_mouse_forget": "Esquecer a calibración",
"ui.space_mouse_hint": "Move e rota a vista á vez; os bosquexos só usan desprazamento e zoom.",
"ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "Non se atopou ningún rato 3D",
"ui.space_mouse_not_calibrated": "Sen calibrar",
"ui.space_mouse_reading": "Lectura",
"ui.space_mouse_step_lift": "Levanta o capuchón, mantéño e sóltao.",
"ui.space_mouse_step_press": "Preme o capuchón cara abaixo, mantéño e sóltao.",
"ui.space_mouse_step_pull": "Tira do capuchón cara a ti, mantéño e sóltao.",
"ui.space_mouse_step_push": "Empurra o capuchón lonxe de ti, mantéño e sóltao.",
"ui.space_mouse_step_rest": "Solta o capuchón e déixao quieto.",
"ui.space_mouse_step_slide_left": "Despraza o capuchón á esquerda, mantéño e sóltao.",
"ui.space_mouse_step_slide_right": "Despraza o capuchón á dereita, mantéño e sóltao.",
"ui.space_mouse_step_tilt_back": "Inclina o capuchón cara atrás (bordo dianteiro arriba), mantéño e sóltao.",
"ui.space_mouse_step_tilt_forward": "Inclina o capuchón cara adiante (bordo dianteiro abaixo), mantéño e sóltao.",
"ui.space_mouse_step_tilt_left": "Inclina o capuchón á esquerda (bordo esquerdo abaixo), mantéño e sóltao.",
"ui.space_mouse_step_tilt_right": "Inclina o capuchón á dereita (bordo dereito abaixo), mantéño e sóltao.",
"ui.space_mouse_step_twist_clockwise": "Xira o capuchón no sentido horario, mantéño e sóltao.",
"ui.space_mouse_step_twist_counterclockwise": "Xira o capuchón no sentido antihorario, mantéño e sóltao.",
"ui.spacing": "Espazado",
"ui.spacing_2": "Espazado 2",
"ui.sphere": "Esfera",
@@ -1398,6 +1425,7 @@
"ui.split_body": "Dividir o corpo",
"ui.stand_up_tip": "Despois de abrir un ficheiro STEP ou IGES con Z cara arriba, ofrecer un cuarto de volta arredor de X",
"ui.start": "Inicio",
"ui.start_over": "Volver comezar",
"ui.start_radius": "Raio inicial",
"ui.supersampling": "Supermostraxe (SSAA)",
"ui.supersampling_adaptive": "Só cando a vista está quieta",
+28
View File
@@ -1010,6 +1010,7 @@
"ui.autosave_every": "Salvataggio automatico ogni",
"ui.axes": "Assi",
"ui.axis": "Asse",
"ui.back": "Indietro",
"ui.base_point": "Punto base",
"ui.blocked": "Bloccato",
"ui.bodies": "Corpi",
@@ -1423,8 +1424,34 @@
"ui.smooth_wheel_zoom": "Zoom fluido con rotellina",
"ui.smooth_wheel_zoom_tip": "Disattiva per applicare immediatamente ogni evento della rotellina, senza coda di interpolazione",
"ui.snap": "Aggancio",
"ui.space_mouse_calibrate": "Calibra…",
"ui.space_mouse_calibrate_tip": "Muovi la manopola come chiede la finestra, così SolidCraft impara in che direzione e quanto va ogni asse di questo mouse 3D. Viene salvata per questo mouse 3D.",
"ui.space_mouse_calibrate_title": "Calibra mouse 3D",
"ui.space_mouse_calibrated": "Calibrato",
"ui.space_mouse_calibration": "Calibrazione del mouse 3D",
"ui.space_mouse_calibration_done": "Fatto. Salvala per usarla ogni volta che questo mouse 3D è collegato.",
"ui.space_mouse_calibration_no_response": "Un asse si è mosso appena, quindi non si può calibrare. Ricomincia e muovi la manopola più a fondo ogni volta.",
"ui.space_mouse_dead_zone": "Zona morta",
"ui.space_mouse_dead_zone_tip": "Quanto deve muoversi la manopola prima che si muova la vista, come quota della sua corsa completa. Aumentala se la vista si sposta con la manopola a riposo.",
"ui.space_mouse_forget": "Dimentica calibrazione",
"ui.space_mouse_hint": "Sposta e ruota la vista insieme; gli schizzi usano solo panoramica e zoom.",
"ui.space_mouse_navigate": "Naviga con SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "Nessun mouse 3D trovato",
"ui.space_mouse_not_calibrated": "Non calibrato",
"ui.space_mouse_reading": "Lettura",
"ui.space_mouse_step_lift": "Solleva la manopola, tienila, poi lasciala.",
"ui.space_mouse_step_press": "Premi la manopola verso il basso, tienila, poi lasciala.",
"ui.space_mouse_step_pull": "Tira la manopola verso di te, tienila, poi lasciala.",
"ui.space_mouse_step_push": "Spingi la manopola lontano da te, tienila, poi lasciala.",
"ui.space_mouse_step_rest": "Togli la mano dalla manopola e lasciala ferma.",
"ui.space_mouse_step_slide_left": "Fai scorrere la manopola a sinistra, tienila, poi lasciala.",
"ui.space_mouse_step_slide_right": "Fai scorrere la manopola a destra, tienila, poi lasciala.",
"ui.space_mouse_step_tilt_back": "Inclina la manopola all'indietro (bordo anteriore in alto), tienila, poi lasciala.",
"ui.space_mouse_step_tilt_forward": "Inclina la manopola in avanti (bordo anteriore in basso), tienila, poi lasciala.",
"ui.space_mouse_step_tilt_left": "Inclina la manopola a sinistra (bordo sinistro in basso), tienila, poi lasciala.",
"ui.space_mouse_step_tilt_right": "Inclina la manopola a destra (bordo destro in basso), tienila, poi lasciala.",
"ui.space_mouse_step_twist_clockwise": "Ruota la manopola in senso orario, tienila, poi lasciala.",
"ui.space_mouse_step_twist_counterclockwise": "Ruota la manopola in senso antiorario, tienila, poi lasciala.",
"ui.spacing": "Spaziatura",
"ui.spacing_2": "Spaziatura 2",
"ui.sphere": "Sfera",
@@ -1432,6 +1459,7 @@
"ui.split_body": "Dividi corpo",
"ui.stand_up_tip": "Dopo l'apertura di un file STEP o IGES con asse Z verticale, proponi un quarto di giro attorno a X",
"ui.start": "Inizio",
"ui.start_over": "Ricomincia",
"ui.start_radius": "Raggio iniziale",
"ui.stretch": "Stira",
"ui.supersampling": "Sovracampionamento (SSAA)",
+28
View File
@@ -1074,6 +1074,7 @@
"ui.autosave_every": "自動保存の間隔",
"ui.axes": "軸",
"ui.axis": "軸",
"ui.back": "戻る",
"ui.base_point": "基点",
"ui.blocked": "到達不可",
"ui.bodies": "ボディ",
@@ -1508,8 +1509,34 @@
"ui.smooth_wheel_zoom": "滑らかなホイールズーム",
"ui.smooth_wheel_zoom_tip": "オフにすると、ホイール操作のたびにズームが即座に反映され、滑らかな減速効果は適用されません。",
"ui.snap": "スナップ",
"ui.space_mouse_calibrate": "キャリブレーション…",
"ui.space_mouse_calibrate_tip": "ウィンドウの指示どおりにキャップを動かすと、この3Dマウスの各軸の向きと移動量をSolidCraftが学習します。この3Dマウス用に保存されます。",
"ui.space_mouse_calibrate_title": "3Dマウスのキャリブレーション",
"ui.space_mouse_calibrated": "キャリブレーション済み",
"ui.space_mouse_calibration": "3Dマウスのキャリブレーション",
"ui.space_mouse_calibration_done": "完了しました。保存すると、この3Dマウスを接続したときに毎回使われます。",
"ui.space_mouse_calibration_no_response": "ほとんど動かなかった軸があるため、キャリブレーションできません。最初からやり直し、毎回キャップをもっと大きく動かしてください。",
"ui.space_mouse_dead_zone": "デッドゾーン",
"ui.space_mouse_dead_zone_tip": "視点が動き出すまでにキャップを動かす量(全ストロークに対する割合)。キャップに触れていないのに視点が動く場合は大きくしてください。",
"ui.space_mouse_forget": "キャリブレーションを削除",
"ui.space_mouse_hint": "視点の移動と回転を同時に行います(スケッチ中はパンとズームのみ)",
"ui.space_mouse_navigate": "SpaceNavigator / SpaceMouseで視点を操作",
"ui.space_mouse_none": "3Dマウスが見つかりません",
"ui.space_mouse_not_calibrated": "未キャリブレーション",
"ui.space_mouse_reading": "読み取り値",
"ui.space_mouse_step_lift": "キャップを持ち上げて保持し、離してください。",
"ui.space_mouse_step_press": "キャップを押し下げて保持し、離してください。",
"ui.space_mouse_step_pull": "キャップを手前に引いて保持し、離してください。",
"ui.space_mouse_step_push": "キャップを奥に押して保持し、離してください。",
"ui.space_mouse_step_rest": "キャップから手を離し、動かさないでください。",
"ui.space_mouse_step_slide_left": "キャップを左にスライドして保持し、離してください。",
"ui.space_mouse_step_slide_right": "キャップを右にスライドして保持し、離してください。",
"ui.space_mouse_step_tilt_back": "キャップを後ろに傾け(手前の縁を上げて)保持し、離してください。",
"ui.space_mouse_step_tilt_forward": "キャップを前に傾け(手前の縁を下げて)保持し、離してください。",
"ui.space_mouse_step_tilt_left": "キャップを左に傾け(左の縁を下げて)保持し、離してください。",
"ui.space_mouse_step_tilt_right": "キャップを右に傾け(右の縁を下げて)保持し、離してください。",
"ui.space_mouse_step_twist_clockwise": "キャップを時計回りにひねって保持し、離してください。",
"ui.space_mouse_step_twist_counterclockwise": "キャップを反時計回りにひねって保持し、離してください。",
"ui.spacing": "間隔",
"ui.spacing_2": "間隔 2",
"ui.sphere": "球",
@@ -1517,6 +1544,7 @@
"ui.split_body": "ボディを分割",
"ui.stand_up_tip": "Z軸上向きで開いたSTEPまたはIGESファイルに対し、X軸周りに90度回転させるか確認します",
"ui.start": "開始",
"ui.start_over": "最初からやり直す",
"ui.start_radius": "開始半径",
"ui.stretch": "伸縮",
"ui.supersampling": "スーパーサンプリング (SSAA)",
+28
View File
@@ -782,6 +782,7 @@
"ui.autosave_every": "자동 저장 간격",
"ui.axes": "축",
"ui.axis": "축",
"ui.back": "뒤로",
"ui.base_point": "기준점",
"ui.blocked": "막힘",
"ui.bodies": "바디",
@@ -1174,12 +1175,39 @@
"ui.slot": "슬롯",
"ui.smooth": "부드럽게",
"ui.snap": "스냅",
"ui.space_mouse_calibrate": "보정…",
"ui.space_mouse_calibrate_tip": "창의 안내대로 캡을 움직이면 SolidCraft가 이 3D 마우스의 각 축이 어느 방향으로 얼마나 움직이는지 학습합니다. 이 3D 마우스에 저장됩니다.",
"ui.space_mouse_calibrate_title": "3D 마우스 보정",
"ui.space_mouse_calibrated": "보정됨",
"ui.space_mouse_calibration": "3D 마우스 보정",
"ui.space_mouse_calibration_done": "완료했습니다. 저장하면 이 3D 마우스를 연결할 때마다 사용됩니다.",
"ui.space_mouse_calibration_no_response": "거의 움직이지 않은 축이 있어 보정할 수 없습니다. 처음부터 다시 하고 매번 캡을 더 멀리 움직이세요.",
"ui.space_mouse_dead_zone": "데드존",
"ui.space_mouse_dead_zone_tip": "보기가 움직이기 전에 캡이 움직여야 하는 정도로, 전체 이동 범위에 대한 비율입니다. 캡을 건드리지 않았는데 보기가 움직이면 높이세요.",
"ui.space_mouse_forget": "보정 삭제",
"ui.space_mouse_none": "3D 마우스를 찾을 수 없음",
"ui.space_mouse_not_calibrated": "보정 안 됨",
"ui.space_mouse_reading": "읽은 값",
"ui.space_mouse_step_lift": "캡을 위로 들어 유지한 다음 놓으세요.",
"ui.space_mouse_step_press": "캡을 아래로 눌러 유지한 다음 놓으세요.",
"ui.space_mouse_step_pull": "캡을 몸 쪽으로 당겨 유지한 다음 놓으세요.",
"ui.space_mouse_step_push": "캡을 앞쪽으로 밀어 유지한 다음 놓으세요.",
"ui.space_mouse_step_rest": "캡에서 손을 떼고 가만히 두세요.",
"ui.space_mouse_step_slide_left": "캡을 왼쪽으로 밀어 유지한 다음 놓으세요.",
"ui.space_mouse_step_slide_right": "캡을 오른쪽으로 밀어 유지한 다음 놓으세요.",
"ui.space_mouse_step_tilt_back": "캡을 뒤로 기울여(앞쪽 가장자리를 위로) 유지한 다음 놓으세요.",
"ui.space_mouse_step_tilt_forward": "캡을 앞으로 기울여(앞쪽 가장자리를 아래로) 유지한 다음 놓으세요.",
"ui.space_mouse_step_tilt_left": "캡을 왼쪽으로 기울여(왼쪽 가장자리를 아래로) 유지한 다음 놓으세요.",
"ui.space_mouse_step_tilt_right": "캡을 오른쪽으로 기울여(오른쪽 가장자리를 아래로) 유지한 다음 놓으세요.",
"ui.space_mouse_step_twist_clockwise": "캡을 시계 방향으로 돌려 유지한 다음 놓으세요.",
"ui.space_mouse_step_twist_counterclockwise": "캡을 시계 반대 방향으로 돌려 유지한 다음 놓으세요.",
"ui.spacing": "간격",
"ui.spacing_2": "간격 2",
"ui.sphere": "구",
"ui.spline": "스플라인",
"ui.split_body": "바디 분할",
"ui.start": "시작",
"ui.start_over": "처음부터 다시",
"ui.start_radius": "시작 반지름",
"ui.supersampling": "슈퍼샘플링 (SSAA)",
"ui.supersampling_adaptive": "뷰가 멈춰 있을 때만",
+28
View File
@@ -964,6 +964,7 @@
"ui.autosave_every": "Salvar automaticamente a cada",
"ui.axes": "Eixos",
"ui.axis": "Eixo",
"ui.back": "Voltar",
"ui.base_point": "Ponto base",
"ui.blocked": "Bloqueado",
"ui.bodies": "Corpos",
@@ -1369,8 +1370,34 @@
"ui.smooth_wheel_zoom": "Zoom suave com a roda",
"ui.smooth_wheel_zoom_tip": "Desative para aplicar cada evento da roda na hora, sem rastro de suavização",
"ui.snap": "Encaixe",
"ui.space_mouse_calibrate": "Calibrar…",
"ui.space_mouse_calibrate_tip": "Mova a tampa como a janela pedir, para que o SolidCraft aprenda para onde e até onde vai cada eixo deste mouse 3D. Salvo para este mouse 3D.",
"ui.space_mouse_calibrate_title": "Calibrar mouse 3D",
"ui.space_mouse_calibrated": "Calibrado",
"ui.space_mouse_calibration": "Calibração do mouse 3D",
"ui.space_mouse_calibration_done": "Pronto. Salve para usá-la sempre que este mouse 3D estiver conectado.",
"ui.space_mouse_calibration_no_response": "Um eixo quase não se moveu, então não dá para calibrá-lo. Recomece e mova a tampa mais longe a cada vez.",
"ui.space_mouse_dead_zone": "Zona morta",
"ui.space_mouse_dead_zone_tip": "Quanto a tampa precisa se mover antes de a vista se mover, como fração do curso completo. Aumente se a vista se mexer com a tampa parada.",
"ui.space_mouse_forget": "Esquecer calibração",
"ui.space_mouse_hint": "Move e gira a vista juntos; esboços usam apenas deslocamento e zoom.",
"ui.space_mouse_navigate": "Navegar com SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "Nenhum mouse 3D encontrado",
"ui.space_mouse_not_calibrated": "Não calibrado",
"ui.space_mouse_reading": "Leitura",
"ui.space_mouse_step_lift": "Levante a tampa, segure e solte.",
"ui.space_mouse_step_press": "Pressione a tampa para baixo, segure e solte.",
"ui.space_mouse_step_pull": "Puxe a tampa na sua direção, segure e solte.",
"ui.space_mouse_step_push": "Empurre a tampa para longe de você, segure e solte.",
"ui.space_mouse_step_rest": "Tire a mão da tampa e deixe-a parada.",
"ui.space_mouse_step_slide_left": "Deslize a tampa para a esquerda, segure e solte.",
"ui.space_mouse_step_slide_right": "Deslize a tampa para a direita, segure e solte.",
"ui.space_mouse_step_tilt_back": "Incline a tampa para trás (borda da frente para cima), segure e solte.",
"ui.space_mouse_step_tilt_forward": "Incline a tampa para a frente (borda da frente para baixo), segure e solte.",
"ui.space_mouse_step_tilt_left": "Incline a tampa para a esquerda (borda esquerda para baixo), segure e solte.",
"ui.space_mouse_step_tilt_right": "Incline a tampa para a direita (borda direita para baixo), segure e solte.",
"ui.space_mouse_step_twist_clockwise": "Gire a tampa no sentido horário, segure e solte.",
"ui.space_mouse_step_twist_counterclockwise": "Gire a tampa no sentido anti-horário, segure e solte.",
"ui.spacing": "Espaçamento",
"ui.spacing_2": "Espaçamento 2",
"ui.sphere": "Esfera",
@@ -1378,6 +1405,7 @@
"ui.split_body": "Dividir corpo",
"ui.stand_up_tip": "Depois que um arquivo STEP ou IGES abrir com Z para cima, oferecer um quarto de volta em torno de X",
"ui.start": "Início",
"ui.start_over": "Recomeçar",
"ui.start_radius": "Raio inicial",
"ui.supersampling": "Supersampling (SSAA)",
"ui.supersampling_adaptive": "Só quando a vista está parada",
+28
View File
@@ -776,6 +776,7 @@
"ui.autosave_every": "Автосохранение каждые",
"ui.axes": "Оси",
"ui.axis": "Ось",
"ui.back": "Назад",
"ui.base_point": "Базовая точка",
"ui.bodies": "Тела",
"ui.box": "Бокс",
@@ -1177,8 +1178,34 @@
"ui.smooth_wheel_zoom": "Плавное масштабирование колесом",
"ui.smooth_wheel_zoom_tip": "Отключите, чтобы каждое движение колеса применялось сразу, без сглаживания",
"ui.snap": "Привязка",
"ui.space_mouse_calibrate": "Калибровать…",
"ui.space_mouse_calibrate_tip": "Двигайте колпачок так, как просит окно, чтобы SolidCraft узнал, куда и насколько далеко движется каждая ось этой 3D-мыши. Сохраняется для этой 3D-мыши.",
"ui.space_mouse_calibrate_title": "Калибровка 3D-мыши",
"ui.space_mouse_calibrated": "Откалибрована",
"ui.space_mouse_calibration": "Калибровка 3D-мыши",
"ui.space_mouse_calibration_done": "Готово. Сохраните её, чтобы она применялась всякий раз, когда подключена эта 3D-мышь.",
"ui.space_mouse_calibration_no_response": "Одна ось почти не сдвинулась, поэтому её нельзя откалибровать. Начните заново и каждый раз двигайте колпачок дальше.",
"ui.space_mouse_dead_zone": "Мёртвая зона",
"ui.space_mouse_dead_zone_tip": "Насколько нужно сдвинуть колпачок, прежде чем сдвинется вид, в доле от полного хода. Увеличьте, если вид смещается, когда колпачок в покое.",
"ui.space_mouse_forget": "Забыть калибровку",
"ui.space_mouse_hint": "Совместное перемещение и вращение вида; в эскизе — только панорама и масштаб.",
"ui.space_mouse_navigate": "Навигация через SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "3D-мышь не найдена",
"ui.space_mouse_not_calibrated": "Не откалибрована",
"ui.space_mouse_reading": "Показания",
"ui.space_mouse_step_lift": "Поднимите колпачок вверх, удержите и отпустите.",
"ui.space_mouse_step_press": "Нажмите на колпачок вниз, удержите и отпустите.",
"ui.space_mouse_step_pull": "Потяните колпачок на себя, удержите и отпустите.",
"ui.space_mouse_step_push": "Толкните колпачок от себя, удержите и отпустите.",
"ui.space_mouse_step_rest": "Уберите руку с колпачка и не трогайте его.",
"ui.space_mouse_step_slide_left": "Сдвиньте колпачок влево, удержите и отпустите.",
"ui.space_mouse_step_slide_right": "Сдвиньте колпачок вправо, удержите и отпустите.",
"ui.space_mouse_step_tilt_back": "Наклоните колпачок назад (передний край вверх), удержите и отпустите.",
"ui.space_mouse_step_tilt_forward": "Наклоните колпачок вперёд (передний край вниз), удержите и отпустите.",
"ui.space_mouse_step_tilt_left": "Наклоните колпачок влево (левый край вниз), удержите и отпустите.",
"ui.space_mouse_step_tilt_right": "Наклоните колпачок вправо (правый край вниз), удержите и отпустите.",
"ui.space_mouse_step_twist_clockwise": "Поверните колпачок по часовой стрелке, удержите и отпустите.",
"ui.space_mouse_step_twist_counterclockwise": "Поверните колпачок против часовой стрелки, удержите и отпустите.",
"ui.spacing": "Интервал",
"ui.spacing_2": "Интервал 2",
"ui.sphere": "Сфера",
@@ -1186,6 +1213,7 @@
"ui.split_body": "Разделить тело",
"ui.stand_up_tip": "Если файл STEP или IGES открывается с Z вверх, предложить поворот на четверть оборота вокруг X",
"ui.start": "Старт",
"ui.start_over": "Начать заново",
"ui.start_radius": "Начальный радиус",
"ui.suppress": "Подавить",
"ui.sweep": "Сдвиг",
+28
View File
@@ -913,6 +913,7 @@
"ui.autosave_every": "Otomatik kaydetme aralığı",
"ui.axes": "Eksenler",
"ui.axis": "Eksen",
"ui.back": "Geri",
"ui.base_point": "Temel nokta",
"ui.blocked": "Engellenmiş",
"ui.bodies": "Gövdeler",
@@ -1316,8 +1317,34 @@
"ui.smooth_wheel_zoom": "Yumuşak tekerlek yakınlaştırması",
"ui.smooth_wheel_zoom_tip": "Her tekerlek hareketini yumuşatma olmadan hemen uygulamak için kapatın",
"ui.snap": "Yakala",
"ui.space_mouse_calibrate": "Kalibre et…",
"ui.space_mouse_calibrate_tip": "Pencerenin istediği gibi başlığı hareket ettirin; SolidCraft bu 3B farenin her ekseninin hangi yöne ve ne kadar gittiğini öğrensin. Bu 3B fare için kaydedilir.",
"ui.space_mouse_calibrate_title": "3B fareyi kalibre et",
"ui.space_mouse_calibrated": "Kalibre edildi",
"ui.space_mouse_calibration": "3B fare kalibrasyonu",
"ui.space_mouse_calibration_done": "Bitti. Bu 3B fare her bağlandığında kullanılması için kaydedin.",
"ui.space_mouse_calibration_no_response": "Bir eksen neredeyse hiç hareket etmedi, bu yüzden kalibre edilemiyor. Baştan başlayın ve başlığı her seferinde daha fazla hareket ettirin.",
"ui.space_mouse_dead_zone": "Ölü bölge",
"ui.space_mouse_dead_zone_tip": "Görünüm hareket etmeden önce başlığın ne kadar hareket etmesi gerektiği, tam hareket aralığının oranı olarak. Başlık dururken görünüm kayıyorsa artırın.",
"ui.space_mouse_forget": "Kalibrasyonu unut",
"ui.space_mouse_hint": "Görünümü aynı anda kaydırın ve döndürün; eskizlerde yalnızca kaydırma ve yakınlaştırma kullanılır.",
"ui.space_mouse_navigate": "SpaceNavigator / SpaceMouse ile gezin",
"ui.space_mouse_none": "3B fare bulunamadı",
"ui.space_mouse_not_calibrated": "Kalibre edilmedi",
"ui.space_mouse_reading": "Okunan değer",
"ui.space_mouse_step_lift": "Başlığı yukarı kaldırın, tutun, sonra bırakın.",
"ui.space_mouse_step_press": "Başlığı aşağı bastırın, tutun, sonra bırakın.",
"ui.space_mouse_step_pull": "Başlığı kendinize doğru çekin, tutun, sonra bırakın.",
"ui.space_mouse_step_push": "Başlığı sizden uzağa itin, tutun, sonra bırakın.",
"ui.space_mouse_step_rest": "Elinizi başlıktan çekin ve hareketsiz bırakın.",
"ui.space_mouse_step_slide_left": "Başlığı sola kaydırın, tutun, sonra bırakın.",
"ui.space_mouse_step_slide_right": "Başlığı sağa kaydırın, tutun, sonra bırakın.",
"ui.space_mouse_step_tilt_back": "Başlığı geriye eğin (ön kenar yukarı), tutun, sonra bırakın.",
"ui.space_mouse_step_tilt_forward": "Başlığı öne eğin (ön kenar aşağı), tutun, sonra bırakın.",
"ui.space_mouse_step_tilt_left": "Başlığı sola eğin (sol kenar aşağı), tutun, sonra bırakın.",
"ui.space_mouse_step_tilt_right": "Başlığı sağa eğin (sağ kenar aşağı), tutun, sonra bırakın.",
"ui.space_mouse_step_twist_clockwise": "Başlığı saat yönünde çevirin, tutun, sonra bırakın.",
"ui.space_mouse_step_twist_counterclockwise": "Başlığı saat yönünün tersine çevirin, tutun, sonra bırakın.",
"ui.spacing": "Aralık",
"ui.spacing_2": "Aralık 2",
"ui.sphere": "Küre",
@@ -1325,6 +1352,7 @@
"ui.split_body": "Gövdeyi böl",
"ui.stand_up_tip": "Bir STEP veya IGES dosyası Z yukarı olarak açıldığında X etrafında çeyrek tur döndürmeyi öner",
"ui.start": "Başlangıç",
"ui.start_over": "Baştan başla",
"ui.start_radius": "Başlangıç yarıçapı",
"ui.supersampling": "Süper örnekleme (SSAA)",
"ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken",
+28
View File
@@ -987,6 +987,7 @@
"ui.autosave_every": "Автозбереження кожні",
"ui.axes": "Осі",
"ui.axis": "Вісь",
"ui.back": "Назад",
"ui.base_point": "Базова точка",
"ui.blocked": "Заблоковані",
"ui.bodies": "Тіла",
@@ -1392,8 +1393,34 @@
"ui.smooth_wheel_zoom": "Плавне масштабування колесом",
"ui.smooth_wheel_zoom_tip": "Вимкніть, щоб застосовувати кожну подію колеса негайно, без плавного завершення",
"ui.snap": "Прив'язка",
"ui.space_mouse_calibrate": "Калібрувати…",
"ui.space_mouse_calibrate_tip": "Рухайте ковпачок так, як просить вікно, щоб SolidCraft дізнався, куди й наскільки далеко рухається кожна вісь цієї 3D-миші. Зберігається для цієї 3D-миші.",
"ui.space_mouse_calibrate_title": "Калібрування 3D-миші",
"ui.space_mouse_calibrated": "Відкалібровано",
"ui.space_mouse_calibration": "Калібрування 3D-миші",
"ui.space_mouse_calibration_done": "Готово. Збережіть його, щоб воно застосовувалося щоразу, коли підключено цю 3D-мишу.",
"ui.space_mouse_calibration_no_response": "Одна вісь майже не зрушила, тому її не можна відкалібрувати. Почніть спочатку й щоразу рухайте ковпачок далі.",
"ui.space_mouse_dead_zone": "Мертва зона",
"ui.space_mouse_dead_zone_tip": "Наскільки треба зсунути ковпачок, перш ніж зрушить вигляд, у частці від повного ходу. Збільште, якщо вигляд зміщується, коли ковпачок у спокої.",
"ui.space_mouse_forget": "Забути калібрування",
"ui.space_mouse_hint": "Переміщуйте й обертайте вид разом; в ескізах доступні лише панорамування та масштаб.",
"ui.space_mouse_navigate": "Навігація за допомогою SpaceNavigator / SpaceMouse",
"ui.space_mouse_none": "3D-мишу не знайдено",
"ui.space_mouse_not_calibrated": "Не відкалібровано",
"ui.space_mouse_reading": "Показники",
"ui.space_mouse_step_lift": "Підніміть ковпачок угору, утримайте й відпустіть.",
"ui.space_mouse_step_press": "Натисніть ковпачок униз, утримайте й відпустіть.",
"ui.space_mouse_step_pull": "Потягніть ковпачок до себе, утримайте й відпустіть.",
"ui.space_mouse_step_push": "Штовхніть ковпачок від себе, утримайте й відпустіть.",
"ui.space_mouse_step_rest": "Приберіть руку з ковпачка й не торкайтеся його.",
"ui.space_mouse_step_slide_left": "Зсуньте ковпачок ліворуч, утримайте й відпустіть.",
"ui.space_mouse_step_slide_right": "Зсуньте ковпачок праворуч, утримайте й відпустіть.",
"ui.space_mouse_step_tilt_back": "Нахиліть ковпачок назад (передній край угору), утримайте й відпустіть.",
"ui.space_mouse_step_tilt_forward": "Нахиліть ковпачок уперед (передній край униз), утримайте й відпустіть.",
"ui.space_mouse_step_tilt_left": "Нахиліть ковпачок ліворуч (лівий край униз), утримайте й відпустіть.",
"ui.space_mouse_step_tilt_right": "Нахиліть ковпачок праворуч (правий край униз), утримайте й відпустіть.",
"ui.space_mouse_step_twist_clockwise": "Поверніть ковпачок за годинниковою стрілкою, утримайте й відпустіть.",
"ui.space_mouse_step_twist_counterclockwise": "Поверніть ковпачок проти годинникової стрілки, утримайте й відпустіть.",
"ui.spacing": "Крок",
"ui.spacing_2": "Крок 2",
"ui.sphere": "Куля",
@@ -1401,6 +1428,7 @@
"ui.split_body": "Розділити тіло",
"ui.stand_up_tip": "Після відкриття файлу STEP або IGES з напрямком Z вгору пропонувати поворот на чверть оберту навколо X",
"ui.start": "Початок",
"ui.start_over": "Почати спочатку",
"ui.start_radius": "Початковий радіус",
"ui.supersampling": "Наддискретизація (SSAA)",
"ui.supersampling_adaptive": "Лише коли вид нерухомий",
+28
View File
@@ -1074,6 +1074,7 @@
"ui.autosave_every": "自动保存间隔",
"ui.axes": "轴",
"ui.axis": "轴",
"ui.back": "返回",
"ui.base_point": "基点",
"ui.blocked": "被遮挡",
"ui.bodies": "实体",
@@ -1508,8 +1509,34 @@
"ui.smooth_wheel_zoom": "平滑滚轮缩放",
"ui.smooth_wheel_zoom_tip": "关闭后每个滚轮事件立即生效,不做平滑延迟",
"ui.snap": "捕捉",
"ui.space_mouse_calibrate": "校准…",
"ui.space_mouse_calibrate_tip": "按窗口提示移动摇杆帽,SolidCraft 会记住这个 3D 鼠标每个轴的方向和行程。校准结果按此 3D 鼠标保存。",
"ui.space_mouse_calibrate_title": "校准 3D 鼠标",
"ui.space_mouse_calibrated": "已校准",
"ui.space_mouse_calibration": "3D 鼠标校准",
"ui.space_mouse_calibration_done": "完成。保存后,每次连接此 3D 鼠标都会使用它。",
"ui.space_mouse_calibration_no_response": "有一个轴几乎没有移动,因此无法校准。请重新开始,并且每次把摇杆帽移得更远。",
"ui.space_mouse_dead_zone": "死区",
"ui.space_mouse_dead_zone_tip": "视图开始移动前摇杆帽需要移动的距离,以其全行程的比例表示。如果摇杆帽静止时视图仍在漂移,请调大。",
"ui.space_mouse_forget": "清除校准",
"ui.space_mouse_hint": "同时移动和旋转视图;草图中仅支持平移和缩放。",
"ui.space_mouse_navigate": "使用 SpaceNavigator / SpaceMouse 导航",
"ui.space_mouse_none": "未找到 3D 鼠标",
"ui.space_mouse_not_calibrated": "未校准",
"ui.space_mouse_reading": "读数",
"ui.space_mouse_step_lift": "向上提起摇杆帽,保持住,然后松开。",
"ui.space_mouse_step_press": "向下按压摇杆帽,保持住,然后松开。",
"ui.space_mouse_step_pull": "把摇杆帽拉向自己,保持住,然后松开。",
"ui.space_mouse_step_push": "把摇杆帽推离自己,保持住,然后松开。",
"ui.space_mouse_step_rest": "请把手从摇杆帽上移开,让它保持静止。",
"ui.space_mouse_step_slide_left": "向左推动摇杆帽,保持住,然后松开。",
"ui.space_mouse_step_slide_right": "向右推动摇杆帽,保持住,然后松开。",
"ui.space_mouse_step_tilt_back": "向后倾斜摇杆帽(前缘向上),保持住,然后松开。",
"ui.space_mouse_step_tilt_forward": "向前倾斜摇杆帽(前缘向下),保持住,然后松开。",
"ui.space_mouse_step_tilt_left": "向左倾斜摇杆帽(左缘向下),保持住,然后松开。",
"ui.space_mouse_step_tilt_right": "向右倾斜摇杆帽(右缘向下),保持住,然后松开。",
"ui.space_mouse_step_twist_clockwise": "顺时针扭转摇杆帽,保持住,然后松开。",
"ui.space_mouse_step_twist_counterclockwise": "逆时针扭转摇杆帽,保持住,然后松开。",
"ui.spacing": "间距",
"ui.spacing_2": "间距 2",
"ui.sphere": "球体",
@@ -1517,6 +1544,7 @@
"ui.split_body": "分割实体",
"ui.stand_up_tip": "当 Z 朝上的 STEP 或 IGES 文件打开后,提示绕 X 轴旋转四分之一周",
"ui.start": "开始",
"ui.start_over": "重新开始",
"ui.start_radius": "起始半径",
"ui.stretch": "伸展",
"ui.supersampling": "超级采样 (SSAA)",
+4
View File
@@ -7,3 +7,7 @@ license.workspace = true
[lints]
workspace = true
[dependencies]
# Saving a calibration with the app's preferences; off by default, so the crate needs nothing.
serde = { workspace = true, optional = true }
File diff suppressed because it is too large Load Diff
+4
View File
@@ -10,6 +10,10 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod calibration;
mod descriptor;
pub use calibration::{
AxisCalibration, Calibration, HOLD_SECONDS, MAX_DEAD_ZONE_SHARE, MIN_SHARE, Problem, REST_SECONDS, Recording, STEPS, Stage, Step, Wizard,
};
pub use descriptor::{Descriptor, FULL_SCALE, Field, Layout, MAX_BUTTONS, Report};
+1
View File
@@ -13,6 +13,7 @@ solidcraft-engine = { workspace = true }
egui = { workspace = true }
egui-wgpu = { workspace = true }
solidcraft-gpu = { workspace = true }
solidcraft-space-mouse = { workspace = true, features = ["serde"] }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+4
View File
@@ -178,6 +178,7 @@ pub mod smart_extrude;
#[cfg(test)]
mod smart_extrude_ui_tests;
pub mod space_mouse;
pub mod space_mouse_calibration;
pub mod stand_up;
#[cfg(test)]
mod sweep_dialog_tests;
@@ -415,6 +416,8 @@ pub struct SolveApp {
pub flat_view: dialogs_sheet::FlatView,
/// The start page.
pub home: home::HomeState,
/// The 3D mouse: which device, its reading, and the calibration window.
pub space_mouse: space_mouse::Input,
pub file_load: file_load::FileLoad,
/// The other open designs (tabs).
pub docs: documents::Documents,
@@ -507,6 +510,7 @@ impl SolveApp {
pending_fit: None,
flat_view: Default::default(),
home: home::HomeState::default(),
space_mouse: Default::default(),
file_load: file_load::FileLoad::default(),
docs: documents::Documents::default(),
applied_fonts_language: "en".into(),
+76 -3
View File
@@ -284,6 +284,10 @@ pub struct Prefs {
pub space_mouse_reverse: [bool; 6],
/// Per physical axis of the cap, a multiplier on top of `space_mouse_speed`; 0 switches it off.
pub space_mouse_axis_speed: [f32; 6],
/// Per 3D mouse (`space_mouse::Input::device`), the calibration that puts its axes on
/// 3Dconnexion's. A device without one is read as it reports.
#[serde(deserialize_with = "calibrations_that_read")]
pub space_mouse_calibrations: std::collections::BTreeMap<String, solidcraft_space_mouse::Calibration>,
/// Anti-aliasing samples (applies on restart).
pub msaa: u32,
/// Soft contact shading in the GPU viewport; optional and applied immediately.
@@ -446,6 +450,7 @@ impl Default for Prefs {
space_mouse_speed: 1.0,
space_mouse_reverse: [false; 6],
space_mouse_axis_speed: [1.0; 6],
space_mouse_calibrations: Default::default(),
msaa: 4,
ambient_occlusion: false,
grid_follows_view: false,
@@ -763,6 +768,7 @@ fn defaults(app: &mut SolveApp, page: usize) {
p.space_mouse_speed = d.space_mouse_speed;
p.space_mouse_reverse = d.space_mouse_reverse;
p.space_mouse_axis_speed = d.space_mouse_axis_speed;
// The 3D mice the user calibrated stay: a calibration describes the device.
p.look_at_anim = d.look_at_anim;
p.look_at_speed = d.look_at_speed;
p.middle_double_click = d.middle_double_click;
@@ -1079,6 +1085,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
if !app.prefs_window.open {
app.prefs_window.snapshot = None;
// Calibration opens from here and ends with it, so the cap moves the view again.
app.space_mouse.calibrating = None;
return;
}
if app.prefs_window.snapshot.is_none() {
@@ -1147,6 +1155,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if let Some(w) = &shown {
crate::scenario::publish_rect("prefs:window", w.response.rect);
}
crate::space_mouse_calibration::show(app, ctx);
if app.preferences.msaa != before.msaa {
save_graphics(app);
}
@@ -1395,6 +1404,42 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
});
ui.end_row();
}
ui.label(app.tr("ui.space_mouse_calibration"));
ui.horizontal(|ui| {
let device = app.space_mouse.device.clone();
let saved = device.as_ref().is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device));
ui.add_enabled_ui(app.preferences.space_mouse_enabled && device.is_some(), |ui| {
if ui.button(app.tr("ui.space_mouse_calibrate")).on_hover_text(app.tr("ui.space_mouse_calibrate_tip")).clicked() {
crate::space_mouse_calibration::start(app);
}
if saved && ui.button(app.tr("ui.space_mouse_forget")).clicked()
&& let Some(device) = &device
{
app.preferences.space_mouse_calibrations.remove(device);
}
});
// With the device it's about, so it's clear which calibration is in use.
ui.label(match (&device, saved) {
(None, _) => app.tr("ui.space_mouse_none").to_owned(),
(Some(device), true) => format!("{} ({device})", app.tr("ui.space_mouse_calibrated")),
(Some(device), false) => format!("{} ({device})", app.tr("ui.space_mouse_not_calibrated")),
});
});
ui.end_row();
// The calibrated device's dead zone, adjustable after calibrating.
let enabled = app.preferences.space_mouse_enabled;
let (label, tip) = (app.tr("ui.space_mouse_dead_zone").to_owned(), app.tr("ui.space_mouse_dead_zone_tip").to_owned());
let (device, raw) = (app.space_mouse.device.clone(), app.space_mouse.raw.into());
if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) {
ui.label(label);
ui.add_enabled_ui(enabled, |ui| {
crate::space_mouse_calibration::dead_zone_slider(ui, &mut calibration.dead_zone_share).on_hover_text(tip);
});
ui.end_row();
ui.label("");
crate::space_mouse_calibration::dead_zone_pads(ui, calibration, raw);
ui.end_row();
}
note(ui, crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only."));
}
PAGE_DESIGN => {
@@ -1704,6 +1749,24 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::
Ok(out)
}
/// The saved 3D mouse calibrations that still read. One this version can't read (a hand edit, a
/// format from another release) is dropped on its own, with a log line, not with all the others.
fn calibrations_that_read<'de, D: serde::Deserializer<'de>>(
saved: D,
) -> Result<std::collections::BTreeMap<String, solidcraft_space_mouse::Calibration>, D::Error> {
let saved = std::collections::BTreeMap::<String, serde_json::Value>::deserialize(saved)?;
Ok(saved
.into_iter()
.filter_map(|(device, calibration)| match serde_json::from_value(calibration) {
Ok(calibration) => Some((device, calibration)),
Err(error) => {
log::warn!("preferences: the 3D mouse calibration for `{device}` can't be read ({error}); reading the device as it reports");
None
}
})
.collect())
}
/// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then
/// the imported ones.
fn theme_choices(app: &SolveApp) -> Vec<(String, String)> {
@@ -1756,16 +1819,26 @@ fn current_theme_file(app: &SolveApp) -> serde_json::Value {
}
}
/// Fold a setting an older release kept in its own field into the one this version reads.
/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`.
/// The cap's physical axes, in the order of `Prefs::space_mouse_reverse`.
const SPACE_MOUSE_AXES: [&str; 6] = ["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"];
pub(crate) const SPACE_MOUSE_AXES: [&str; 6] =
["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"];
/// Fold a setting an older release kept in its own field into the one this version reads.
/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. A 3D mouse
/// calibration that can't be used as it is (a hand edit) is dropped, so the device is read as it
/// reports rather than spinning the view.
pub fn migrate(mut p: Prefs) -> Prefs {
if p.orbit_cursor {
p.orbit_around = OrbitAround::Cursor;
p.orbit_cursor = false;
}
p.space_mouse_calibrations.retain(|device, calibration| {
let usable = calibration.is_usable();
if !usable {
log::warn!("preferences: the 3D mouse calibration for `{device}` can't be used as it is; reading the device as it reports");
}
usable
});
p
}
+164 -3
View File
@@ -8,6 +8,8 @@ use std::time::Duration;
use crate::SolveApp;
pub use solidcraft_space_mouse::{AxisCalibration, Calibration};
/// What a 3Dconnexion device reports at full deflection, in raw units, on every axis.
pub const FULL_SCALE: i16 = 350;
@@ -26,6 +28,31 @@ impl Axes {
}
}
impl From<Axes> for [i16; 6] {
fn from(axes: Axes) -> Self {
let ([x, y, z], [rx, ry, rz]) = (axes.translation, axes.rotation);
[x, y, z, rx, ry, rz]
}
}
impl From<[i16; 6]> for Axes {
fn from([x, y, z, rx, ry, rz]: [i16; 6]) -> Self {
Self { translation: [x, y, z], rotation: [rx, ry, rz] }
}
}
/// The 3D mouse as of this frame.
#[derive(Debug, Default)]
pub struct Input {
/// The device being read: where from and its vendor and product ids (`hid 256f:c63a`,
/// `web 256f:c63a`), or where from alone (`spacenavd`). Its calibration is saved under it.
pub device: Option<String>,
/// This frame's reading, before calibration.
pub raw: Axes,
/// The guided calibration while its window is open, and the device it is for.
pub calibrating: Option<(String, solidcraft_space_mouse::Wizard)>,
}
/// Seconds after the cap last moved that wheel events are still taken for 3DxWare's: one can be
/// queued just before the cap stops and only reach the next frame.
pub const WHEEL_QUIET_S: f64 = 0.15;
@@ -134,13 +161,39 @@ pub struct DeviceMotion {
pub seconds: f64,
}
/// The saved calibration of the device being read, when it has one.
pub fn calibration(app: &SolveApp) -> Option<Calibration> {
app.space_mouse.device.as_ref().and_then(|device| app.preferences.space_mouse_calibrations.get(device)).copied()
}
/// A reading on 3Dconnexion's axes: through `calibration` when there is one. Whether the cap is
/// moving is asked of this, never of the raw reading, so a device resting off zero isn't "moving"
/// and a short-range one moves as soon as it does.
pub fn calibrated(axes: Axes, calibration: Option<Calibration>) -> Axes {
calibration.map_or(axes, |calibration| calibration.apply(axes.into()).into())
}
/// Hands one frame of 3D mouse input, `seconds` after the previous frame, to the page showing
/// the camera. Nothing happens with navigation switched off, on the start page or while a file
/// picker is open. Returns whether there was motion to hand over; it then asks for the next frame
/// itself.
/// picker is open, or while the reading is inside the dead zone (after calibration, which takes
/// off the device's own rest offset), so a cap resting just off zero doesn't keep redrawing.
/// Returns whether there was motion to hand over; it then asks for the next frame itself. The
/// reading goes through the device's saved calibration first, when it has one; while the
/// calibration window is open, the reading goes to it instead and the view stays put.
pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool {
app.space_mouse.raw = axes;
if let Some((device, wizard)) = &mut app.space_mouse.calibrating {
if app.space_mouse.device.as_ref() == Some(device) {
wizard.feed(axes.into(), seconds);
ctx.request_repaint_after(Duration::from_millis(16));
return false;
}
// Another device is being read now, or none: what was recorded isn't its.
app.space_mouse.calibrating = None;
}
let axes = calibrated(axes, calibration(app));
// Only the window with focus: with two windows open, the cap moves the one being used, not both.
if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() || !ctx.input(|i| i.focused) {
if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || !axes.moving() || !ctx.input(|i| i.focused) {
return false;
}
let speed = f64::from(app.preferences.space_mouse_speed);
@@ -467,4 +520,112 @@ mod tests {
guard.filter(false, f64::NAN, &mut events);
assert_eq!(events.len(), 1);
}
/// A homemade device that sends push forward/back as its fifth axis, the other way round, at
/// ten times 3Dconnexion's range.
fn homemade() -> solidcraft_space_mouse::Calibration {
let axis = |source, reversed| solidcraft_space_mouse::AxisCalibration { source, reversed, rest: 0, dead_zone: 0, full: [3500; 2] };
solidcraft_space_mouse::Calibration {
dead_zone_share: 0.0,
axes: [axis(0, false), axis(4, true), axis(2, false), axis(3, false), axis(1, false), axis(5, false)],
}
}
#[test]
fn a_devices_saved_calibration_puts_its_axes_on_3dconnexions() {
let ctx = window(true);
let mut reference = app();
frame(&mut reference, &ctx, DriverMapping::default(), PUSH, 0.02);
let sent = Axes { translation: [0; 3], rotation: [0, -3500, 0] };
let mut calibrated = app();
calibrated.space_mouse.device = Some("hid 1234:5678".into());
calibrated.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade());
assert!(frame(&mut calibrated, &ctx, DriverMapping::default(), sent, 0.02));
assert_eq!(calibrated.cam, reference.cam);
// Another device's calibration isn't applied: the reading turns the view as it comes.
let mut other = app();
other.space_mouse.device = Some("hid 256f:c63a".into());
other.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade());
frame(&mut other, &ctx, DriverMapping::default(), sent, 0.02);
assert_ne!(other.cam, reference.cam);
}
#[test]
fn while_calibrating_the_cap_feeds_the_calibration_and_the_view_stays() {
let ctx = window(true);
let mut app = app();
crate::space_mouse_calibration::start(&mut app);
assert!(app.space_mouse.calibrating.is_none(), "nothing to calibrate without a device");
app.space_mouse.device = Some("hid 256f:c63a".into());
crate::space_mouse_calibration::start(&mut app);
let before = app.cam;
assert!(!frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02));
assert_eq!(app.cam, before);
assert_eq!(app.space_mouse.raw, PUSH);
assert!(app.space_mouse.calibrating.as_ref().is_some_and(|(_, wizard)| wizard.progress() > 0.0));
// Closing Preferences ends it, so the cap moves the view again.
app.prefs_window.open = false;
crate::prefs::show(&mut app, &ctx);
assert!(app.space_mouse.calibrating.is_none());
assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02));
}
#[test]
fn a_reading_resting_off_zero_is_kept_for_calibration_and_doesnt_move_the_view() {
let ctx = window(true);
// Inside the dead zone and not calibrated: no motion, so no redraw either.
let mut app = app();
let resting = Axes { translation: [0, 15, 0], rotation: [0; 3] };
let before = app.cam;
assert!(!frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02));
assert_eq!(app.cam, before);
// The calibration window gets it as it is, to measure where the cap rests.
app.space_mouse.device = Some("web 1234:5678".into());
crate::space_mouse_calibration::start(&mut app);
frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02);
assert_eq!(app.space_mouse.raw, resting);
app.space_mouse.calibrating = None;
// A device resting far off zero, calibrated: still at rest, moving when pushed.
let mut offset = homemade();
for axis in &mut offset.axes {
axis.rest = 1000;
}
app.preferences.space_mouse_calibrations.insert("web 1234:5678".into(), offset);
let at_rest = Axes { translation: [1000; 3], rotation: [1000; 3] };
assert!(!frame(&mut app, &ctx, DriverMapping::default(), at_rest, 0.02));
assert_eq!(app.cam, before);
assert!(frame(&mut app, &ctx, DriverMapping::default(), Axes { rotation: [1000, 1000 - 3500, 1000], ..at_rest }, 0.02));
}
#[test]
fn another_device_turning_up_mid_calibration_ends_it() {
let ctx = window(true);
let mut app = app();
app.space_mouse.device = Some("hid 256f:c63a".into());
crate::space_mouse_calibration::start(&mut app);
frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02);
app.space_mouse.device = Some("spacenavd".into());
assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02), "the new device moves the view");
assert!(app.space_mouse.calibrating.is_none());
assert!(app.preferences.space_mouse_calibrations.is_empty());
}
#[test]
fn calibrations_are_saved_with_the_preferences() {
let mut prefs = crate::prefs::Prefs::default();
prefs.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade());
let mut saved = serde_json::to_value(&prefs).unwrap();
assert_eq!(crate::prefs::lenient(&saved), prefs);
// One that can't be read, or that could spin the view, is dropped on its own.
let mut spinning = homemade();
spinning.axes[0].full = [0; 2];
saved["space_mouse_calibrations"]["spacenavd"] = serde_json::to_value(spinning).unwrap();
saved["space_mouse_calibrations"]["web 046d:c62b"] = serde_json::json!({ "axes": "garbled" });
assert_eq!(crate::prefs::lenient(&saved), prefs);
// One saved before the dead zone setting existed reads with none.
let mut older = serde_json::to_value(homemade()).unwrap();
older.as_object_mut().unwrap().remove("dead_zone_share");
saved["space_mouse_calibrations"]["hid 1234:5678"] = older;
assert_eq!(crate::prefs::lenient(&saved), prefs);
}
}
@@ -0,0 +1,157 @@
//! The 3D mouse calibration window, opened from Preferences › Navigation. It asks the user to
//! leave the cap still, then to move it along each axis both ways, moving on by itself after each
//! (`solidcraft_space_mouse::Wizard`), and saves what it found for the device it started with.
//! The window closes with Preferences, and when another device (or none) is read instead.
use solidcraft_space_mouse::{Calibration, Problem, Stage, Wizard};
use crate::SolveApp;
/// What each of `solidcraft_space_mouse::STEPS` asks for, in order.
const STEP_PROMPTS: [&str; 12] = [
"ui.space_mouse_step_slide_right",
"ui.space_mouse_step_slide_left",
"ui.space_mouse_step_pull",
"ui.space_mouse_step_push",
"ui.space_mouse_step_press",
"ui.space_mouse_step_lift",
"ui.space_mouse_step_tilt_back",
"ui.space_mouse_step_tilt_forward",
"ui.space_mouse_step_tilt_left",
"ui.space_mouse_step_tilt_right",
"ui.space_mouse_step_twist_clockwise",
"ui.space_mouse_step_twist_counterclockwise",
];
/// The dead zone, as a share of full travel, shown as a percentage.
pub(crate) fn dead_zone_slider(ui: &mut egui::Ui, share: &mut f32) -> egui::Response {
ui.add(
egui::Slider::new(share, 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE)
.step_by(0.01)
.custom_formatter(|v, _| format!("{:.0} %", v * 100.0)),
)
}
/// The calibration's dead zones the way a game controller tester shows a stick: per pair of axes,
/// a circle for the full travel, the dead zone shaded inside it (each direction its own size), and
/// a dot where the cap is now, before the dead zone, so it's plain when the view starts to move.
pub(crate) fn dead_zone_pads(ui: &mut egui::Ui, calibration: &Calibration, raw: [i16; 6]) {
const NAMES: [&str; 6] = ["X", "Y", "Z", "Rx", "Ry", "Rz"];
// (horizontal axis, its positive way on screen, vertical axis, its positive way down), so the
// dot moves as the cap does: slid right and pulled toward you, twisted and pressed, tilted.
const PADS: [(usize, f32, usize, f32); 3] = [(0, 1.0, 1, 1.0), (5, 1.0, 2, 1.0), (4, -1.0, 3, -1.0)];
const SIZE: f32 = 76.0;
let (shares, travel, moving) = (calibration.dead_zone_shares(), calibration.travel(raw), calibration.apply(raw));
let visuals = ui.visuals().clone();
ui.horizontal(|ui| {
for (h, h_way, v, v_way) in PADS {
ui.vertical(|ui| {
let (rect, response) = ui.allocate_exact_size(egui::vec2(SIZE, SIZE), egui::Sense::hover());
let painter = ui.painter_at(rect);
let (centre, radius) = (rect.center(), SIZE / 2.0 - 2.0);
let faint = visuals.weak_text_color();
// Which side of an axis's dead zone lies along a way on screen.
let side = |axis: usize, way: f32, screen: f32| shares[axis][usize::from(way * screen > 0.0)];
let zone: Vec<egui::Pos2> = (0..64)
.map(|i| {
let (sin, cos) = (i as f32 / 64.0 * std::f32::consts::TAU).sin_cos();
let (x, y) = (side(h, h_way, cos) * cos, side(v, v_way, sin) * sin);
centre + egui::vec2(x, y) * radius
})
.collect();
painter.add(egui::Shape::convex_polygon(zone, visuals.selection.bg_fill.gamma_multiply(0.35), egui::Stroke::NONE));
painter.line_segment(
[centre - egui::vec2(radius, 0.0), centre + egui::vec2(radius, 0.0)],
egui::Stroke::new(1.0, faint.gamma_multiply(0.4)),
);
painter.line_segment(
[centre - egui::vec2(0.0, radius), centre + egui::vec2(0.0, radius)],
egui::Stroke::new(1.0, faint.gamma_multiply(0.4)),
);
painter.circle_stroke(centre, radius, egui::Stroke::new(1.0, faint));
let dot = egui::vec2(h_way * travel[h], v_way * travel[v]);
let dot = if dot.length() > 1.0 { dot.normalized() } else { dot };
let live = moving[h] != 0 || moving[v] != 0;
painter.circle_filled(centre + dot * radius, 3.5, if live { visuals.selection.stroke.color } else { faint });
let percent = |axis: usize| format!("{} −{:.0} % +{:.0} %", NAMES[axis], shares[axis][0] * 100.0, shares[axis][1] * 100.0);
response.on_hover_text(format!("{}\n{}", percent(h), percent(v)));
ui.label(egui::RichText::new(format!("{} · {}", NAMES[h], NAMES[v])).small().color(faint));
});
}
});
}
/// Starts calibrating the device being read, if there is one.
pub fn start(app: &mut SolveApp) {
app.space_mouse.calibrating = app.space_mouse.device.clone().map(|device| (device, Wizard::default()));
}
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some((_, wizard)) = &app.space_mouse.calibrating else { return };
let (stage, progress, result) = (wizard.stage(), wizard.progress(), wizard.result());
let mut dead_zone = wizard.dead_zone_share();
let raw: [i16; 6] = app.space_mouse.raw.into();
let prompt = match (stage, result) {
(Stage::Rest, _) => "ui.space_mouse_step_rest",
(Stage::Step(index), _) => STEP_PROMPTS.get(index).copied().unwrap_or_default(),
(Stage::Done, Some(Ok(_))) => "ui.space_mouse_calibration_done",
(Stage::Done, _) => "ui.space_mouse_calibration_no_response",
};
// The axis that barely moved, as Preferences names it.
let weak = match result {
Some(Err(Problem::NoResponse(axis))) => crate::prefs::SPACE_MOUSE_AXES.get(axis).copied(),
_ => None,
};
let counter = match stage {
Stage::Rest => String::new(),
Stage::Step(index) => format!("{} / {}", index + 1, STEP_PROMPTS.len()),
Stage::Done => format!("{0} / {0}", STEP_PROMPTS.len()),
};
let (mut back, mut over, mut cancel, mut save) = (false, false, false, false);
crate::frame::window(ctx, app.tr("ui.space_mouse_calibrate_title"), crate::frame::Width::Normal)
.id(egui::Id::new("sc_space_mouse_calibration"))
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label(app.tr(prompt));
if let Some(axis) = weak {
ui.label(egui::RichText::new(app.tr_label(axis)).strong());
}
ui.add_space(6.0);
ui.add(egui::ProgressBar::new(progress as f32).text(counter));
if let Some(Ok(calibration)) = result {
ui.add_space(6.0);
dead_zone_pads(ui, &Calibration { dead_zone_share: dead_zone, ..calibration }, raw);
}
// The device's six raw axes as they come, so the jitter at rest is there to see.
let reading = raw.map(|value| format!("{value:>6}")).join(" ");
ui.label(egui::RichText::new(format!("{}: {reading}", app.tr("ui.space_mouse_reading"))).monospace());
ui.horizontal(|ui| {
ui.label(app.tr("ui.space_mouse_dead_zone"));
dead_zone_slider(ui, &mut dead_zone).on_hover_text(app.tr("ui.space_mouse_dead_zone_tip"));
});
ui.add_space(6.0);
ui.horizontal(|ui| {
back = ui.add_enabled(stage != Stage::Rest, egui::Button::new(app.tr("ui.back"))).clicked();
over = matches!(result, Some(Err(_))) && ui.button(app.tr("ui.start_over")).clicked();
cancel = ui.button(app.tr("ui.cancel")).clicked();
save = matches!(result, Some(Ok(_))) && ui.button(app.tr("ui.save")).clicked();
});
});
if cancel {
app.space_mouse.calibrating = None;
} else if let Some((device, wizard)) = &mut app.space_mouse.calibrating {
wizard.set_dead_zone_share(dead_zone);
let result = wizard.result();
if save && let Some(Ok(calibration)) = result {
app.preferences.space_mouse_calibrations.insert(std::mem::take(device), calibration);
app.space_mouse.calibrating = None;
} else if over {
// A new recording; the dead zone set so far stays.
*wizard = Wizard::default();
wizard.set_dead_zone_share(dead_zone);
} else if back {
wizard.back();
}
}
}