plasma-prp 0.1.0

Read, write, inspect, and manipulate Plasma engine PRP files used by Myst Online: Uru Live
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! PyO3 Python bindings for plasma-prp.
//!
//! Exposes PRP, age, SDL, and FNI file parsing to Python via `pip install plasma-prp`.

use pyo3::prelude::*;
use pyo3::exceptions::{PyIOError, PyValueError};
use std::path::Path;
use std::collections::HashMap;

use crate::resource::prp::{self, PlasmaRead};
use crate::core::class_index::ClassIndex;

// ============================================================================
// PrpFile — load, save, iterate objects
// ============================================================================

/// A loaded .prp (Plasma Resource Page) file.
#[pyclass]
#[derive(Clone)]
pub struct PrpFile {
    inner: std::sync::Arc<prp::PrpPage>,
}

#[pymethods]
impl PrpFile {
    /// Load a PRP file from disk.
    #[staticmethod]
    fn load(path: &str) -> PyResult<Self> {
        let page = prp::PrpPage::from_file(Path::new(path))
            .map_err(|e| PyIOError::new_err(format!("{}", e)))?;
        Ok(Self { inner: std::sync::Arc::new(page) })
    }

    /// Load a PRP file from bytes.
    #[staticmethod]
    fn from_bytes(data: &[u8]) -> PyResult<Self> {
        let page = prp::PrpPage::from_bytes(data.to_vec())
            .map_err(|e| PyIOError::new_err(format!("{}", e)))?;
        Ok(Self { inner: std::sync::Arc::new(page) })
    }

    /// Save the PRP file to disk (byte-identical round-trip).
    fn save(&self, path: &str) -> PyResult<()> {
        self.inner.save(Path::new(path))
            .map_err(|e| PyIOError::new_err(format!("{}", e)))
    }

    /// Serialize to bytes.
    fn to_bytes(&self) -> PyResult<Vec<u8>> {
        self.inner.to_bytes()
            .map_err(|e| PyIOError::new_err(format!("{}", e)))
    }

    /// Age name from the page header.
    #[getter]
    fn age_name(&self) -> &str {
        &self.inner.header.age_name
    }

    /// Page name from the page header.
    #[getter]
    fn page_name(&self) -> &str {
        &self.inner.header.page_name
    }

    /// Number of objects in the page.
    fn __len__(&self) -> usize {
        self.inner.keys.len()
    }

    /// Iterate over all objects.
    fn __iter__(&self) -> PyResult<ObjectIterator> {
        Ok(ObjectIterator {
            page: self.inner.clone(),
            index: 0,
        })
    }

    /// Get all objects as a list.
    fn objects(&self) -> Vec<PrpObject> {
        self.inner.keys.iter().map(|k| PrpObject {
            key: k.clone(),
            page: self.inner.clone(),
        }).collect()
    }

    /// Get objects by class type ID.
    fn objects_of_type(&self, class_type: u16) -> Vec<PrpObject> {
        self.inner.keys.iter()
            .filter(|k| k.class_type == class_type)
            .map(|k| PrpObject {
                key: k.clone(),
                page: self.inner.clone(),
            })
            .collect()
    }

    /// Get objects by class type name (e.g., "plSceneObject", "plDrawableSpans").
    fn objects_by_name(&self, class_name: &str) -> Vec<PrpObject> {
        self.inner.keys.iter()
            .filter(|k| ClassIndex::class_name(k.class_type) == class_name)
            .map(|k| PrpObject {
                key: k.clone(),
                page: self.inner.clone(),
            })
            .collect()
    }

    /// Count objects by class type.
    fn count_by_type(&self) -> HashMap<String, usize> {
        let mut counts: HashMap<String, usize> = HashMap::new();
        for key in &self.inner.keys {
            let name = ClassIndex::class_name(key.class_type).to_string();
            *counts.entry(name).or_insert(0) += 1;
        }
        counts
    }

    /// Get the page header info.
    #[getter]
    fn header(&self) -> PageHeaderInfo {
        PageHeaderInfo {
            version: self.inner.header.version,
            sequence_number: self.inner.header.sequence_number,
            flags: self.inner.header.flags,
            age_name: self.inner.header.age_name.clone(),
            page_name: self.inner.header.page_name.clone(),
            major_version: self.inner.header.major_version,
            checksum: self.inner.header.checksum,
            data_start: self.inner.header.data_start,
            index_start: self.inner.header.index_start,
        }
    }

