gpui_types/math.rs
1//! Device-pixel snapping helpers shared by layout and painting.
2//!
3//! Layout resolves fractional positions and sizes; painting them directly
4//! produces blurry edges. These helpers round in device-pixel space so painted
5//! edges land on physical pixel boundaries. They live in this leaf crate so the
6//! engine (`gpui_engine_default`) and the facade (`gpui`) snap identically.
7
8/// Rounds to the nearest integer with 0.5 ties toward zero.
9#[inline]
10pub fn round_half_toward_zero(value: f32) -> f32 {
11 (value.abs() - 0.5).ceil().copysign(value)
12}
13
14/// Rounds to the nearest integer with 0.5 ties toward zero.
15#[inline]
16pub fn round_half_toward_zero_f64(value: f64) -> f64 {
17 (value.abs() - 0.5).ceil().copysign(value)
18}
19
20/// Rounds a logical coordinate to the nearest device pixel.
21#[inline]
22pub fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
23 round_half_toward_zero(logical * scale_factor)
24}
25
26/// Snaps a stroke width to at least one device pixel.
27#[inline]
28pub fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
29 if logical == 0.0 {
30 0.0
31 } else {
32 round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
33 }
34}
35
36/// Rounds a logical coordinate down to a device pixel boundary.
37#[inline]
38pub fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
39 (logical * scale_factor).floor()
40}
41
42/// Rounds a logical coordinate up to a device pixel boundary.
43#[inline]
44pub fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
45 (logical * scale_factor).ceil()
46}