tx2-iff 0.1.0

PPF-IFF (Involuted Fractal Format) - Image codec using Physics-Prime Factorization, 360-prime quantization, and symplectic warping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Fixed-point arithmetic for deterministic computation
//!
//! All operations use 16.16 fixed-point format (16 bits integer, 16 bits fractional)
//! to ensure bit-exact reproducibility across platforms (x86, ARM, WASM).
//!
//! No floating-point operations are used to prevent platform-dependent rounding.

use crate::error::{IffError, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Add, Sub, Mul, Div, Neg};

/// 16.16 fixed-point number (16 bits integer, 16 bits fractional)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(transparent)]
pub struct Fixed(i32);

impl Fixed {
    /// Number of fractional bits
    pub const FRAC_BITS: u32 = 16;

    /// Fixed-point scale factor (2^16)
    pub const SCALE: i32 = 1 << Self::FRAC_BITS;

    /// Zero
    pub const ZERO: Fixed = Fixed(0);

    /// One
    pub const ONE: Fixed = Fixed(Self::SCALE);

    /// Negative one
    pub const NEG_ONE: Fixed = Fixed(-Self::SCALE);

    /// Half (0.5)
    pub const HALF: Fixed = Fixed(Self::SCALE / 2);

    /// Pi (3.141592...)
    pub const PI: Fixed = Fixed(205887); // 3.14159... × 2^16

    /// Two pi
    pub const TWO_PI: Fixed = Fixed(411775); // 6.28318... × 2^16

    /// Create from raw i32 value (internal representation)
    #[inline]
    pub const fn from_raw(val: i32) -> Self {
        Fixed(val)
    }

    /// Get raw i32 value
    #[inline]
    pub const fn raw(self) -> i32 {
        self.0
    }

    /// Create from integer
    #[inline]
    pub const fn from_int(val: i32) -> Self {
        Fixed(val * Self::SCALE)
    }

    /// Convert to integer (truncate fractional part)
    #[inline]
    pub const fn to_int(self) -> i32 {
        self.0 / Self::SCALE
    }

    /// Convert to integer (round to nearest)
    #[inline]
    pub const fn to_int_round(self) -> i32 {
        (self.0 + Self::SCALE / 2) / Self::SCALE
    }

    /// Create from f32 (for testing/initialization only, not for runtime)
    #[inline]
    pub fn from_f32(val: f32) -> Self {
        Fixed((val * Self::SCALE as f32) as i32)
    }

    /// Convert to f32 (for display/testing only)
    #[inline]
    pub fn to_f32(self) -> f32 {
        self.0 as f32 / Self::SCALE as f32
    }

    /// Absolute value
    #[inline]
    pub const fn abs(self) -> Self {
        Fixed(self.0.abs())
    }

    /// Floor
    #[inline]
    pub const fn floor(self) -> Self {
        Fixed(self.0 & !((1 << Self::FRAC_BITS) - 1))
    }

    /// Ceiling
    #[inline]
    pub const fn ceil(self) -> Self {
        let mask = (1 << Self::FRAC_BITS) - 1;
        if self.0 & mask == 0 {
            Fixed(self.0)
        } else {
            Fixed((self.0 | mask) + 1)
        }
    }

    /// Fractional part (always positive)
    #[inline]
    pub const fn fract(self) -> Self {
        Fixed(self.0 & ((1 << Self::FRAC_BITS) - 1))
    }

    /// Multiply with checked overflow
    #[inline]
    pub fn mul_checked(self, rhs: Fixed) -> Result<Fixed> {
        let product = (self.0 as i64) * (rhs.0 as i64);
        let result = (product >> Self::FRAC_BITS) as i32;

        // Check for overflow
        if (product >> Self::FRAC_BITS) != result as i64 {
            return Err(IffError::FixedPointOverflow {
                operation: format!("{} * {}", self.to_f32(), rhs.to_f32()),
            });
        }

        Ok(Fixed(result))
    }

    /// Divide with checked division by zero
    #[inline]
    pub fn div_checked(self, rhs: Fixed) -> Result<Fixed> {
        if rhs.0 == 0 {
            return Err(IffError::FixedPointOverflow {
                operation: "division by zero".to_string(),
            });
        }

        let dividend = (self.0 as i64) << Self::FRAC_BITS;
        let result = (dividend / rhs.0 as i64) as i32;

        Ok(Fixed(result))
    }