    fn __repr__(&self) -> String {
        format!("PrpFile('{}', '{}', {} objects)",
            self.inner.header.age_name,
            self.inner.header.page_name,
            self.inner.keys.len())
    }
}

#[pyclass]
struct ObjectIterator {
    page: std::sync::Arc<prp::PrpPage>,
    index: usize,
}

#[pymethods]
impl ObjectIterator {
    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { slf }
    fn __next__(&mut self) -> Option<PrpObject> {
        if self.index >= self.page.keys.len() {
            return None;
        }
        let key = self.page.keys[self.index].clone();
        self.index += 1;
        Some(PrpObject { key, page: self.page.clone() })
    }
}

// ============================================================================
// PrpObject — a single keyed object in a PRP page
// ============================================================================

/// A single object in a PRP file.
#[pyclass]
#[derive(Clone)]
pub struct PrpObject {
    key: prp::ObjectKey,
    page: std::sync::Arc<prp::PrpPage>,
}

#[pymethods]
impl PrpObject {
    /// Object name.
    #[getter]
    fn name(&self) -> &str {
        &self.key.object_name
    }

    /// Class type ID.
    #[getter]
    fn class_type(&self) -> u16 {
        self.key.class_type
    }

    /// Human-readable class type name.
    #[getter]
    fn class_name(&self) -> &str {
        ClassIndex::class_name(self.key.class_type)
    }

    /// Object ID.
    #[getter]
    fn object_id(&self) -> u32 {
        self.key.object_id
    }

    /// Location sequence number.
    #[getter]
    fn location_sequence(&self) -> u32 {
        self.key.location_sequence
    }

    /// Raw object data as bytes.
    #[getter]
    fn data(&self) -> Option<Vec<u8>> {
        self.page.object_data(&self.key).map(|d| d.to_vec())
    }

    /// Data length in bytes.
    #[getter]
    fn data_len(&self) -> u32 {
        self.key.data_len
    }

    /// Parse as a SceneObject (if class_type matches).
    fn as_scene_object(&self) -> PyResult<SceneObject> {
        if self.key.class_type != 0x0001 {
            return Err(PyValueError::new_err(format!(
                "Not a plSceneObject (class 0x{:04X})", self.key.class_type)));
        }
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        SceneObject::parse(data)
    }

    /// Parse as a Mipmap texture.
    fn as_mipmap(&self) -> PyResult<Mipmap> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        Mipmap::parse(data)
    }

    /// Parse as a Material (hsGMaterial).
    fn as_material(&self) -> PyResult<Material> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        Material::parse(data)
    }

    /// Parse as a Layer (plLayer).
    fn as_layer(&self) -> PyResult<Layer> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        Layer::parse(data)
    }

    /// Parse as a PythonFileMod.
    fn as_python_file_mod(&self) -> PyResult<PythonFileMod> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        PythonFileMod::parse(data)
    }

    /// Parse as a ResponderModifier.
    fn as_responder(&self) -> PyResult<ResponderMod> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        ResponderMod::parse(data)
    }

    /// Parse as a plPXPhysical.
    fn as_physical(&self) -> PyResult<PhysicalData> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        PhysicalData::parse(data)
    }

    /// Parse as a plWin32Sound.
    fn as_sound(&self) -> PyResult<SoundInfo> {
        let data = self.page.object_data(&self.key)
            .ok_or_else(|| PyIOError::new_err("Object data not found"))?;
        SoundInfo::parse(data)
    }

    fn __repr__(&self) -> String {
        format!("PrpObject('{}', class=0x{:04X}/{})",
            self.key.object_name, self.key.class_type,
            ClassIndex::class_name(self.key.class_type))
    }
}

// ============================================================================
// PageHeaderInfo
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct PageHeaderInfo {
    #[pyo3(get)] pub version: u32,
    #[pyo3(get)] pub sequence_number: u32,
    #[pyo3(get)] pub flags: u16,
    #[pyo3(get)] pub age_name: String,
    #[pyo3(get)] pub page_name: String,
    #[pyo3(get)] pub major_version: u16,
    #[pyo3(get)] pub checksum: u32,
    #[pyo3(get)] pub data_start: u32,
    #[pyo3(get)] pub index_start: u32,
}

