1use crate::{Point, Rect, Size};
4
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
7pub struct WindowCoordinates {
8 pub size: Size,
10 pub local_to_window: ProjectiveTransform,
12}
13
14impl WindowCoordinates {
15 pub fn bounds(self) -> Rect {
17 self.local_to_window
18 .bounds_for_rect(Rect::from_size(self.size))
19 }
20}
21
22pub const NEAR_W: f32 = 1.0 / 64.0;
27
28#[derive(Clone, Copy, Debug)]
30pub struct ProjectiveTransform {
31 matrix: [[f32; 3]; 3],
32}
33
34#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct FrontPolygon {
39 corners: [[f32; 2]; 5],
40 len: u8,
41}
42
43impl FrontPolygon {
44 pub fn of_rect(rect: Rect) -> Self {
47 let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
48 Self {
49 corners: [
50 [rect.x, rect.y],
51 [right, rect.y],
52 [right, bottom],
53 [rect.x, bottom],
54 [0.0; 2],
55 ],
56 len: 4,
57 }
58 }
59
60 fn push(&mut self, corner: [f32; 2]) {
61 self.corners[usize::from(self.len)] = corner;
62 self.len += 1;
63 }
64
65 pub fn corners(&self) -> &[[f32; 2]] {
67 &self.corners[..usize::from(self.len)]
68 }
69
70 pub fn is_empty(&self) -> bool {
72 self.len < 3
73 }
74
75 pub fn strip(&self) -> [[f32; 2]; 5] {
78 let c = self.corners;
79 match self.len {
80 5 => [c[0], c[1], c[4], c[2], c[3]],
81 4 => [c[0], c[1], c[3], c[2], c[2]],
82 _ => c,
83 }
84 }
85
86 pub fn bounds(&self) -> Rect {
89 if self.is_empty() {
90 return Rect::from_size(Size::ZERO);
91 }
92 let (mut min, mut max) = ([f32::INFINITY; 2], [f32::NEG_INFINITY; 2]);
93 for corner in self.corners() {
94 min = [min[0].min(corner[0]), min[1].min(corner[1])];
95 max = [max[0].max(corner[0]), max[1].max(corner[1])];
96 }
97 Rect {
98 x: min[0],
99 y: min[1],
100 width: (max[0] - min[0]).max(0.0),
101 height: (max[1] - min[1]).max(0.0),
102 }
103 }
104}
105
106impl PartialEq for ProjectiveTransform {
107 fn eq(&self, other: &Self) -> bool {
108 let [[a0, a1, a2], [a3, a4, a5], [a6, a7, a8]] = self.matrix;
111 let [[b0, b1, b2], [b3, b4, b5], [b6, b7, b8]] = other.matrix;
112 a0 == b0
113 && a1 == b1
114 && a2 == b2
115 && a3 == b3
116 && a4 == b4
117 && a5 == b5
118 && a6 == b6
119 && a7 == b7
120 && a8 == b8
121 }
122}
123
124impl ProjectiveTransform {
125 pub const fn identity() -> Self {
127 Self {
128 matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
129 }
130 }
131
132 pub fn translation(tx: f32, ty: f32) -> Self {
134 Self {
135 matrix: [[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]],
136 }
137 }
138
139 pub fn uniform_scale(scale: f32) -> Self {
142 Self {
143 matrix: [[scale, 0.0, 0.0], [0.0, scale, 0.0], [0.0, 0.0, 1.0]],
144 }
145 }
146
147 pub fn from_rect_to_quad(rect: Rect, quad: [[f32; 2]; 4]) -> Self {
150 if rect.width.abs() <= f32::EPSILON || rect.height.abs() <= f32::EPSILON {
151 return Self::translation(quad[0][0], quad[0][1]);
152 }
153
154 if let Some(axis_aligned) = axis_aligned_rect_from_quad(quad) {
155 let scale_x = axis_aligned.width / rect.width;
156 let scale_y = axis_aligned.height / rect.height;
157 return Self {
158 matrix: [
159 [scale_x, 0.0, axis_aligned.x - rect.x * scale_x],
160 [0.0, scale_y, axis_aligned.y - rect.y * scale_y],
161 [0.0, 0.0, 1.0],
162 ],
163 };
164 }
165
166 let source = [
167 [rect.x, rect.y],
168 [rect.x + rect.width, rect.y],
169 [rect.x, rect.y + rect.height],
170 [rect.x + rect.width, rect.y + rect.height],
171 ];
172 let Some(coefficients) = solve_homography(source, quad) else {
173 return Self::identity();
174 };
175
176 let solved = Self {
177 matrix: [
178 [coefficients[0], coefficients[1], coefficients[2]],
179 [coefficients[3], coefficients[4], coefficients[5]],
180 [coefficients[6], coefficients[7], 1.0],
181 ],
182 };
183 if solved.w_at(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5) >= 0.0 {
184 return solved;
185 }
186 Self {
187 matrix: solved.matrix.map(|row| row.map(|value| -value)),
188 }
189 }
190
191 pub const fn from_rows(matrix: [[f32; 3]; 3]) -> Self {
194 Self { matrix }
195 }
196
197 pub fn from_homogeneous(matrix: [[f32; 3]; 3]) -> Self {
203 let w = matrix[2][2].abs();
204 if w == 1.0 || w <= f32::EPSILON {
205 return Self { matrix };
206 }
207 Self {
208 matrix: matrix.map(|row| row.map(|value| value / w)),
209 }
210 }
211
212 pub fn then(self, next: Self) -> Self {
214 Self {
215 matrix: multiply_matrices(next.matrix, self.matrix),
216 }
217 }
218
219 pub fn after_translation(self, tx: f32, ty: f32) -> Self {
222 let [[a, b, c], [d, e, f], [g, h, i]] = self.matrix;
225 Self {
226 matrix: [
227 [a, b, a * tx + b * ty + c],
228 [d, e, d * tx + e * ty + f],
229 [g, h, g * tx + h * ty + i],
230 ],
231 }
232 }
233
234 pub fn inverse(self) -> Option<Self> {
236 let m = self.matrix;
237 let a = m[0][0];
238 let b = m[0][1];
239 let c = m[0][2];
240 let d = m[1][0];
241 let e = m[1][1];
242 let f = m[1][2];
243 let g = m[2][0];
244 let h = m[2][1];
245 let i = m[2][2];
246
247 let cofactor00 = e * i - f * h;
248 let cofactor01 = -(d * i - f * g);
249 let cofactor02 = d * h - e * g;
250 let cofactor10 = -(b * i - c * h);
251 let cofactor11 = a * i - c * g;
252 let cofactor12 = -(a * h - b * g);
253 let cofactor20 = b * f - c * e;
254 let cofactor21 = -(a * f - c * d);
255 let cofactor22 = a * e - b * d;
256
257 let determinant = a * cofactor00 + b * cofactor01 + c * cofactor02;
258 if determinant.abs() <= f32::EPSILON {
259 return None;
260 }
261 let inverse_determinant = 1.0 / determinant;
262
263 Some(Self {
264 matrix: [
265 [
266 cofactor00 * inverse_determinant,
267 cofactor10 * inverse_determinant,
268 cofactor20 * inverse_determinant,
269 ],
270 [
271 cofactor01 * inverse_determinant,
272 cofactor11 * inverse_determinant,
273 cofactor21 * inverse_determinant,
274 ],
275 [
276 cofactor02 * inverse_determinant,
277 cofactor12 * inverse_determinant,
278 cofactor22 * inverse_determinant,
279 ],
280 ],
281 })
282 }
283
284 pub fn matrix(self) -> [[f32; 3]; 3] {
286 self.matrix
287 }
288
289 pub fn as_translation(self) -> Option<Point> {
291 let [[a, b, x], [c, d, y], [p, q, w]] = self.matrix;
292 [a - 1.0, b, c, d - 1.0, p, q, w - 1.0]
295 .iter()
296 .all(|entry| entry.abs() <= 0.0)
297 .then_some(Point { x, y })
298 }
299
300 pub fn map_point(&self, point: Point) -> Point {
302 let x = point.x;
303 let y = point.y;
304 let w = self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2];
305 let mapped_x = self.matrix[0][0] * x + self.matrix[0][1] * y + self.matrix[0][2];
306 let mapped_y = self.matrix[1][0] * x + self.matrix[1][1] * y + self.matrix[1][2];
307 if w == 1.0 {
310 return Point {
311 x: mapped_x,
312 y: mapped_y,
313 };
314 }
315 let safe_w = if w.abs() <= f32::EPSILON { 1.0 } else { w };
316
317 Point {
318 x: mapped_x / safe_w,
319 y: mapped_y / safe_w,
320 }
321 }
322
323 pub fn map_rect(&self, rect: Rect) -> [[f32; 2]; 4] {
325 let right = rect.x + rect.width;
326 let bottom = rect.y + rect.height;
327 let corner = |x, y| {
328 let point = self.map_point(Point { x, y });
329 [point.x, point.y]
330 };
331 [
332 corner(rect.x, rect.y),
333 corner(right, rect.y),
334 corner(rect.x, bottom),
335 corner(right, bottom),
336 ]
337 }
338
339 fn w_at(&self, x: f32, y: f32) -> f32 {
340 self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2]
341 }
342
343 pub fn in_front(&self, point: Point) -> bool {
347 self.w_at(point.x, point.y) >= NEAR_W
348 }
349
350 pub fn rect_in_front(&self, rect: Rect) -> bool {
352 let right = rect.x + rect.width;
353 let bottom = rect.y + rect.height;
354 [
355 (rect.x, rect.y),
356 (right, rect.y),
357 (rect.x, bottom),
358 (right, bottom),
359 ]
360 .into_iter()
361 .all(|(x, y)| self.w_at(x, y) >= NEAR_W)
362 }
363
364 pub fn map_point_in_front(&self, point: Point) -> Option<Point> {
370 let w = self.w_at(point.x, point.y);
371 (w > 0.0 && w * NEAR_W <= 1.0).then(|| self.map_point(point))
372 }
373
374 pub fn front_polygon(&self, rect: Rect) -> FrontPolygon {
378 let right = rect.x + rect.width;
379 let bottom = rect.y + rect.height;
380 let around = [
381 [rect.x, rect.y],
382 [right, rect.y],
383 [right, bottom],
384 [rect.x, bottom],
385 ];
386 let mut polygon = FrontPolygon {
387 corners: [[0.0; 2]; 5],
388 len: 0,
389 };
390 let mapped = |[x, y]: [f32; 2]| {
391 let point = self.map_point(Point { x, y });
392 [point.x, point.y]
393 };
394 for (index, &from) in around.iter().enumerate() {
395 let to = around[(index + 1) % around.len()];
396 let (w_from, w_to) = (self.w_at(from[0], from[1]), self.w_at(to[0], to[1]));
397 if w_from >= NEAR_W {
398 polygon.push(mapped(from));
399 }
400 if (w_from >= NEAR_W) != (w_to >= NEAR_W) {
401 let t = (NEAR_W - w_from) / (w_to - w_from);
402 polygon.push(mapped([
403 from[0] + (to[0] - from[0]) * t,
404 from[1] + (to[1] - from[1]) * t,
405 ]));
406 }
407 }
408 polygon
409 }
410
411 pub fn bounds_for_rect(&self, rect: Rect) -> Rect {
414 let [[sx, kx, tx], [ky, sy, ty], [px, py, w]] = self.matrix;
415 if kx != 0.0 || ky != 0.0 || px != 0.0 || py != 0.0 || w != 1.0 {
416 return self.turned_bounds_for_rect(rect);
417 }
418 let x0 = sx * rect.x + tx;
421 let x1 = sx * (rect.x + rect.width) + tx;
422 let y0 = sy * rect.y + ty;
423 let y1 = sy * (rect.y + rect.height) + ty;
424 Rect {
425 x: x0.min(x1),
426 y: y0.min(y1),
427 width: (x1 - x0).abs(),
428 height: (y1 - y0).abs(),
429 }
430 }
431
432 #[inline(never)]
433 fn turned_bounds_for_rect(&self, rect: Rect) -> Rect {
434 let [_, _, [px, py, w]] = self.matrix;
435 if px != 0.0 || py != 0.0 || w != 1.0 {
436 return self.front_polygon(rect).bounds();
437 }
438 quad_bounds(self.map_rect(rect))
439 }
440}
441
442fn axis_aligned_rect_from_quad(quad: [[f32; 2]; 4]) -> Option<Rect> {
443 let top_left = quad[0];
444 let top_right = quad[1];
445 let bottom_left = quad[2];
446 let bottom_right = quad[3];
447 let x_epsilon = 1e-4;
448 let y_epsilon = 1e-4;
449
450 if (top_left[1] - top_right[1]).abs() > y_epsilon
451 || (bottom_left[1] - bottom_right[1]).abs() > y_epsilon
452 || (top_left[0] - bottom_left[0]).abs() > x_epsilon
453 || (top_right[0] - bottom_right[0]).abs() > x_epsilon
454 {
455 return None;
456 }
457
458 Some(Rect {
459 x: top_left[0],
460 y: top_left[1],
461 width: top_right[0] - top_left[0],
462 height: bottom_left[1] - top_left[1],
463 })
464}
465
466impl Default for ProjectiveTransform {
467 fn default() -> Self {
468 Self::identity()
469 }
470}
471
472pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
474 let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = quad;
477 let min_x = f32::INFINITY.min(x0).min(x1).min(x2).min(x3);
478 let min_y = f32::INFINITY.min(y0).min(y1).min(y2).min(y3);
479 let max_x = f32::NEG_INFINITY.max(x0).max(x1).max(x2).max(x3);
480 let max_y = f32::NEG_INFINITY.max(y0).max(y1).max(y2).max(y3);
481
482 Rect {
483 x: min_x,
484 y: min_y,
485 width: (max_x - min_x).max(0.0),
486 height: (max_y - min_y).max(0.0),
487 }
488}
489
490fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
491 let cell = |row: usize, col: usize| {
494 lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col]
495 };
496 [
497 [cell(0, 0), cell(0, 1), cell(0, 2)],
498 [cell(1, 0), cell(1, 1), cell(1, 2)],
499 [cell(2, 0), cell(2, 1), cell(2, 2)],
500 ]
501}
502
503fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
504 let mut matrix = [[0.0f32; 9]; 8];
505 for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
506 let row = index * 2;
507 let x = src[0];
508 let y = src[1];
509 let u = dst[0];
510 let v = dst[1];
511
512 matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
513 matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
514 }
515
516 for pivot in 0..8 {
517 let mut pivot_row = pivot;
518 let mut pivot_value = matrix[pivot][pivot].abs();
519 let mut candidate = pivot + 1;
520 while candidate < 8 {
521 let candidate_value = matrix[candidate][pivot].abs();
522 if candidate_value > pivot_value {
523 pivot_row = candidate;
524 pivot_value = candidate_value;
525 }
526 candidate += 1;
527 }
528
529 if pivot_value <= f32::EPSILON {
530 return None;
531 }
532
533 if pivot_row != pivot {
534 matrix.swap(pivot, pivot_row);
535 }
536
537 let divisor = matrix[pivot][pivot];
538 let mut col = pivot;
539 while col < 9 {
540 matrix[pivot][col] /= divisor;
541 col += 1;
542 }
543
544 for row in 0..8 {
545 if row == pivot {
546 continue;
547 }
548 let factor = matrix[row][pivot];
549 if factor.abs() <= f32::EPSILON {
550 continue;
551 }
552 let mut col = pivot;
553 while col < 9 {
554 matrix[row][col] -= factor * matrix[pivot][col];
555 col += 1;
556 }
557 }
558 }
559
560 let mut solution = [0.0f32; 8];
561 for index in 0..8 {
562 solution[index] = matrix[index][8];
563 }
564 Some(solution)
565}