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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Texture synthesis module (Layer 2: The Flesh)
//!
//! This module implements deterministic texture synthesis using PPF-based noise
//! generation. Instead of storing high-entropy texture pixels, we store compact
//! region descriptors and synthesize the texture on-the-fly during decoding.
//!
//! ## The Cheat
//!
//! Standard codecs spend huge amounts of bits encoding "noise" (pores on skin,
//! grain in asphalt, leaves on trees). We don't store the pixels - we store a
//! synthesizer config and generate the texture deterministically.
//!
//! ## Data Structure
//!
//! A Region stores compact texture synthesis parameters instead of raw pixels:
//! - Position and size (x, y, w, h)
//! - Deterministic noise seed
//! - Chaos level (number of octaves 1-8)
//! - Scale (base frequency log₂)
//! - Persistence (amplitude decay 0-255 → 0.0-1.0)
//! - Noise type (fBm, turbulence, ridged, etc.)
//! - Base color (RGB)
//! - Amplitude (noise amplitude 0-255)

use crate::error::{IffError, Result};
use crate::fixed::Fixed;
use crate::noise::{NoiseParams, PerlinNoise, PpfNoise};
use serde::{Deserialize, Serialize};

/// Texture region descriptor
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Region {
    /// X coordinate (top-left corner)
    pub x: u16,
    /// Y coordinate (top-left corner)
    pub y: u16,
    /// Width in pixels
    pub w: u16,
    /// Height in pixels
    pub h: u16,
    /// Deterministic noise seed
    pub seed: u32,
    /// Number of octaves (1-8)
    pub chaos_level: u8,
    /// Base frequency scale (log₂, 0-7)
    pub scale: u8,
    /// Amplitude decay between octaves (0-255 → 0.0-1.0)
    pub persistence: u8,
    /// Type of noise function
    pub noise_type: NoiseType,
    /// RGB base color
    pub base_color: [u8; 3],
    /// Noise amplitude (0-255)
    pub amplitude: u8,
}

impl Region {
    /// Create a new region with default parameters
    pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
        Region {
            x,
            y,
            w,
            h,
            seed: 0,
            chaos_level: 4,
            scale: 1,
            persistence: 128, // 0.5 in u8 encoding
            noise_type: NoiseType::Fbm,
            base_color: [128, 128, 128],
            amplitude: 64,
        }
    }

    /// Check if a point is inside this region
    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
    }

    /// Get noise parameters for this region
    pub fn noise_params(&self) -> NoiseParams {
        NoiseParams {
            seed: self.seed,
            octaves: self.chaos_level.min(8),
            scale: self.scale.min(7),
            persistence: self.persistence as f32 / 255.0,
            lacunarity: 2.0,
        }
    }
}

/// Type of noise function to use
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum NoiseType {
    /// Fractal Brownian Motion (smooth, natural)
    Fbm = 0,
    /// Turbulence (absolute value, energetic)
    Turbulence = 1,
    /// Ridged multi-fractal (sharp features)
    Ridged = 2,
    /// Warped (domain distortion)
    Warped = 3,
    /// Cellular/Worley (organic cells)
    Cellular = 4,
    /// Perlin (classic gradient noise)
    Perlin = 5,
}

impl Default for NoiseType {
    fn default() -> Self {
        NoiseType::Fbm
    }
}

/// Texture synthesizer
pub struct TextureSynthesizer {
    /// Regions to synthesize
    regions: Vec<Region>,
}

impl TextureSynthesizer {
    /// Create a new synthesizer
    pub fn new() -> Self {
        TextureSynthesizer {
            regions: Vec::new(),
        }
    }

    /// Add a region
    pub fn add_region(&mut self, region: Region) {
        self.regions.push(region);
    }

    /// Get all regions
    pub fn regions(&self) -> &[Region] {
        &self.regions
    }

    /// Synthesize texture for a specific pixel
    pub fn synthesize_pixel(&self, x: u16, y: u16) -> Option<[u8; 3]> {
        // Find region containing this pixel
        let region = self.regions.iter().find(|r| r.contains(x, y))?;

        // Local coordinates within region
        let local_x = x - region.x;
        let local_y = y - region.y;

        // Synthesize color
        Some(self.synthesize_region_pixel(region, local_x, local_y))
    }