#[pymethods]
impl PageHeaderInfo {
    fn __repr__(&self) -> String {
        format!("PageHeader(age='{}', page='{}', v{})",
            self.age_name, self.page_name, self.version)
    }
}

// ============================================================================
// SceneObject
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct SceneObject {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub draw_interface_names: Vec<String>,
    #[pyo3(get)] pub coord_interface_name: Option<String>,
    #[pyo3(get)] pub modifier_names: Vec<String>,
}

impl SceneObject {
    fn parse(data: &[u8]) -> PyResult<Self> {
        use crate::core::scene_object::SceneObjectData;
        let mut cursor = std::io::Cursor::new(data);
        let _class_idx = cursor.read_i16().map_err(|e| PyValueError::new_err(format!("{}", e)))?;

        let so = SceneObjectData::read(&mut cursor)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;

        let name = so.self_key.as_ref().map(|u| u.object_name.clone()).unwrap_or_default();

        Ok(Self {
            name,
            draw_interface_names: so.draw_interface
                .iter().map(|u| u.object_name.clone()).collect(),
            coord_interface_name: so.coord_interface
                .as_ref().map(|u| u.object_name.clone()),
            modifier_names: so.modifiers.iter()
                .filter_map(|u| u.as_ref().map(|k| k.object_name.clone())).collect(),
        })
    }
}

#[pymethods]
impl SceneObject {
    fn __repr__(&self) -> String {
        format!("SceneObject('{}', {} drawables, {} modifiers)",
            self.name, self.draw_interface_names.len(), self.modifier_names.len())
    }
}

// ============================================================================
// Mipmap
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct Mipmap {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub width: u32,
    #[pyo3(get)] pub height: u32,
    #[pyo3(get)] pub num_levels: u8,
    #[pyo3(get)] pub compression_type: u8,
    #[pyo3(get)] pub dxt_type: u8,
    #[pyo3(get)] pub total_size: u32,
    /// Raw pixel data for all mip levels.
    pixel_data: Vec<u8>,
}

impl Mipmap {
    fn parse(data: &[u8]) -> PyResult<Self> {
        use crate::core::uoid::read_key_uoid;
        let mut cursor = std::io::Cursor::new(data);
        // hsKeyedObject prologue: class_idx + self_key
        let _class_idx = cursor.read_i16().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let self_key = read_key_uoid(&mut cursor)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let name = self_key.as_ref().map(|u| u.object_name.clone()).unwrap_or_default();
        // plBitmap + plMipmap body uses read_mipmap_from_cursor, but it's private.
        // Re-parse from the full data using from_cubic_envmap_data workaround is wrong.
        // Instead, just read bitmap + mipmap fields inline.
        let version = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        if version != 2 {
            return Err(PyValueError::new_err(format!("Unsupported bitmap version: {}", version)));
        }
        let _pixel_size = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let _space = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let _flags = cursor.read_u16().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let compression_type = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let (dxt_type, _block_size) = match compression_type {
            0 | 2 | 3 => { (cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?, 0u8) }
            1 => {
                let bs = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
                let ct = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
                (ct, bs)
            }
            _ => { return Err(PyValueError::new_err(format!("Unknown compression: {}", compression_type))); }
        };
        // Skip timestamps (8 bytes)
        let mut _skip = [0u8; 8];
        std::io::Read::read_exact(&mut cursor, &mut _skip)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        // plMipmap data
        let width = cursor.read_u32().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let height = cursor.read_u32().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let _row_bytes = cursor.read_u32().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let total_size = cursor.read_u32().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let num_levels = cursor.read_u8().map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let pos = cursor.position() as usize;
        let remaining = data.len().saturating_sub(pos);
        let read_size = (total_size as usize).min(remaining);
        let pixel_data = data[pos..pos + read_size].to_vec();

        Ok(Self {
            name,
            width,
            height,
            num_levels,
            compression_type,
            dxt_type,
            total_size,
            pixel_data,
        })
    }
}

#[pymethods]
impl Mipmap {
    #[getter]
    fn pixel_data(&self) -> &[u8] {
        &self.pixel_data
    }

    fn __repr__(&self) -> String {
        format!("Mipmap('{}', {}x{}, {} levels, {} bytes)",
            self.name, self.width, self.height, self.num_levels, self.total_size)
    }
}

// ============================================================================
// Material
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct Material {
    #[pyo3(get)] pub layer_names: Vec<String>,
}