    /// Square root using integer Newton-Raphson
    pub fn sqrt(self) -> Result<Fixed> {
        if self.0 < 0 {
            return Err(IffError::FixedPointOverflow {
                operation: "sqrt of negative number".to_string(),
            });
        }

        if self.0 == 0 {
            return Ok(Fixed::ZERO);
        }

        // Initial guess: x/2
        let mut x = Fixed(self.0 >> 1);

        // Newton-Raphson: x_new = (x + self/x) / 2
        for _ in 0..10 {
            let x_div = self.div_checked(x)?;
            let x_new = (x + x_div).0 >> 1;
            if (x_new - x.0).abs() <= 1 {
                break;
            }
            x = Fixed(x_new);
        }

        Ok(x)
    }

    /// Sine using Taylor series (for small angles)
    /// For larger angles, use range reduction first
    pub fn sin_small(self) -> Fixed {
        // sin(x) ≈ x - x³/6 + x⁵/120
        let x = self.0;
        let x2 = ((x as i64 * x as i64) >> Self::FRAC_BITS) as i32;
        let x3 = ((x2 as i64 * x as i64) >> Self::FRAC_BITS) as i32;
        let x5 = ((x3 as i64 * x2 as i64) >> Self::FRAC_BITS) as i32;

        let term1 = x;
        let term2 = x3 / 6;
        let term3 = x5 / 120;

        Fixed(term1 - term2 + term3)
    }

    /// Cosine using Taylor series
    pub fn cos_small(self) -> Fixed {
        // cos(x) ≈ 1 - x²/2 + x⁴/24
        let x = self.0;
        let x2 = ((x as i64 * x as i64) >> Self::FRAC_BITS) as i32;
        let x4 = ((x2 as i64 * x2 as i64) >> Self::FRAC_BITS) as i32;

        let term1 = Self::SCALE;
        let term2 = x2 / 2;
        let term3 = x4 / 24;

        Fixed(term1 - term2 + term3)
    }

    /// Sine with full range using range reduction
    pub fn sin(self) -> Fixed {
        // Range reduction to [-π, π]
        let two_pi = Self::TWO_PI.0;
        let mut x = self.0 % two_pi;
        if x > Self::PI.0 {
            x -= two_pi;
        } else if x < -Self::PI.0 {
            x += two_pi;
        }

        Fixed(x).sin_small()
    }

    /// Cosine with full range
    pub fn cos(self) -> Fixed {
        // cos(x) = sin(x + π/2)
        (self + Fixed(Self::PI.0 / 2)).sin()
    }

    /// Minimum of two values
    #[inline]
    pub const fn min(self, other: Fixed) -> Fixed {
        if self.0 < other.0 {
            self
        } else {
            other
        }
    }

    /// Maximum of two values
    #[inline]
    pub const fn max(self, other: Fixed) -> Fixed {
        if self.0 > other.0 {
            self
        } else {
            other
        }
    }

    /// Clamp to range [min, max]
    #[inline]
    pub const fn clamp(self, min: Fixed, max: Fixed) -> Fixed {
        if self.0 < min.0 {
            min
        } else if self.0 > max.0 {
            max
        } else {
            self
        }
    }
}

impl Add for Fixed {
    type Output = Fixed;

    #[inline]
    fn add(self, rhs: Fixed) -> Fixed {
        Fixed(self.0.wrapping_add(rhs.0))
    }
}

impl Sub for Fixed {
    type Output = Fixed;

    #[inline]
    fn sub(self, rhs: Fixed) -> Fixed {
        Fixed(self.0.wrapping_sub(rhs.0))
    }
}

impl Mul for Fixed {
    type Output = Fixed;

    #[inline]
    fn mul(self, rhs: Fixed) -> Fixed {
        let product = (self.0 as i64) * (rhs.0 as i64);
        Fixed((product >> Self::FRAC_BITS) as i32)
    }
}

impl Div for Fixed {
    type Output = Fixed;

    #[inline]
    fn div(self, rhs: Fixed) -> Fixed {
        let dividend = (self.0 as i64) << Self::FRAC_BITS;
        Fixed((dividend / rhs.0 as i64) as i32)
    }
}