    /// Synthesize a pixel within a region
    pub fn synthesize_region_pixel(&self, region: &Region, local_x: u16, local_y: u16) -> [u8; 3] {
        // Convert to fixed-point coordinates
        let x = Fixed::from(local_x);
        let y = Fixed::from(local_y);

        // Generate noise value based on type
        let noise_val = match region.noise_type {
            NoiseType::Fbm => {
                let noise = PpfNoise::new(region.noise_params());
                noise.fbm(x, y)
            }
            NoiseType::Turbulence => {
                let noise = PpfNoise::new(region.noise_params());
                noise.turbulence(x, y)
            }
            NoiseType::Ridged => {
                let noise = PpfNoise::new(region.noise_params());
                noise.ridged(x, y)
            }
            NoiseType::Warped => {
                let noise = PpfNoise::new(region.noise_params());
                let warp_strength = Fixed::from_int(2);
                noise.warped(x, y, warp_strength)
            }
            NoiseType::Cellular => {
                let noise = PpfNoise::new(region.noise_params());
                let cell_size = Fixed::from_int(10);
                noise.cellular(x, y, cell_size)
            }
            NoiseType::Perlin => {
                let perlin = PerlinNoise::new(region.seed);
                perlin.noise(x, y)
            }
        };

        // Convert noise to signed value centered at 0
        let noise_centered = noise_val - Fixed::HALF;

        // Scale by amplitude
        let amplitude = Fixed::from_f32(region.amplitude as f32 / 255.0);
        let noise_scaled = noise_centered * amplitude * Fixed::from_int(255);

        // Apply to base color
        let mut color = [0u8; 3];
        for i in 0..3 {
            let base = region.base_color[i] as i32;
            let modulated = base + noise_scaled.to_int();
            color[i] = modulated.clamp(0, 255) as u8;
        }

        color
    }

    /// Synthesize entire region to buffer
    pub fn synthesize_region(&self, region: &Region, buffer: &mut [[u8; 3]]) -> Result<()> {
        if buffer.len() != (region.w as usize * region.h as usize) {
            return Err(IffError::Other(
                "Buffer size doesn't match region dimensions".to_string(),
            ));
        }

        for y in 0..region.h {
            for x in 0..region.w {
                let idx = (y as usize * region.w as usize) + x as usize;
                buffer[idx] = self.synthesize_region_pixel(region, x, y);
            }
        }

        Ok(())
    }
}

impl Default for TextureSynthesizer {
    fn default() -> Self {
        Self::new()
    }
}

/// Texture analyzer for finding optimal synthesis parameters
#[cfg(feature = "encoder")]
pub struct TextureAnalyzer {
    /// Similarity threshold for region detection (0.0-1.0)
    similarity_threshold: f32,
}

#[cfg(feature = "encoder")]
impl TextureAnalyzer {
    /// Create a new texture analyzer
    pub fn new(similarity_threshold: f32) -> Self {
        TextureAnalyzer {
            similarity_threshold,
        }
    }

    /// Detect high-entropy regions suitable for synthesis
    pub fn detect_texture_regions(
        &self,
        image: &[[u8; 3]],
        width: usize,
        height: usize,
        min_size: usize,
    ) -> Vec<Region> {
        let mut regions = Vec::new();

        // Simple grid-based region detection
        let region_size = min_size.max(32);

        for y in (0..height).step_by(region_size) {
            for x in (0..width).step_by(region_size) {
                let w = (region_size).min(width - x);
                let h = (region_size).min(height - y);

                if w < min_size || h < min_size {
                    continue;
                }

                // Calculate entropy of region
                let entropy = self.calculate_entropy(image, x, y, w, h, width);

                log::debug!("Region ({}, {}) entropy: {}", x, y, entropy);

                // High entropy regions are good candidates for synthesis
                // Use the similarity threshold from the analyzer
                if entropy > self.similarity_threshold {
                    let region = Region::new(x as u16, y as u16, w as u16, h as u16);
                    regions.push(region);
                }
            }
        }

        regions
    }