impl Material {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let names = prp::parse_material_layers(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        Ok(Self { layer_names: names })
    }
}

#[pymethods]
impl Material {
    fn __repr__(&self) -> String {
        format!("Material({} layers: {:?})", self.layer_names.len(), self.layer_names)
    }
}

// ============================================================================
// Layer
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct Layer {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub texture_name: Option<String>,
    #[pyo3(get)] pub blend_flags: u32,
    #[pyo3(get)] pub shade_flags: u32,
    #[pyo3(get)] pub misc_flags: u32,
    #[pyo3(get)] pub z_flags: u32,
    #[pyo3(get)] pub uv_channel: u8,
    #[pyo3(get)] pub opacity: f32,
    #[pyo3(get)] pub preshade_color: [f32; 4],
    #[pyo3(get)] pub runtime_color: [f32; 4],
    #[pyo3(get)] pub ambient_color: [f32; 4],
    #[pyo3(get)] pub specular_color: [f32; 4],
}

impl Layer {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let ls = prp::parse_layer_state(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        Ok(Self {
            name: ls.name,
            texture_name: ls.texture_name,
            blend_flags: ls.blend_flags,
            shade_flags: ls.shade_flags,
            misc_flags: ls.misc_flags,
            z_flags: ls.z_flags,
            uv_channel: ls.uv_channel,
            opacity: ls.opacity,
            preshade_color: ls.preshade_color,
            runtime_color: ls.runtime_color,
            ambient_color: ls.ambient_color,
            specular_color: ls.specular_color,
        })
    }
}

#[pymethods]
impl Layer {
    fn __repr__(&self) -> String {
        format!("Layer('{}', texture={:?}, opacity={:.2})",
            self.name, self.texture_name, self.opacity)
    }
}

// ============================================================================
// PythonFileMod
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct PythonFileMod {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub python_file: String,
    #[pyo3(get)] pub receiver_names: Vec<String>,
    #[pyo3(get)] pub params: Vec<PythonParam>,
}

#[pyclass]
#[derive(Clone)]
pub struct PythonParam {
    #[pyo3(get)] pub id: u32,
    #[pyo3(get)] pub param_type: String,
    #[pyo3(get)] pub value: String,
}

impl PythonFileMod {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let pfm = prp::parse_python_file_mod(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let name = pfm.self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
        Ok(Self {
            name,
            python_file: pfm.script_file,
            receiver_names: pfm.receivers.iter().map(|u| u.object_name.clone()).collect(),
            params: pfm.parameters.iter().map(|p| PythonParam {
                id: p.id as u32,
                param_type: format!("{:?}", p.value),
                value: match &p.value {
                    prp::PythonParamValue::Int(v) => v.to_string(),
                    prp::PythonParamValue::Float(v) => v.to_string(),
                    prp::PythonParamValue::Bool(v) => v.to_string(),
                    prp::PythonParamValue::String(v) => v.clone(),
                    prp::PythonParamValue::Key(v) => v.as_ref()
                        .map(|u| u.object_name.clone())
                        .unwrap_or_else(|| "None".to_string()),
                    prp::PythonParamValue::None => "None".to_string(),
                },
            }).collect(),
        })
    }
}

#[pymethods]
impl PythonFileMod {
    fn __repr__(&self) -> String {
        format!("PythonFileMod('{}', file='{}', {} params)",
            self.name, self.python_file, self.params.len())
    }
}

#[pymethods]
impl PythonParam {
    fn __repr__(&self) -> String {
        format!("PythonParam(id={}, {}={})", self.id, self.param_type, self.value)
    }
}

// ============================================================================
// ResponderMod
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct ResponderMod {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub num_states: usize,
    #[pyo3(get)] pub cur_state: u8,
    #[pyo3(get)] pub enabled: bool,
}

impl ResponderMod {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let r = prp::parse_responder_modifier(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        let name = r.self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
        Ok(Self {
            name,
            num_states: r.states.len(),
            cur_state: r.cur_state,
            enabled: r.enabled,
        })
    }
}

#[pymethods]
impl ResponderMod {
    fn __repr__(&self) -> String {
        format!("ResponderMod('{}', {} states, enabled={})",
            self.name, self.num_states, self.enabled)
    }
}

