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
//! plSceneObject and its interfaces — the central game object type.
//!
//! A plSceneObject holds optional references to:
//!   - plDrawInterface (rendering)
//!   - plCoordinateInterface (transform hierarchy)
//!   - plSimulationInterface (physics)
//!   - plAudioInterface (sound)
//!   - Generic interfaces (arbitrary)
//!   - Modifiers (behavior)
//!   - Scene node (page grouping)
//!
//! C++ ref: pnSceneObject/plSceneObject.h/.cpp,
//!          plCoordinateInterface.h/.cpp, plDrawInterface.h/.cpp

use std::io::Read;

use anyhow::Result;

use crate::resource::prp::PlasmaRead;

use super::bit_vector::BitVector;
use super::synched_object::SynchedObjectData;
use super::uoid::{Uoid, read_key_uoid};

/// Parsed plObjInterface base data.
#[derive(Debug, Clone, Default)]
pub struct ObjInterfaceData {
    /// Self-key Uoid (from hsKeyedObject::Read).
    pub self_key: Option<Uoid>,
    /// Synched object data.
    pub synched: SynchedObjectData,
    /// Owner scene object key.
    pub owner: Option<Uoid>,
    /// Interface properties.
    pub props: BitVector,
}

impl ObjInterfaceData {
    /// Read the plObjInterface portion from a stream.
    /// Reads: [creatable_class_index] [self_key] [synched_object] [owner_key] [props_bitvector]
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        // Note: the creatable class index (i16) is read by the caller before this
        let self_key = read_key_uoid(reader)?;
        let synched = SynchedObjectData::read(reader)?;
        let owner = read_key_uoid(reader)?;
        let props = BitVector::read(reader)?;

        Ok(Self {
            self_key,
            synched,
            owner,
            props,
        })
    }
}

/// Parsed plCoordinateInterface data.
#[derive(Debug, Clone)]
pub struct CoordinateInterfaceData {
    pub base: ObjInterfaceData,
    pub local_to_parent: [f32; 16],
    pub parent_to_local: [f32; 16],
    pub local_to_world: [f32; 16],
    pub world_to_local: [f32; 16],
    pub children: Vec<Option<Uoid>>,
}

impl CoordinateInterfaceData {
    /// Read a plCoordinateInterface from the stream.
    /// Format: [ObjInterface] [L2P matrix] [P2L matrix] [L2W matrix] [W2L matrix] [child_count] [child_keys...]
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        let base = ObjInterfaceData::read(reader)?;

        let local_to_parent = read_matrix44(reader)?;
        let parent_to_local = read_matrix44(reader)?;
        let local_to_world = read_matrix44(reader)?;
        let world_to_local = read_matrix44(reader)?;

        let num_children = reader.read_u32()?;
        let mut children = Vec::with_capacity(num_children as usize);
        for _ in 0..num_children {
            children.push(read_key_uoid(reader)?);
        }

        Ok(Self {
            base,
            local_to_parent,
            parent_to_local,
            local_to_world,
            world_to_local,
            children,
        })
    }
}

/// Parsed plDrawInterface data.
#[derive(Debug, Clone)]
pub struct DrawInterfaceData {
    pub base: ObjInterfaceData,
    /// (drawable_index, drawable_key) pairs.
    pub drawables: Vec<(u32, Option<Uoid>)>,
    /// Visibility region keys.
    pub regions: Vec<Option<Uoid>>,
}

impl DrawInterfaceData {
    /// Read a plDrawInterface from the stream.
    /// Format: [ObjInterface] [n_drawables] [foreach: index + key] [n_regions] [foreach: key]
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        let base = ObjInterfaceData::read(reader)?;

        let num_drawables = reader.read_u32()?;
        let mut drawables = Vec::with_capacity(num_drawables as usize);
        for _ in 0..num_drawables {
            let index = reader.read_u32()?;
            let key = read_key_uoid(reader)?;
            drawables.push((index, key));
        }

        let num_regions = reader.read_u32()?;
        let mut regions = Vec::with_capacity(num_regions as usize);
        for _ in 0..num_regions {
            regions.push(read_key_uoid(reader)?);
        }