    /// Calculate entropy of a region (0.0 = uniform, 1.0 = maximum entropy)
    fn calculate_entropy(
        &self,
        image: &[[u8; 3]],
        x: usize,
        y: usize,
        w: usize,
        h: usize,
        stride: usize,
    ) -> f32 {
        // Calculate variance as proxy for entropy
        let mut sum = [0f32; 3];
        let mut sum_sq = [0f32; 3];
        let mut count = 0;

        for dy in 0..h {
            for dx in 0..w {
                let idx = (y + dy) * stride + (x + dx);
                if idx < image.len() {
                    let pixel = image[idx];
                    for c in 0..3 {
                        let val = pixel[c] as f32;
                        sum[c] += val;
                        sum_sq[c] += val * val;
                    }
                    count += 1;
                }
            }
        }

        if count == 0 {
            return 0.0;
        }

        // Calculate average variance across channels
        let count_f = count as f32;
        let mut total_variance = 0.0;

        for c in 0..3 {
            let mean = sum[c] / count_f;
            let variance = (sum_sq[c] / count_f) - (mean * mean);
            total_variance += variance;
        }

        // Normalize to [0, 1]
        (total_variance / (3.0 * 255.0 * 255.0)).min(1.0)
    }

    /// Find optimal synthesis parameters for a region
    pub fn optimize_region(
        &self,
        image: &[[u8; 3]],
        region: &mut Region,
        stride: usize,
        max_iterations: usize,
        error_threshold: f32,
    ) -> Result<f32> {
        let mut best_seed = 0u32;
        let mut best_error = f32::MAX;

        // Extract region pixels
        let region_pixels = self.extract_region(image, region, stride)?;

        // Calculate base color (average)
        let base_color = self.calculate_base_color(&region_pixels);
        region.base_color = base_color;

        // Try different seeds
        for iteration in 0..max_iterations {
            let seed = iteration as u32 * 12345; // Pseudo-random seed generation
            region.seed = seed;

            // Synthesize with this seed
            let synthesizer = TextureSynthesizer::new();
            let mut synth_buffer = vec![[0u8; 3]; region_pixels.len()];
            synthesizer.synthesize_region(region, &mut synth_buffer)?;

            // Calculate error
            let error = self.calculate_l2_error(&region_pixels, &synth_buffer);

            if error < best_error {
                best_error = error;
                best_seed = seed;
            }

            // Early exit if error is good enough
            if error < error_threshold {
                break;
            }
        }

        log::debug!("Region optimized: best_error = {}, threshold = {}", best_error, error_threshold);

        region.seed = best_seed;
        Ok(best_error)
    }

    /// Extract region pixels from image
    fn extract_region(&self, image: &[[u8; 3]], region: &Region, stride: usize) -> Result<Vec<[u8; 3]>> {
        let mut pixels = Vec::with_capacity((region.w as usize) * (region.h as usize));

        for y in 0..region.h {
            for x in 0..region.w {
                let img_x = region.x as usize + x as usize;
                let img_y = region.y as usize + y as usize;
                let idx = img_y * stride + img_x;

                if idx < image.len() {
                    pixels.push(image[idx]);
                } else {
                    pixels.push([0, 0, 0]);
                }
            }
        }

        Ok(pixels)
    }

    /// Calculate base color (average) of region
    fn calculate_base_color(&self, pixels: &[[u8; 3]]) -> [u8; 3] {
        let mut sum = [0u32; 3];

        for pixel in pixels {
            for c in 0..3 {
                sum[c] += pixel[c] as u32;
            }
        }

        let count = pixels.len() as u32;
        [
            (sum[0] / count) as u8,
            (sum[1] / count) as u8,
            (sum[2] / count) as u8,
        ]
    }