// ============================================================================
// PhysicalData
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct PhysicalData {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub mass: f32,
    #[pyo3(get)] pub friction: f32,
    #[pyo3(get)] pub restitution: f32,
    #[pyo3(get)] pub group: String,
    #[pyo3(get)] pub bounds_type: String,
    #[pyo3(get)] pub num_verts: usize,
    #[pyo3(get)] pub num_faces: usize,
}

impl PhysicalData {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let p = prp::parse_px_physical(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        Ok(Self {
            name: p.name,
            mass: p.mass,
            friction: p.friction,
            restitution: p.restitution,
            group: format!("{:?}", p.group),
            bounds_type: format!("{:?}", p.bounds),
            num_verts: match &p.shape {
                prp::PhysShapeData::TriMesh { vertices, .. } => vertices.len(),
                prp::PhysShapeData::Hull { vertices, .. } => vertices.len(),
                _ => 0,
            },
            num_faces: match &p.shape {
                prp::PhysShapeData::TriMesh { indices, .. } => indices.len() / 3,
                _ => 0,
            },
        })
    }
}

#[pymethods]
impl PhysicalData {
    fn __repr__(&self) -> String {
        format!("PhysicalData('{}', mass={:.1}, group={}, bounds={}, {} verts)",
            self.name, self.mass, self.group, self.bounds_type, self.num_verts)
    }
}

// ============================================================================
// SoundInfo
// ============================================================================

#[pyclass]
#[derive(Clone)]
pub struct SoundInfo {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub sound_file: String,
    #[pyo3(get)] pub volume: f32,
    #[pyo3(get)] pub is_3d: bool,
    #[pyo3(get)] pub auto_start: bool,
    #[pyo3(get)] pub looping: bool,
    #[pyo3(get)] pub min_distance: f32,
    #[pyo3(get)] pub max_distance: f32,
}

impl SoundInfo {
    fn parse(data: &[u8]) -> PyResult<Self> {
        let s = prp::parse_win32_sound(data)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        Ok(Self {
            name: s.name,
            sound_file: s.buffer_name.unwrap_or_default(),
            volume: s.volume,
            is_3d: s.is_3d,
            auto_start: s.auto_start,
            looping: s.looping,
            min_distance: s.min_falloff,
            max_distance: s.max_falloff,
        })
    }
}

#[pymethods]
impl SoundInfo {
    fn __repr__(&self) -> String {
        format!("SoundInfo('{}', file='{}', vol={:.2}, 3d={})",
            self.name, self.sound_file, self.volume, self.is_3d)
    }
}

// ============================================================================
// AgeDescription
// ============================================================================

/// Parsed .age file.
#[pyclass]
#[derive(Clone)]
pub struct AgeFile {
    #[pyo3(get)] pub age_name: String,
    #[pyo3(get)] pub sequence_prefix: i32,
    #[pyo3(get)] pub max_capacity: i32,
    #[pyo3(get)] pub day_length: f32,
    #[pyo3(get)] pub pages: Vec<PageEntry>,
}

#[pyclass]
#[derive(Clone)]
pub struct PageEntry {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub seq_suffix: u32,
    #[pyo3(get)] pub flags: u8,
    #[pyo3(get)] pub auto_load: bool,
}

#[pymethods]
impl AgeFile {
    /// Load an .age file from disk.
    #[staticmethod]
    fn load(path: &str) -> PyResult<Self> {
        let desc = crate::age::description::AgeDescription::from_file(Path::new(path))
            .map_err(|e| PyIOError::new_err(format!("{}", e)))?;
        Ok(Self::from_desc(desc))
    }

    /// Parse .age content string.
    #[staticmethod]
    fn parse(age_name: &str, content: &str) -> PyResult<Self> {
        let desc = crate::age::description::AgeDescription::parse(age_name, content)
            .map_err(|e| PyValueError::new_err(format!("{}", e)))?;
        Ok(Self::from_desc(desc))
    }

    /// Get the .prp filename for a page.
    fn prp_filename(&self, page_name: &str) -> Option<String> {
        self.pages.iter()
            .find(|p| p.name == page_name)
            .map(|_| format!("{}_District_{}.prp", self.age_name, page_name))
    }

    fn __repr__(&self) -> String {
        format!("AgeFile('{}', {} pages, prefix={})",
            self.age_name, self.pages.len(), self.sequence_prefix)
    }
}