        Ok(Self {
            base,
            drawables,
            regions,
        })
    }
}

/// Parsed plSimulationInterface data (just the ObjInterface base for now).
#[derive(Debug, Clone, Default)]
pub struct SimulationInterfaceData {
    pub base: ObjInterfaceData,
    pub physical_key: Option<Uoid>,
}

impl SimulationInterfaceData {
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        let base = ObjInterfaceData::read(reader)?;
        // plSimulationInterface reads one key: the plPhysical
        let physical_key = read_key_uoid(reader)?;
        Ok(Self {
            base,
            physical_key,
        })
    }
}

/// Parsed plAudioInterface data.
#[derive(Debug, Clone, Default)]
pub struct AudioInterfaceData {
    pub base: ObjInterfaceData,
    pub audible_key: Option<Uoid>,
}

impl AudioInterfaceData {
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        let base = ObjInterfaceData::read(reader)?;
        // plAudioInterface reads one key: the plAudible
        let audible_key = read_key_uoid(reader)?;
        Ok(Self {
            base,
            audible_key,
        })
    }
}

/// Parsed plSceneObject data.
#[derive(Debug, Clone)]
pub struct SceneObjectData {
    /// Self-key Uoid.
    pub self_key: Option<Uoid>,
    /// Synched object data.
    pub synched: SynchedObjectData,
    /// Draw interface key (optional).
    pub draw_interface: Option<Uoid>,
    /// Simulation interface key (optional).
    pub sim_interface: Option<Uoid>,
    /// Coordinate interface key (optional).
    pub coord_interface: Option<Uoid>,
    /// Audio interface key (optional).
    pub audio_interface: Option<Uoid>,
    /// Generic interface keys.
    pub generics: Vec<Option<Uoid>>,
    /// Modifier keys.
    pub modifiers: Vec<Option<Uoid>>,
    /// Scene node key.
    pub scene_node: Option<Uoid>,
}

impl SceneObjectData {
    /// Read a plSceneObject from the stream.
    ///
    /// Format:
    ///   [creatable_class_idx (i16)] [self_key] [synched_object]
    ///   [draw_iface_key] [sim_iface_key] [coord_iface_key] [audio_iface_key]
    ///   [n_generics] [generic_keys...] [n_modifiers] [modifier_keys...] [scene_node_key]
    pub fn read(reader: &mut impl Read) -> Result<Self> {
        // Creatable class index already read by caller (part of "read creatable" dispatch)
        // hsKeyedObject::Read — self-key
        let self_key = read_key_uoid(reader)?;

        // plSynchedObject::Read
        let synched = SynchedObjectData::read(reader)?;

        // plSceneObject::Read — interface keys
        let draw_interface = read_key_uoid(reader)?;
        let sim_interface = read_key_uoid(reader)?;
        let coord_interface = read_key_uoid(reader)?;
        let audio_interface = read_key_uoid(reader)?;

        // Generic interfaces
        let num_generics = reader.read_u32()?;
        let mut generics = Vec::with_capacity(num_generics as usize);
        for _ in 0..num_generics {
            generics.push(read_key_uoid(reader)?);
        }

        // Modifiers
        let num_modifiers = reader.read_u32()?;
        let mut modifiers = Vec::with_capacity(num_modifiers as usize);
        for _ in 0..num_modifiers {
            modifiers.push(read_key_uoid(reader)?);
        }

        // Scene node
        let scene_node = read_key_uoid(reader)?;

        Ok(Self {
            self_key,
            synched,
            draw_interface,
            sim_interface,
            coord_interface,
            audio_interface,
            generics,
            modifiers,
            scene_node,
        })
    }
}

