Skip to main content

rust_css_parser/ast/transform/
utils.rs

1//! Port of `src/ast/transform/utils.ts`: matrix operations of the transform functions.
2
3use super::{DecomposedMatrix3D, Matrix};
4use crate::syntax::constants::epsilon;
5use crate::utils::number::{js_round, js_to_precision};
6
7/// the identity matrix
8pub const IDENTITY_MATRIX: Matrix = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
9
10pub fn identity() -> Matrix {
11    IDENTITY_MATRIX
12}
13
14pub fn set_identity(matrix: &mut Matrix) -> &mut Matrix {
15    *matrix = IDENTITY_MATRIX;
16    matrix
17}
18
19/// true if the values are equal (`===`) to the values of the identity matrix
20pub fn is_identity(matrix: &Matrix) -> bool {
21    matrix.iter().zip(IDENTITY_MATRIX.iter()).all(|(a, b)| a == b)
22}
23
24pub fn multiply(a: &Matrix, b: &Matrix) -> Matrix {
25    let mut result = [0.0; 16];
26    multiply_into(a, b, &mut result);
27    result
28}
29
30/// `result = a × b` (the operands are read before the result is written)
31pub fn multiply_into(a: &Matrix, b: &Matrix, result: &mut Matrix) {
32    let a = *a;
33    let b = *b;
34    for column in (0..16).step_by(4) {
35        let (b0, b1, b2, b3) = (b[column], b[column + 1], b[column + 2], b[column + 3]);
36        result[column] = a[0] * b0 + a[4] * b1 + a[8] * b2 + a[12] * b3;
37        result[column + 1] = a[1] * b0 + a[5] * b1 + a[9] * b2 + a[13] * b3;
38        result[column + 2] = a[2] * b0 + a[6] * b1 + a[10] * b2 + a[14] * b3;
39        result[column + 3] = a[3] * b0 + a[7] * b1 + a[11] * b2 + a[15] * b3;
40    }
41}
42
43/// `matrix = matrix × b`
44pub fn multiply_in_place(matrix: &mut Matrix, b: &Matrix) {
45    let a = *matrix;
46    multiply_into(&a, b, matrix);
47}
48
49/// inverse of a matrix, used to extract the perspective (the typescript indexing is kept: the augmented rows are
50/// written with a stride of 8 and read with a stride of 4)
51fn inverse(matrix: &Matrix) -> Option<[f64; 32]> {
52    let mut augmented = [0.0f64; 32];
53    for row in 0..4 {
54        for j in 0..4 {
55            augmented[row * 8 + j] = matrix[row * 4 + j];
56            augmented[row * 8 + 4 + j] = if row == j { 1.0 } else { 0.0 };
57        }
58    }
59    for col in 0..4 {
60        let mut max_row = col;
61        let mut max_val = augmented[col * 4 + col].abs();
62        for row in col + 1..4 {
63            let val = augmented[row * 4 + col].abs();
64            if val > max_val {
65                max_val = val;
66                max_row = row;
67            }
68        }
69        if max_val < epsilon {
70            return None;
71        }
72        if max_row != col {
73            augmented.swap(col, max_row);
74        }
75        let pivot = augmented[col * 4 + col];
76        for j in 0..8 {
77            augmented[col * 4 + j] /= pivot;
78        }
79        for row in 0..4 {
80            if row != col {
81                let factor = augmented[row * 4 + col];
82                for j in 0..8 {
83                    augmented[row * 4 + j] -= factor * augmented[col * 4 + j];
84                }
85            }
86        }
87    }
88    Some(augmented)
89}
90
91/// `+value.toPrecision(6)`
92pub fn to_precision6(value: f64) -> f64 {
93    js_to_precision(value, 6)
94}
95
96/// round a number to 6 significant digits, or to the nearest integer when it is closer than `epsilon`
97pub fn round(number: f64) -> f64 {
98    let rounded = js_round(number);
99    if (rounded - number).abs() <= epsilon {
100        rounded
101    } else {
102        to_precision6(number)
103    }
104}
105
106/// `Math.hypot()` (v8 algorithm: scaled, compensated sum)
107pub fn js_hypot(values: &[f64]) -> f64 {
108    let mut max = 0.0f64;
109    let mut nan = false;
110    for &v in values {
111        let abs = v.abs();
112        if abs.is_nan() {
113            nan = true;
114        } else if abs > max {
115            max = abs;
116        }
117    }
118    if max == f64::INFINITY {
119        return f64::INFINITY;
120    }
121    if nan {
122        return f64::NAN;
123    }
124    if max == 0.0 {
125        return 0.0;
126    }
127    let mut sum = 0.0f64;
128    let mut compensation = 0.0f64;
129    for &v in values {
130        let n = v.abs() / max;
131        let summand = n * n - compensation;
132        let preliminary = sum + summand;
133        compensation = (preliminary - sum) - summand;
134        sum = preliminary;
135    }
136    sum.sqrt() * max
137}
138
139/// decompose a matrix: translate → rotate → skew → scale. false if the matrix cannot be decomposed
140pub fn decompose(original: &Matrix, result: &mut DecomposedMatrix3D) -> bool {
141    if original[15] == 0.0 {
142        return false;
143    }
144    let mut matrix = *original;
145    // `matrix[i] /= matrix[15]`: the last value is divided last
146    for i in 0..16 {
147        matrix[i] /= matrix[15];
148    }
149    result.perspective_x = 0.0;
150    result.perspective_y = 0.0;
151    result.perspective_z = 0.0;
152    result.perspective_w = 1.0;
153    if matrix[3] != 0.0 || matrix[7] != 0.0 || matrix[11] != 0.0 {
154        let (r0, r1, r2, r3) = (matrix[3], matrix[7], matrix[11], matrix[15]);
155        let Some(inverted) = inverse(original) else {
156            return false;
157        };
158        result.perspective_x = r0 * inverted[0] + r1 * inverted[4] + r2 * inverted[8] + r3 * inverted[12];
159        result.perspective_y = r0 * inverted[1] + r1 * inverted[5] + r2 * inverted[9] + r3 * inverted[13];
160        result.perspective_z = r0 * inverted[2] + r1 * inverted[6] + r2 * inverted[10] + r3 * inverted[14];
161        result.perspective_w = r0 * inverted[3] + r1 * inverted[7] + r2 * inverted[11] + r3 * inverted[15];
162        matrix[3] = 0.0;
163        matrix[7] = 0.0;
164        matrix[11] = 0.0;
165        matrix[15] = 1.0;
166    }
167    result.translate_x = matrix[12];
168    result.translate_y = matrix[13];
169    result.translate_z = matrix[14];
170    let (row00, row01, row02) = (matrix[0], matrix[1], matrix[2]);
171    let (row10, row11, row12) = (matrix[4], matrix[5], matrix[6]);
172    let (row20, row21, row22) = (matrix[8], matrix[9], matrix[10]);
173    let cross0 = row11 * row22 - row12 * row21;
174    let cross1 = row12 * row20 - row10 * row22;
175    let cross2 = row10 * row21 - row11 * row20;
176    let scale_x = js_hypot(&[row00, row01, row02]);
177    let norm = (row00 * row00 + row01 * row01 + row02 * row02).sqrt();
178    let n = |v: f64, norm: f64| if norm == 0.0 { 0.0 } else { v / norm };
179    let (row0_norm0, row0_norm1, row0_norm2) = (n(row00, norm), n(row01, norm), n(row02, norm));
180    let skew_xy = row0_norm0 * row10 + row0_norm1 * row11 + row0_norm2 * row12;
181    let row1_proj0 = row10 - skew_xy * row0_norm0;
182    let row1_proj1 = row11 - skew_xy * row0_norm1;
183    let row1_proj2 = row12 - skew_xy * row0_norm2;
184    let scale_y = js_hypot(&[row1_proj0, row1_proj1, row1_proj2]);
185    let norm = (row1_proj0 * row1_proj0 + row1_proj1 * row1_proj1 + row1_proj2 * row1_proj2).sqrt();
186    let (row1_norm0, row1_norm1, row1_norm2) = (n(row1_proj0, norm), n(row1_proj1, norm), n(row1_proj2, norm));
187    let skew_xz = row0_norm0 * row20 + row0_norm1 * row21 + row0_norm2 * row22;
188    let skew_yz = row1_norm0 * row20 + row1_norm1 * row21 + row1_norm2 * row22;
189    let row2_proj0 = row20 - skew_xz * row0_norm0 - skew_yz * row1_norm0;
190    let row2_proj1 = row21 - skew_xz * row0_norm1 - skew_yz * row1_norm1;
191    let row2_proj2 = row22 - skew_xz * row0_norm2 - skew_yz * row1_norm2;
192    let norm = (row2_proj0 * row2_proj0 + row2_proj1 * row2_proj1 + row2_proj2 * row2_proj2).sqrt();
193    let (row2_norm0, row2_norm1, row2_norm2) = (n(row2_proj0, norm), n(row2_proj1, norm), n(row2_proj2, norm));
194    let determinant = row00 * cross0 + row01 * cross1 + row02 * cross2;
195    let scale_z = js_hypot(&[row2_proj0, row2_proj1, row2_proj2]) * if determinant < 0.0 { -1.0 } else { 1.0 };
196    let (r00, r01, r02) = (row0_norm0, row1_norm0, row2_norm0);
197    let (r10, r11, r12) = (row0_norm1, row1_norm1, row2_norm1);
198    let (r20, r21, r22) = (row0_norm2, row1_norm2, row2_norm2);
199    let trace = r00 + r11 + r22;
200    let (qw, mut qx, mut qy, mut qz);
201    if trace > 0.0 {
202        let s = 0.5 / (trace + 1.0).sqrt();
203        qw = 0.25 / s;
204        qx = (r21 - r12) * s;
205        qy = (r02 - r20) * s;
206        qz = (r10 - r01) * s;
207    } else if r00 > r11 && r00 > r22 {
208        let s = 2.0 * (1.0 + r00 - r11 - r22).sqrt();
209        qw = (r21 - r12) / s;
210        qx = 0.25 * s;
211        qy = (r01 + r10) / s;
212        qz = (r02 + r20) / s;
213    } else if r11 > r22 {
214        let s = 2.0 * (1.0 + r11 - r00 - r22).sqrt();
215        qw = (r02 - r20) / s;
216        qx = (r01 + r10) / s;
217        qy = 0.25 * s;
218        qz = (r12 + r21) / s;
219    } else {
220        let s = 2.0 * (1.0 + r22 - r00 - r11).sqrt();
221        qw = (r10 - r01) / s;
222        qx = (r02 + r20) / s;
223        qy = (r12 + r21) / s;
224        qz = 0.25 * s;
225    }
226    qx = to_zero_value(qx);
227    qy = to_zero_value(qy);
228    qz = to_zero_value(qz);
229    // smallest non zero absolute value of the axis components
230    let mut q = 0.0f64;
231    for abs in [qx.abs(), qy.abs(), qz.abs()] {
232        if q == 0.0 || (abs > 0.0 && abs < q) {
233            q = abs;
234        }
235    }
236    if q > 0.0 {
237        qx /= q;
238        qy /= q;
239        qz /= q;
240    }
241    result.rotate_x = qx;
242    result.rotate_y = qy;
243    result.rotate_z = qz;
244    // `Object.is(qw, +0)`
245    result.rotate_angle = if qw == 0.0 && qw.is_sign_positive() { 0.0 } else { 2.0 * qw.acos() * 180.0 / std::f64::consts::PI };
246    result.scale_x = scale_x;
247    result.scale_y = scale_y;
248    result.scale_z = scale_z;
249    result.skew_xy = skew_xy;
250    result.skew_xz = skew_xz;
251    result.skew_yz = skew_yz;
252    true
253}
254
255/// a value close to 0 (`epsilon`) is set to 0, the other values are rounded to 6 significant digits
256pub fn to_zero_value(value: f64) -> f64 {
257    if value.abs() <= epsilon {
258        return 0.0;
259    }
260    if value.fract() == 0.0 && value < 1e6 && value > -1e6 {
261        return value;
262    }
263    to_precision6(value)
264}
265
266pub fn to_zero(matrix: &mut Matrix) -> &mut Matrix {
267    for v in matrix.iter_mut() {
268        *v = to_zero_value(*v);
269    }
270    matrix
271}
272
273/// <https://drafts.csswg.org/css-transforms-1/#2d-matrix>
274pub fn is_2d_matrix(m: &Matrix) -> bool {
275    m[2] == 0.0 && m[3] == 0.0 && m[6] == 0.0 && m[7] == 0.0 && m[8] == 0.0 && m[9] == 0.0 && m[11] == 0.0 && m[14] == 0.0 && m[10] == 1.0 && m[15] == 1.0
276}