    /// Calculate L2 error between two buffers
    fn calculate_l2_error(&self, original: &[[u8; 3]], synthesized: &[[u8; 3]]) -> f32 {
        let mut sum_sq_error = 0.0;

        for (orig, synth) in original.iter().zip(synthesized.iter()) {
            for c in 0..3 {
                let diff = orig[c] as f32 - synth[c] as f32;
                sum_sq_error += diff * diff;
            }
        }

        (sum_sq_error / (original.len() as f32 * 3.0)).sqrt()
    }
}

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

    #[test]
    fn test_region_contains() {
        let region = Region::new(10, 20, 100, 50);

        assert!(region.contains(10, 20)); // Top-left corner
        assert!(region.contains(109, 69)); // Bottom-right corner
        assert!(region.contains(50, 40)); // Middle

        assert!(!region.contains(9, 20)); // Just outside left
        assert!(!region.contains(110, 40)); // Just outside right
        assert!(!region.contains(50, 19)); // Just outside top
        assert!(!region.contains(50, 70)); // Just outside bottom
    }

    #[test]
    fn test_noise_params() {
        let region = Region {
            chaos_level: 6,
            scale: 2,
            persistence: 128,
            ..Region::new(0, 0, 64, 64)
        };

        let params = region.noise_params();
        assert_eq!(params.octaves, 6);
        assert_eq!(params.scale, 2);
        assert!((params.persistence - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_synthesizer() {
        let mut synth = TextureSynthesizer::new();

        let region = Region {
            seed: 42,
            chaos_level: 4,
            base_color: [100, 150, 200],
            amplitude: 50,
            ..Region::new(0, 0, 64, 64)
        };

        synth.add_region(region);

        // Synthesize a pixel
        let pixel = synth.synthesize_pixel(10, 20);
        assert!(pixel.is_some());

        let color = pixel.unwrap();
        // Color should be modulated around base color
        assert!(color[0] > 50 && color[0] < 150);
        assert!(color[1] > 100 && color[1] < 200);
        assert!(color[2] > 150 && color[2] < 250);
    }

    #[test]
    fn test_synthesize_determinism() {
        let synth = TextureSynthesizer::new();

        let region = Region {
            seed: 123,
            ..Region::new(0, 0, 64, 64)
        };

        // Same pixel should give same result
        let color1 = synth.synthesize_region_pixel(&region, 10, 20);
        let color2 = synth.synthesize_region_pixel(&region, 10, 20);

        assert_eq!(color1, color2);
    }

    #[test]
    fn test_synthesize_region() {
        let synth = TextureSynthesizer::new();

        let region = Region::new(0, 0, 16, 16);
        let mut buffer = vec![[0u8; 3]; 16 * 16];

        let result = synth.synthesize_region(&region, &mut buffer);
        assert!(result.is_ok());

        // Buffer should be filled
        assert!(buffer.iter().any(|&pixel| pixel != [0, 0, 0]));
    }

    #[cfg(feature = "encoder")]
    #[test]
    fn test_texture_analyzer() {
        let analyzer = TextureAnalyzer::new(0.05); // Very low threshold for test

        // Create a test image with high entropy
        let width = 64;
        let height = 64;
        let mut image = vec![[0u8; 3]; width * height];

        // Create actual high-variance noise using multiple prime multipliers
        for y in 0..height {
            for x in 0..width {
                let idx = y * width + x;
                // Use larger primes and XOR for better distribution
                let r = ((x * 2654435761u32 as usize + y * 2246822519u32 as usize) ^ (x * y)) % 256;
                let g = ((x * 3266489917u32 as usize + y * 668265263u32 as usize) ^ (x + y)) % 256;
                let b = ((x * 374761393u32 as usize + y * 1935289041u32 as usize) ^ (x | y)) % 256;
                image[idx] = [r as u8, g as u8, b as u8];
            }
        }

        let regions = analyzer.detect_texture_regions(&image, width, height, 16);

        // Should detect at least one region with high-variance content
        assert!(!regions.is_empty(), "Expected to detect texture regions");
    }

    #[test]
    fn test_different_noise_types() {
        let synth = TextureSynthesizer::new();

        let noise_types = [
            NoiseType::Fbm,
            NoiseType::Turbulence,
            NoiseType::Ridged,
            NoiseType::Warped,
            NoiseType::Cellular,
            NoiseType::Perlin,
        ];

        for noise_type in &noise_types {
            let region = Region {
                noise_type: *noise_type,
                seed: 42,
                ..Region::new(0, 0, 64, 64)
            };

            let color = synth.synthesize_region_pixel(&region, 10, 20);

            // Should produce valid color
            assert!(color[0] <= 255);
            assert!(color[1] <= 255);
            assert!(color[2] <= 255);
        }
    }
}