/// Read an hsMatrix44 from a stream.
/// Format: u8 flag (0 = identity), then 16 floats if non-identity.
fn read_matrix44(reader: &mut impl Read) -> Result<[f32; 16]> {
    let flag = reader.read_u8()?;
    if flag == 0 {
        return Ok([
            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,
        ]);
    }
    let mut m = [0f32; 16];
    for val in &mut m {
        *val = reader.read_f32()?;
    }
    Ok(m)
}

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

    /// Parse all plSceneObjects in Cleft_District_Cleft.prp using our new parser.
    #[test]
    fn test_parse_cleft_scene_objects() {
        use crate::resource::prp::{PrpPage, class_types};
        use std::path::Path;

        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() {
            eprintln!("Skipping test: {:?} not found", path);
            return;
        }

        let page = PrpPage::from_file(path).unwrap();
        let scene_keys: Vec<_> = page.keys_of_type(class_types::PL_SCENE_OBJECT);

        let mut parsed = 0;
        let mut with_draw = 0;
        let mut with_coord = 0;
        let mut with_sim = 0;
        let mut with_audio = 0;
        let mut total_modifiers = 0;

        for key in &scene_keys {
            if let Some(data) = page.object_data(key) {
                let mut cursor = Cursor::new(data);

                // Skip creatable class index (i16)
                let _ = cursor.read_i16().unwrap();

                match SceneObjectData::read(&mut cursor) {
                    Ok(so) => {
                        parsed += 1;
                        if so.draw_interface.is_some() {
                            with_draw += 1;
                        }
                        if so.coord_interface.is_some() {
                            with_coord += 1;
                        }
                        if so.sim_interface.is_some() {
                            with_sim += 1;
                        }
                        if so.audio_interface.is_some() {
                            with_audio += 1;
                        }
                        total_modifiers += so.modifiers.len();

                        // Verify self-key name matches
                        if let Some(uoid) = &so.self_key {
                            assert_eq!(
                                uoid.object_name, key.object_name,
                                "Self-key name mismatch for {}",
                                key.object_name
                            );
                        }
                    }
                    Err(e) => {
                        panic!(
                            "Failed to parse SceneObject '{}': {}",
                            key.object_name, e
                        );
                    }
                }
            }
        }

        eprintln!(
            "Parsed {} plSceneObjects: {} with draw, {} with coord, {} with sim, {} with audio, {} total modifiers",
            parsed, with_draw, with_coord, with_sim, with_audio, total_modifiers
        );
        assert!(parsed > 0, "Should have parsed at least some scene objects");
        assert!(with_draw > 0, "Some objects should have draw interfaces");
        assert!(with_coord > 0, "Some objects should have coordinate interfaces");
    }

    /// Parse plCoordinateInterface objects from Cleft.
    #[test]
    fn test_parse_cleft_coord_interfaces() {
        use crate::core::class_index::ClassIndex;
        use crate::resource::prp::PrpPage;
        use std::path::Path;

        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() {
            eprintln!("Skipping test: {:?} not found", path);
            return;
        }

        let page = PrpPage::from_file(path).unwrap();
        let coord_keys: Vec<_> = page.keys_of_type(ClassIndex::PL_COORDINATE_INTERFACE);

        let mut parsed = 0;
        for key in &coord_keys {
            if let Some(data) = page.object_data(key) {
                let mut cursor = Cursor::new(data);
                let _ = cursor.read_i16().unwrap(); // creatable class index

                match CoordinateInterfaceData::read(&mut cursor) {
                    Ok(ci) => {
                        parsed += 1;
                        // Verify the transform matrices are plausible
                        // (diagonal elements should be non-zero for valid transforms)
                        let l2w = ci.local_to_world;
                        let has_some_nonzero = l2w.iter().any(|&v| v != 0.0);
                        assert!(
                            has_some_nonzero,
                            "L2W matrix for {} is all zeros",
                            key.object_name
                        );
                    }
                    Err(e) => {
                        panic!(
                            "Failed to parse CoordinateInterface '{}': {}",
                            key.object_name, e
                        );
                    }
                }
            }
        }

        eprintln!(
            "Parsed {} plCoordinateInterfaces from Cleft",
            parsed
        );
        assert!(parsed > 0, "Should have parsed coordinate interfaces");
    }

    /// Parse plDrawInterface objects from Cleft.
    #[test]
    fn test_parse_cleft_draw_interfaces() {
        use crate::core::class_index::ClassIndex;
        use crate::resource::prp::PrpPage;
        use std::path::Path;

        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() {
            eprintln!("Skipping test: {:?} not found", path);
            return;
        }

        let page = PrpPage::from_file(path).unwrap();
        let draw_keys: Vec<_> = page.keys_of_type(ClassIndex::PL_DRAW_INTERFACE);

        let mut parsed = 0;
        let mut total_drawables = 0;
        for key in &draw_keys {
            if let Some(data) = page.object_data(key) {
                let mut cursor = Cursor::new(data);
                let _ = cursor.read_i16().unwrap(); // creatable class index

                match DrawInterfaceData::read(&mut cursor) {
                    Ok(di) => {
                        parsed += 1;
                        total_drawables += di.drawables.len();

                        // Verify drawable references point to plDrawableSpans
                        for (idx, key_ref) in &di.drawables {
                            if let Some(uoid) = key_ref {
                                assert_eq!(
                                    uoid.class_type,
                                    ClassIndex::PL_DRAWABLE_SPANS,
                                    "DrawInterface should reference plDrawableSpans, got 0x{:04X} for {}",
                                    uoid.class_type,
                                    key.object_name
                                );
                            }
                        }
                    }
                    Err(e) => {
                        panic!(
                            "Failed to parse DrawInterface '{}': {}",
                            key.object_name, e
                        );
                    }
                }
            }
        }

        eprintln!(
            "Parsed {} plDrawInterfaces ({} total drawable refs) from Cleft",
            parsed, total_drawables
        );
        assert!(parsed > 0, "Should have parsed draw interfaces");
        assert!(total_drawables > 0, "Should have drawable references");
    }

    /// Extract spawn point transforms by following SceneObject → modifier → CoordinateInterface chain.
    #[test]
    fn find_cleft_spawn_transforms() {
        use crate::core::class_index::ClassIndex;
        use crate::resource::prp::PrpPage;
        use std::path::Path;

        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Desert.prp");
        if !path.exists() { return; }
        let page = PrpPage::from_file(path).unwrap();

        let spawn_names: std::collections::HashSet<String> = page.keys_of_type(ClassIndex::PL_SPAWN_MODIFIER)
            .iter().map(|k| k.object_name.clone()).collect();
        assert!(!spawn_names.is_empty());

        let mut found = 0;
        for so_key in page.keys_of_type(ClassIndex::PL_SCENE_OBJECT) {
            let has_spawn = if let Some(data) = page.object_data(so_key) {
                let mut c = Cursor::new(data);
                let _ = c.read_i16().unwrap();
                SceneObjectData::read(&mut c).map_or(false, |so| {
                    so.modifiers.iter().any(|m| m.as_ref().map_or(false, |u| spawn_names.contains(&u.object_name)))
                })
            } else { false };
            if !has_spawn { continue; }

            if let Some(data) = page.object_data(so_key) {
                let mut cursor = Cursor::new(data);
                let _ = cursor.read_i16().unwrap();
                if let Ok(so) = SceneObjectData::read(&mut cursor) {
                    if let Some(ci_uoid) = &so.coord_interface {
                        for ci_key in page.keys_of_type(ClassIndex::PL_COORDINATE_INTERFACE) {
                            if ci_key.object_name != ci_uoid.object_name { continue; }
                            if let Some(ci_data) = page.object_data(ci_key) {
                                let mut ci_cursor = Cursor::new(ci_data);
                                let _ = ci_cursor.read_i16().unwrap();
                                if let Ok(ci) = CoordinateInterfaceData::read(&mut ci_cursor) {
                                    let m = ci.local_to_world;
                                    // Row-major: translation at m[3], m[7], m[11]
                                    found += 1;
                                    if so_key.object_name == "LinkInPointDefault" {
                                        // Verify the known Cleft LinkInPointDefault position
                                        assert!((m[3] - -147.78).abs() < 1.0, "X mismatch: {}", m[3]);
                                        assert!((m[7] - -648.55).abs() < 1.0, "Y mismatch: {}", m[7]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        assert!(found > 0, "Should have found spawn transforms");
    }
}