Skip to main content

fontoxide_misc/
array_tools.rs

1//! Rectangles and point arrays (`fontTools.misc.arrayTools`).
2//!
3//! Comparisons follow Python's `min` and `max`, which keep the first argument
4//! unless the second one is strictly smaller or larger.
5
6/// A point.
7pub type Point = (f64, f64);
8
9/// A rectangle: `(xMin, yMin, xMax, yMax)`.
10pub type Rect = [f64; 4];
11
12/// Python's `min(a, b)`.
13fn py_min(a: f64, b: f64) -> f64 {
14	if b < a { b } else { a }
15}
16
17/// Python's `max(a, b)`.
18fn py_max(a: f64, b: f64) -> f64 {
19	if b > a { b } else { a }
20}
21
22/// `calcBounds`: the bounding rectangle of the points; `(0, 0, 0, 0)` if there
23/// are none.
24pub fn calc_bounds(points: &[Point]) -> Rect {
25	let Some(&(x0, y0)) = points.first() else {
26		return [0.0; 4];
27	};
28	points[1..].iter().fold([x0, y0, x0, y0], |b, &(x, y)| {
29		[
30			py_min(b[0], x),
31			py_min(b[1], y),
32			py_max(b[2], x),
33			py_max(b[3], y),
34		]
35	})
36}
37
38/// `updateBounds`: the rectangle extended to include `p`.
39pub fn update_bounds(bounds: Rect, (x, y): Point) -> Rect {
40	[
41		py_min(bounds[0], x),
42		py_min(bounds[1], y),
43		py_max(bounds[2], x),
44		py_max(bounds[3], y),
45	]
46}
47
48/// `pointInRect`: whether the point is inside the rectangle or on its edge.
49pub fn point_in_rect((x, y): Point, rect: Rect) -> bool {
50	rect[0] <= x && x <= rect[2] && rect[1] <= y && y <= rect[3]
51}
52
53/// `unionRect`: the smallest rectangle containing both.
54pub fn union_rect(a: Rect, b: Rect) -> Rect {
55	[
56		py_min(a[0], b[0]),
57		py_min(a[1], b[1]),
58		py_max(a[2], b[2]),
59		py_max(a[3], b[3]),
60	]
61}
62
63/// `intRect`: the smallest integer rectangle containing the rectangle.
64pub fn int_rect(rect: Rect) -> [i64; 4] {
65	[
66		rect[0].floor() as i64,
67		rect[1].floor() as i64,
68		rect[2].ceil() as i64,
69		rect[3].ceil() as i64,
70	]
71}
72
73/// `calcIntBounds`: the bounding rectangle, rounded with `round` (`otRound` in
74/// fontTools).
75pub fn calc_int_bounds(points: &[Point], round: impl Fn(f64) -> i64) -> [i64; 4] {
76	calc_bounds(points).map(round)
77}
78
79/// `pointsInRect`: for each point, whether it is inside the rectangle.
80pub fn points_in_rect(points: &[Point], rect: Rect) -> Vec<bool> {
81	points.iter().map(|&p| point_in_rect(p, rect)).collect()
82}
83
84/// `vectorLength`.
85pub fn vector_length((x, y): Point) -> f64 {
86	(x.powi(2) + y.powi(2)).sqrt()
87}
88
89/// `asInt16`: each value rounded half up.
90pub fn as_int16(values: &[f64]) -> Vec<i64> {
91	values.iter().map(|&v| (v + 0.5).floor() as i64).collect()
92}
93
94/// `normRect`: the rectangle with `xMin <= xMax` and `yMin <= yMax`.
95pub fn norm_rect(rect: Rect) -> Rect {
96	let [x_min, y_min, x_max, y_max] = rect;
97	[
98		py_min(x_min, x_max),
99		py_min(y_min, y_max),
100		py_max(x_min, x_max),
101		py_max(y_min, y_max),
102	]
103}
104
105/// `scaleRect`.
106pub fn scale_rect(rect: Rect, x: f64, y: f64) -> Rect {
107	[rect[0] * x, rect[1] * y, rect[2] * x, rect[3] * y]
108}
109
110/// `offsetRect`.
111pub fn offset_rect(rect: Rect, dx: f64, dy: f64) -> Rect {
112	[rect[0] + dx, rect[1] + dy, rect[2] + dx, rect[3] + dy]
113}
114
115/// `insetRect`: the rectangle inset by `dx` and `dy` on all sides.
116pub fn inset_rect(rect: Rect, dx: f64, dy: f64) -> Rect {
117	[rect[0] + dx, rect[1] + dy, rect[2] - dx, rect[3] - dy]
118}
119
120/// `sectRect`: the intersection of the rectangles, or `None` if they do not
121/// intersect (`(False, (0, 0, 0, 0))`).
122pub fn sect_rect(a: Rect, b: Rect) -> Option<Rect> {
123	let r = [
124		py_max(a[0], b[0]),
125		py_max(a[1], b[1]),
126		py_min(a[2], b[2]),
127		py_min(a[3], b[3]),
128	];
129	if r[0] >= r[2] || r[1] >= r[3] {
130		None
131	} else {
132		Some(r)
133	}
134}
135
136/// `rectCenter`.
137pub fn rect_center(rect: Rect) -> Point {
138	((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0)
139}
140
141/// `rectArea`.
142pub fn rect_area(rect: Rect) -> f64 {
143	(rect[3] - rect[1]) * (rect[2] - rect[0])
144}
145
146/// `quantizeRect`: the rectangle, normalized, with its edges moved outwards to
147/// multiples of `factor`. `None` for a factor below 1 (`ValueError`).
148pub fn quantize_rect(rect: Rect, factor: f64) -> Option<[i64; 4]> {
149	if factor < 1.0 {
150		return None;
151	}
152	let [x_min, y_min, x_max, y_max] = norm_rect(rect);
153	Some([
154		((x_min / factor).floor() * factor) as i64,
155		((y_min / factor).floor() * factor) as i64,
156		((x_max / factor).ceil() * factor) as i64,
157		((y_max / factor).ceil() * factor) as i64,
158	])
159}
160
161/// `pairwise`: each item with the next one, the last with the first; in
162/// reverse order if `reverse`.
163pub fn pairwise<T: Copy>(items: &[T], reverse: bool) -> Vec<(T, T)> {
164	let n = items.len();
165	let at = |i: usize| if reverse { items[n - 1 - i] } else { items[i] };
166	(0..n).map(|i| (at(i), at((i + 1) % n))).collect()
167}
168
169#[cfg(test)]
170mod tests {
171	use super::*;
172
173	// Cases from fontTools' doctests.
174	#[test]
175	fn doctests() {
176		assert_eq!(
177			calc_bounds(&[(0.0, 40.0), (0.0, 100.0), (50.0, 50.0), (80.0, 10.0)]),
178			[0.0, 10.0, 80.0, 100.0]
179		);
180		assert_eq!(calc_bounds(&[]), [0.0; 4]);
181		assert_eq!(
182			union_rect([0.0, 10.0, 20.0, 30.0], [0.0, 40.0, 20.0, 50.0]),
183			[0.0, 10.0, 20.0, 50.0]
184		);
185		assert_eq!(int_rect([0.9, 2.9, 3.1, 4.1]), [0, 2, 4, 5]);
186		assert!(point_in_rect((50.0, 50.0), [0.0, 0.0, 100.0, 100.0]));
187		assert!(!point_in_rect((150.0, 50.0), [0.0, 0.0, 100.0, 100.0]));
188		assert_eq!(
189			update_bounds([0.0, 0.0, 100.0, 100.0], (200.0, -10.0)),
190			[0.0, -10.0, 200.0, 100.0]
191		);
192	}
193
194	// `arrayTools._test`.
195	#[test]
196	fn array_tools_test() {
197		assert_eq!(
198			update_bounds([0.0; 4], (100.0, 100.0)),
199			[0.0, 0.0, 100.0, 100.0]
200		);
201		assert!(point_in_rect((0.0, 0.0), [0.0, 0.0, 100.0, 100.0]));
202		assert!(point_in_rect((100.0, 100.0), [0.0, 0.0, 100.0, 100.0]));
203		assert!(!point_in_rect((101.0, 100.0), [0.0, 0.0, 100.0, 100.0]));
204		assert_eq!(
205			points_in_rect(
206				&[(50.0, 50.0), (0.0, 0.0), (100.0, 100.0), (101.0, 100.0)],
207				[0.0, 0.0, 100.0, 100.0]
208			),
209			[true, true, true, false]
210		);
211		assert_eq!(vector_length((3.0, 4.0)), 5.0);
212		assert_eq!(vector_length((1.0, 1.0)), 2f64.sqrt());
213		assert_eq!(as_int16(&[0.0, 0.1, 0.5, 0.9]), [0, 0, 1, 1]);
214		assert_eq!(
215			norm_rect([0.0, 10.0, 100.0, 200.0]),
216			[0.0, 10.0, 100.0, 200.0]
217		);
218		assert_eq!(
219			norm_rect([100.0, 200.0, 0.0, 10.0]),
220			[0.0, 10.0, 100.0, 200.0]
221		);
222		assert_eq!(
223			scale_rect([10.0, 20.0, 50.0, 150.0], 1.5, 2.0),
224			[15.0, 40.0, 75.0, 300.0]
225		);
226		assert_eq!(
227			offset_rect([10.0, 20.0, 30.0, 40.0], 5.0, 6.0),
228			[15.0, 26.0, 35.0, 46.0]
229		);
230		assert_eq!(
231			inset_rect([10.0, 20.0, 50.0, 60.0], 5.0, 10.0),
232			[15.0, 30.0, 45.0, 50.0]
233		);
234		assert_eq!(
235			inset_rect([10.0, 20.0, 50.0, 60.0], -5.0, -10.0),
236			[5.0, 10.0, 55.0, 70.0]
237		);
238		assert_eq!(
239			sect_rect([0.0, 10.0, 20.0, 30.0], [0.0, 40.0, 20.0, 50.0]),
240			None
241		);
242		assert_eq!(
243			sect_rect([0.0, 10.0, 20.0, 30.0], [5.0, 20.0, 35.0, 50.0]),
244			Some([5.0, 20.0, 20.0, 30.0])
245		);
246		assert_eq!(rect_center([0.0, 0.0, 100.0, 200.0]), (50.0, 100.0));
247		assert_eq!(rect_center([0.0, 0.0, 100.0, 199.0]), (50.0, 99.5));
248	}
249
250	#[test]
251	fn quantize_rect_doctests() {
252		let bounds = [72.3, -218.4, 1201.3, 919.1];
253		assert_eq!(quantize_rect(bounds, 1.0), Some([72, -219, 1202, 920]));
254		assert_eq!(quantize_rect(bounds, 10.0), Some([70, -220, 1210, 920]));
255		assert_eq!(quantize_rect(bounds, 100.0), Some([0, -300, 1300, 1000]));
256		assert_eq!(quantize_rect(bounds, 0.5), None);
257	}
258
259	#[test]
260	fn pairwise_doctests() {
261		assert_eq!(pairwise::<i32>(&[], false), []);
262		assert_eq!(pairwise(&[0], false), [(0, 0)]);
263		assert_eq!(pairwise(&[0], true), [(0, 0)]);
264		assert_eq!(pairwise(&[0, 1], false), [(0, 1), (1, 0)]);
265		assert_eq!(pairwise(&[0, 1], true), [(1, 0), (0, 1)]);
266		assert_eq!(pairwise(&[0, 1, 2], false), [(0, 1), (1, 2), (2, 0)]);
267		assert_eq!(pairwise(&[0, 1, 2], true), [(2, 1), (1, 0), (0, 2)]);
268		assert_eq!(
269			pairwise(&['a', 'b', 'c', 'd'], true),
270			[('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd')]
271		);
272	}
273}