impl AgeFile {
    fn from_desc(desc: crate::age::description::AgeDescription) -> Self {
        Self {
            pages: desc.pages.iter().map(|p| PageEntry {
                name: p.name.clone(),
                seq_suffix: p.seq_suffix,
                flags: p.flags,
                auto_load: p.auto_load(),
            }).collect(),
            age_name: desc.age_name,
            sequence_prefix: desc.sequence_prefix,
            max_capacity: desc.max_capacity,
            day_length: desc.day_length,
        }
    }
}

#[pymethods]
impl PageEntry {
    fn __repr__(&self) -> String {
        format!("PageEntry('{}', seq={}, auto_load={})",
            self.name, self.seq_suffix, self.auto_load)
    }
}

// ============================================================================
// SDL
// ============================================================================

/// SDL state descriptor manager.
#[pyclass]
pub struct SdlFile {
    inner: crate::sdl::SdlManager,
}

#[pymethods]
impl SdlFile {
    /// Create a new empty SDL manager.
    #[new]
    fn new() -> Self {
        Self { inner: crate::sdl::SdlManager::new() }
    }

    /// Load all .sdl files from a directory.
    fn load_directory(&mut self, path: &str) -> PyResult<usize> {
        self.inner.load_directory(Path::new(path))
            .map_err(|e| PyIOError::new_err(format!("{}", e)))
    }

    /// Load a single .sdl file.
    fn load_file(&mut self, path: &str) -> PyResult<usize> {
        self.inner.load_file(Path::new(path))
            .map_err(|e| PyIOError::new_err(format!("{}", e)))
    }

    /// Find a descriptor by name. Returns None if not found.
    fn find(&self, name: &str, version: u32) -> Option<SdlDescriptor> {
        self.inner.find(name, version).map(|d| SdlDescriptor {
            name: d.name.clone(),
            version: d.version,
            variables: d.variables.iter().map(|v| SdlVariable {
                name: v.name.clone(),
                var_type: format!("{:?}", v.var_type),
                count: v.count,
                default_value: v.default_value.clone(),
            }).collect(),
        })
    }

    /// Total number of loaded descriptors.
    fn __len__(&self) -> usize {
        self.inner.descriptor_count()
    }

    fn __repr__(&self) -> String {
        format!("SdlFile({} descriptors)", self.inner.descriptor_count())
    }
}

#[pyclass]
#[derive(Clone)]
pub struct SdlDescriptor {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub version: u32,
    #[pyo3(get)] pub variables: Vec<SdlVariable>,
}

#[pymethods]
impl SdlDescriptor {
    fn __repr__(&self) -> String {
        format!("SdlDescriptor('{}', v{}, {} vars)",
            self.name, self.version, self.variables.len())
    }
}

#[pyclass]
#[derive(Clone)]
pub struct SdlVariable {
    #[pyo3(get)] pub name: String,
    #[pyo3(get)] pub var_type: String,
    #[pyo3(get)] pub count: usize,
    #[pyo3(get)] pub default_value: Option<String>,
}

#[pymethods]
impl SdlVariable {
    fn __repr__(&self) -> String {
        format!("SdlVariable('{}', type={}, count={}, default={:?})",
            self.name, self.var_type, self.count, self.default_value)
    }
}

// ============================================================================
// ClassIndex — lookup class names
// ============================================================================

/// Lookup class type names by ID.
#[pyfunction]
fn class_name(class_type: u16) -> &'static str {
    ClassIndex::class_name(class_type)
}

// ============================================================================
// Module registration
// ============================================================================

/// plasma_prp Python module.
#[pymodule]
fn plasma_prp(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PrpFile>()?;
    m.add_class::<PrpObject>()?;
    m.add_class::<PageHeaderInfo>()?;
    m.add_class::<SceneObject>()?;
    m.add_class::<Mipmap>()?;
    m.add_class::<Material>()?;
    m.add_class::<Layer>()?;
    m.add_class::<PythonFileMod>()?;
    m.add_class::<PythonParam>()?;
    m.add_class::<ResponderMod>()?;
    m.add_class::<PhysicalData>()?;
    m.add_class::<SoundInfo>()?;
    m.add_class::<AgeFile>()?;
    m.add_class::<PageEntry>()?;
    m.add_class::<SdlFile>()?;
    m.add_class::<SdlDescriptor>()?;
    m.add_class::<SdlVariable>()?;
    m.add_function(wrap_pyfunction!(class_name, m)?)?;
    Ok(())
}