impl Neg for Fixed {
    type Output = Fixed;

    #[inline]
    fn neg(self) -> Fixed {
        Fixed(self.0.wrapping_neg())
    }
}

impl fmt::Display for Fixed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:.6}", self.to_f32())
    }
}

impl From<i32> for Fixed {
    fn from(val: i32) -> Self {
        Fixed::from_int(val)
    }
}

impl From<u16> for Fixed {
    fn from(val: u16) -> Self {
        Fixed::from_int(val as i32)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;

    #[test]
    fn test_constants() {
        assert_eq!(Fixed::ZERO.to_f32(), 0.0);
        assert_eq!(Fixed::ONE.to_f32(), 1.0);
        assert_eq!(Fixed::NEG_ONE.to_f32(), -1.0);
        assert_eq!(Fixed::HALF.to_f32(), 0.5);
        assert_relative_eq!(Fixed::PI.to_f32(), std::f32::consts::PI, epsilon = 0.001);
    }

    #[test]
    fn test_from_int() {
        assert_eq!(Fixed::from_int(5).to_int(), 5);
        assert_eq!(Fixed::from_int(-3).to_int(), -3);
        assert_eq!(Fixed::from_int(0).to_int(), 0);
    }

    #[test]
    fn test_arithmetic() {
        let a = Fixed::from_int(3);
        let b = Fixed::from_int(2);

        assert_eq!((a + b).to_int(), 5);
        assert_eq!((a - b).to_int(), 1);
        assert_eq!((a * b).to_int(), 6);
        assert_eq!((a / b).to_int(), 1); // 3/2 = 1.5 → 1
    }

    #[test]
    fn test_fractional() {
        let a = Fixed::from_f32(3.5);
        let b = Fixed::from_f32(2.25);

        assert_relative_eq!((a + b).to_f32(), 5.75, epsilon = 0.01);
        assert_relative_eq!((a - b).to_f32(), 1.25, epsilon = 0.01);
        assert_relative_eq!((a * b).to_f32(), 7.875, epsilon = 0.01);
    }

    #[test]
    fn test_sqrt() {
        let tests = vec![
            (4.0, 2.0),
            (9.0, 3.0),
            (2.0, 1.414),
            (0.25, 0.5),
        ];

        for (input, expected) in tests {
            let result = Fixed::from_f32(input).sqrt().unwrap();
            assert_relative_eq!(result.to_f32(), expected, epsilon = 0.01);
        }
    }

    #[test]
    fn test_trig() {
        // Test with smaller angles where Taylor series works well
        let angles = vec![0.0, 0.1, 0.3, 0.5];

        for angle in angles {
            let sin_result = Fixed::from_f32(angle).sin().to_f32();
            let cos_result = Fixed::from_f32(angle).cos().to_f32();

            assert_relative_eq!(sin_result, angle.sin(), epsilon = 0.15);
            assert_relative_eq!(cos_result, angle.cos(), epsilon = 0.15);
        }
    }

    #[test]
    fn test_floor_ceil() {
        let a = Fixed::from_f32(3.7);
        assert_eq!(a.floor().to_int(), 3);
        assert_eq!(a.ceil().to_int(), 4);

        let b = Fixed::from_f32(-2.3);
        assert_eq!(b.floor().to_int(), -3);
        assert_eq!(b.ceil().to_int(), -2);
    }

    #[test]
    fn test_min_max_clamp() {
        let a = Fixed::from_int(5);
        let b = Fixed::from_int(10);

        assert_eq!(a.min(b), a);
        assert_eq!(a.max(b), b);

        let c = Fixed::from_int(7);
        assert_eq!(c.clamp(a, b), c);

        let d = Fixed::from_int(3);
        assert_eq!(d.clamp(a, b), a);

        let e = Fixed::from_int(15);
        assert_eq!(e.clamp(a, b), b);
    }

    #[test]
    fn test_determinism() {
        // Test that operations are deterministic (same input → same output)
        let a = Fixed::from_int(7);
        let b = Fixed::from_int(3);

        for _ in 0..100 {
            assert_eq!((a * b).raw(), (a * b).raw());
            assert_eq!((a / b).raw(), (a / b).raw());
        }
    }
}