Skip to main content

open_dis_rust/
live_entity_information.rs

1//     open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
2//                     Simulation (DIS) application protocol
3//     Copyright (C) 2026 Cameron Howell
4//
5//     Licensed under the BSD 2-Clause License
6
7//! The Live Entity (LE) Information/Interaction protocol family
8
9use bitflags::bitflags;
10use deku::{
11    DekuError, DekuReader, DekuWriter,
12    no_std_io::{Read, Seek, Write},
13    reader::Reader,
14    writer::Writer,
15};
16
17use crate::siso::enums::{DetonationResult, ForceId, PduType, ProtocolFamily};
18use crate::wire::impl_deku_bitflags;
19use crate::{
20    live_entity_records::{
21        FixedBinary16, LEDeadReckoningParameters, LEEntityId, LEEulerAngles, LELinearVelocity,
22        LiveEntityOrientation16, LiveEntityPduHeader, LiveEntityRelativeLocation,
23        LiveEventIdentifier, LiveMunitionDescriptor, OrientationError, PositionError,
24        RelativeWorldCoordinates,
25    },
26    pdu::impl_pdu,
27    records::{EntityAppearance, EntityCapabilities, EntityMarking, EntityType, VariableParameter},
28};
29
30bitflags! {
31    /// TSPI Flag (IEEE 1278.1-2012 §9.4.2.5): which optional TSPI fields are
32    /// present. Bit 0 is the least significant bit.
33    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
34    pub struct TspiFlag: u8 {
35        const LINEAR_VELOCITY      = 1 << 0;
36        const ORIENTATION          = 1 << 1;
37        const POSITION_ERROR       = 1 << 2;
38        const ORIENTATION_ERROR    = 1 << 3;
39        const DEAD_RECKONING       = 1 << 4;
40        const MEASURED_SPEED       = 1 << 5;
41        const SYSTEM_SPECIFIC_DATA = 1 << 6;
42    }
43}
44impl_deku_bitflags!(TspiFlag, u8);
45
46/// Implemented according to IEEE 1278.1-2012 §9.4.2.5
47///
48/// Only the entity ID, flag and location are always present. Set the
49/// optional fields you want to send; `serialize` sets `tspi_flag` to match.
50#[derive(Debug, Default, Clone, deku::DekuRead, deku::DekuWrite)]
51#[deku(endian = "big")]
52pub struct TimeSpacePositionInformationPdu {
53    #[deku(skip)]
54    header: LiveEntityPduHeader,
55    pub live_entity_id: LEEntityId,
56    #[deku(update = "self.derived_tspi_flag()")]
57    pub tspi_flag: TspiFlag,
58    pub entity_location: RelativeWorldCoordinates,
59    #[deku(cond = "tspi_flag.contains(TspiFlag::LINEAR_VELOCITY)")]
60    pub entity_linear_velocity: Option<LELinearVelocity>,
61    #[deku(cond = "tspi_flag.contains(TspiFlag::ORIENTATION)")]
62    pub entity_orientation: Option<LEEulerAngles>,
63    #[deku(cond = "tspi_flag.contains(TspiFlag::POSITION_ERROR)")]
64    pub position_error: Option<PositionError>,
65    #[deku(cond = "tspi_flag.contains(TspiFlag::ORIENTATION_ERROR)")]
66    pub orientation_error: Option<OrientationError>,
67    #[deku(cond = "tspi_flag.contains(TspiFlag::DEAD_RECKONING)")]
68    pub dead_reckoning_parameters: Option<LEDeadReckoningParameters>,
69    #[deku(cond = "tspi_flag.contains(TspiFlag::MEASURED_SPEED)")]
70    pub measured_speed: Option<FixedBinary16<0>>,
71    /// Up to 255 octets. Sent as a one-octet length followed by the data.
72    #[deku(
73        cond = "tspi_flag.contains(TspiFlag::SYSTEM_SPECIFIC_DATA)",
74        reader = "read_system_specific_data(deku::reader)",
75        writer = "write_system_specific_data(deku::writer, system_specific_data.as_deref())"
76    )]
77    pub system_specific_data: Option<Vec<u8>>,
78}
79impl_pdu!(
80    TimeSpacePositionInformationPdu,
81    LiveEntityPduHeader,
82    PduType::TimeSpacePositionInformation,
83    ProtocolFamily::LiveEntityInformationInteraction
84);
85
86impl TimeSpacePositionInformationPdu {
87    /// The flag implied by which optional fields are present. Bits the
88    /// flag doesn't name are kept.
89    fn derived_tspi_flag(&self) -> TspiFlag {
90        let mut flag = self.tspi_flag;
91        flag.set(
92            TspiFlag::LINEAR_VELOCITY,
93            self.entity_linear_velocity.is_some(),
94        );
95        flag.set(TspiFlag::ORIENTATION, self.entity_orientation.is_some());
96        flag.set(TspiFlag::POSITION_ERROR, self.position_error.is_some());
97        flag.set(
98            TspiFlag::ORIENTATION_ERROR,
99            self.orientation_error.is_some(),
100        );
101        flag.set(
102            TspiFlag::DEAD_RECKONING,
103            self.dead_reckoning_parameters.is_some(),
104        );
105        flag.set(TspiFlag::MEASURED_SPEED, self.measured_speed.is_some());
106        flag.set(
107            TspiFlag::SYSTEM_SPECIFIC_DATA,
108            self.system_specific_data.is_some(),
109        );
110        flag
111    }
112}
113
114fn read_system_specific_data<R: Read + Seek>(
115    reader: &mut Reader<R>,
116) -> Result<Option<Vec<u8>>, DekuError> {
117    let length = u8::from_reader_with_ctx(reader, ())?;
118    let mut data = vec![0; usize::from(length)];
119    for octet in &mut data {
120        *octet = u8::from_reader_with_ctx(reader, ())?;
121    }
122    Ok(Some(data))
123}
124
125fn write_system_specific_data<W: Write + Seek>(
126    writer: &mut Writer<W>,
127    data: Option<&[u8]>,
128) -> Result<(), DekuError> {
129    let Some(data) = data else {
130        return Ok(());
131    };
132    let length = u8::try_from(data.len()).map_err(|_| {
133        DekuError::Assertion("TSPI system-specific data is longer than 255 octets".into())
134    })?;
135    length.to_writer(writer, ())?;
136    data.to_writer(writer, ())
137}
138
139// ---------------------------------------------------------------------------
140// Appearance
141// ---------------------------------------------------------------------------
142
143bitflags! {
144    /// Appearance Flags 1 (IEEE 1278.1-2012 §9.4.3.5)
145    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
146    pub struct AppearanceFlags1: u8 {
147        const FORCE_ID_INCLUDED          = 0b0000_0001;
148        const ENTITY_TYPE_INCLUDED       = 0b0000_0010;
149        const ALT_ENTITY_TYPE_INCLUDED   = 0b0000_0100;
150        const ENTITY_MARKING_INCLUDED    = 0b0000_1000;
151        const CAPABILITIES_INCLUDED      = 0b0001_0000;
152        const VISUAL_INCLUDED            = 0b0010_0000;
153        const IR_INCLUDED                = 0b0100_0000;
154        const FLAG2_INCLUDED             = 0b1000_0000;
155    }
156}
157impl_deku_bitflags!(AppearanceFlags1, u8);
158
159bitflags! {
160    /// Appearance Flag-2 (IEEE 1278.1-2012 §9.4.3.5, Table 222). Bits it
161    /// does not name are kept.
162    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
163    pub struct AppearanceFlags2: u8 {
164        const EM_INCLUDED     = 0b0000_0001;
165        const AUDIO_INCLUDED  = 0b0000_0010;
166    }
167}
168impl_deku_bitflags!(AppearanceFlags2, u8);
169
170/// Implemented according to IEEE 1278.1-2012 §9.4.3.5
171///
172/// Set the optional fields you want to send; `serialize` sets the presence
173/// flags to match.
174#[derive(Debug, Default, Clone, deku::DekuRead, deku::DekuWrite)]
175#[deku(endian = "big")]
176pub struct AppearancePdu {
177    #[deku(skip)]
178    header: LiveEntityPduHeader,
179    pub live_entity_id: LEEntityId,
180    #[deku(update = "self.derived_flags1()")]
181    pub appearance_flags1: AppearanceFlags1,
182    #[deku(
183        cond = "appearance_flags1.contains(AppearanceFlags1::FLAG2_INCLUDED)",
184        update = "self.derived_flags2()"
185    )]
186    pub appearance_flags2: Option<AppearanceFlags2>,
187    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::FORCE_ID_INCLUDED)")]
188    pub force_id: Option<ForceId>,
189    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::ENTITY_TYPE_INCLUDED)")]
190    pub entity_type: Option<EntityType>,
191    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::ALT_ENTITY_TYPE_INCLUDED)")]
192    pub alternate_entity_type: Option<EntityType>,
193    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::ENTITY_MARKING_INCLUDED)")]
194    pub entity_marking: Option<EntityMarking>,
195    /// SISO-REF-010 UID 55: a set of capability bits whose meaning depends
196    /// on the entity kind and domain.
197    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::CAPABILITIES_INCLUDED)")]
198    pub capabilities: Option<EntityCapabilities>,
199    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::VISUAL_INCLUDED)")]
200    pub appearance_visual: Option<EntityAppearance>,
201    #[deku(cond = "appearance_flags1.contains(AppearanceFlags1::IR_INCLUDED)")]
202    pub appearance_ir: Option<EntityAppearance>,
203    #[deku(cond = "appearance_flags2.is_some_and(|f| f.contains(AppearanceFlags2::EM_INCLUDED))")]
204    pub appearance_em: Option<EntityAppearance>,
205    #[deku(
206        cond = "appearance_flags2.is_some_and(|f| f.contains(AppearanceFlags2::AUDIO_INCLUDED))"
207    )]
208    pub appearance_audio: Option<EntityAppearance>,
209}
210impl_pdu!(
211    AppearancePdu,
212    LiveEntityPduHeader,
213    PduType::Appearance,
214    ProtocolFamily::LiveEntityInformationInteraction
215);
216
217impl AppearancePdu {
218    /// Flags 2 as implied by the EM and audio fields. A Flags 2 record that
219    /// is already present is kept, with any bits it doesn't name.
220    fn derived_flags2(&self) -> Option<AppearanceFlags2> {
221        let em = self.appearance_em.is_some();
222        let audio = self.appearance_audio.is_some();
223        if self.appearance_flags2.is_none() && !em && !audio {
224            return None;
225        }
226        let mut flags = self.appearance_flags2.unwrap_or_default();
227        flags.set(AppearanceFlags2::EM_INCLUDED, em);
228        flags.set(AppearanceFlags2::AUDIO_INCLUDED, audio);
229        Some(flags)
230    }
231
232    /// Flags 1 as implied by which optional fields are present.
233    fn derived_flags1(&self) -> AppearanceFlags1 {
234        let mut flags = AppearanceFlags1::empty();
235        flags.set(AppearanceFlags1::FORCE_ID_INCLUDED, self.force_id.is_some());
236        flags.set(
237            AppearanceFlags1::ENTITY_TYPE_INCLUDED,
238            self.entity_type.is_some(),
239        );
240        flags.set(
241            AppearanceFlags1::ALT_ENTITY_TYPE_INCLUDED,
242            self.alternate_entity_type.is_some(),
243        );
244        flags.set(
245            AppearanceFlags1::ENTITY_MARKING_INCLUDED,
246            self.entity_marking.is_some(),
247        );
248        flags.set(
249            AppearanceFlags1::CAPABILITIES_INCLUDED,
250            self.capabilities.is_some(),
251        );
252        flags.set(
253            AppearanceFlags1::VISUAL_INCLUDED,
254            self.appearance_visual.is_some(),
255        );
256        flags.set(AppearanceFlags1::IR_INCLUDED, self.appearance_ir.is_some());
257        flags.set(
258            AppearanceFlags1::FLAG2_INCLUDED,
259            self.derived_flags2().is_some(),
260        );
261        flags
262    }
263}
264
265/// Implemented according to IEEE 1278.1-2012 §9.4.4.5
266#[derive(Debug, Default, Clone, deku::DekuRead, deku::DekuWrite)]
267#[deku(endian = "big")]
268pub struct ArticulatedPartsPdu {
269    #[deku(skip)]
270    header: LiveEntityPduHeader,
271    pub live_entity_id: LEEntityId,
272    /// Set by `serialize` from `variable_parameter_records`.
273    #[deku(update = "self.variable_parameter_records.len()")]
274    pub number_of_variable_parameter_records: u8,
275    #[deku(count = "number_of_variable_parameter_records")]
276    pub variable_parameter_records: Vec<VariableParameter>,
277}
278impl_pdu!(
279    ArticulatedPartsPdu,
280    LiveEntityPduHeader,
281    PduType::ArticulatedParts,
282    ProtocolFamily::LiveEntityInformationInteraction
283);
284
285bitflags! {
286    /// LE Fire Flag (IEEE 1278.1-2012 §9.4.5.2, Table 225): which optional
287    /// LE Fire PDU fields are present. `serialize` sets it from the fields
288    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
289    pub struct LEFireFlags: u8 {
290        const TARGET_ID                 = 1 << 0;
291        const MUNITION_SITE_APPLICATION = 1 << 1;
292        const MUNITION_ID               = 1 << 2;
293        const EVENT_SITE_APPLICATION    = 1 << 3;
294        const WARHEAD_FUSE              = 1 << 4;
295        const QUANTITY_RATE             = 1 << 5;
296        const LOCATION                  = 1 << 6;
297    }
298}
299impl_deku_bitflags!(LEFireFlags, u8);
300
301/// Implemented according to IEEE 1278.1-2012 §9.4.5.6
302///
303/// Set the optional fields you want to send; `serialize` sets `flags` to
304/// match. The munition and event IDs' site and application numbers are sent
305/// only when they differ from the firing entity's, as the standard requires,
306/// and are filled in from it when they are not sent.
307///
308/// If `target_live_entity_id` is `None`, the standard requires `location`
309/// (§9.4.5.6 g)
310#[derive(Debug, Default, Clone, deku::DekuRead, deku::DekuWrite)]
311#[deku(endian = "big")]
312pub struct LiveEntityFirePdu {
313    #[deku(skip)]
314    header: LiveEntityPduHeader,
315    pub firing_live_entity_id: LEEntityId,
316    #[deku(update = "self.derived_flags()")]
317    pub flags: LEFireFlags,
318    #[deku(cond = "flags.contains(LEFireFlags::TARGET_ID)")]
319    pub target_live_entity_id: Option<LEEntityId>,
320    #[deku(
321        reader = "read_compact_entity_id(deku::reader, flags.contains(LEFireFlags::MUNITION_ID), flags.contains(LEFireFlags::MUNITION_SITE_APPLICATION), *firing_live_entity_id)",
322        writer = "write_compact_entity_id(deku::writer, *munition_live_entity_id, flags.contains(LEFireFlags::MUNITION_SITE_APPLICATION))"
323    )]
324    pub munition_live_entity_id: Option<LEEntityId>,
325    #[deku(
326        reader = "read_event_id(deku::reader, flags.contains(LEFireFlags::EVENT_SITE_APPLICATION), *firing_live_entity_id)",
327        writer = "write_event_id(deku::writer, *event_id, flags.contains(LEFireFlags::EVENT_SITE_APPLICATION))"
328    )]
329    pub event_id: LiveEventIdentifier,
330    #[deku(cond = "flags.contains(LEFireFlags::LOCATION)")]
331    pub location: Option<RelativeWorldCoordinates>,
332    #[deku(
333        ctx = "flags.contains(LEFireFlags::WARHEAD_FUSE), flags.contains(LEFireFlags::QUANTITY_RATE)"
334    )]
335    pub munition_descriptor: LiveMunitionDescriptor,
336    pub velocity: LELinearVelocity,
337    pub range: u16,
338}
339impl_pdu!(
340    LiveEntityFirePdu,
341    LiveEntityPduHeader,
342    PduType::LiveEntityFire,
343    ProtocolFamily::LiveEntityInformationInteraction
344);
345
346impl LiveEntityFirePdu {
347    /// The flags implied by which optional fields are present and whether
348    /// the munition and event IDs' site and application differ from the
349    /// firing entity's
350    fn derived_flags(&self) -> LEFireFlags {
351        let firing = self.firing_live_entity_id;
352        let mut flags = LEFireFlags::empty();
353        flags.set(LEFireFlags::TARGET_ID, self.target_live_entity_id.is_some());
354        flags.set(
355            LEFireFlags::MUNITION_ID,
356            self.munition_live_entity_id.is_some(),
357        );
358        flags.set(
359            LEFireFlags::MUNITION_SITE_APPLICATION,
360            self.munition_live_entity_id.is_some_and(|id| {
361                !same_site_application(id.site_number, id.application_number, firing)
362            }),
363        );
364        flags.set(
365            LEFireFlags::EVENT_SITE_APPLICATION,
366            !same_site_application(
367                self.event_id.site_number,
368                self.event_id.application_number,
369                firing,
370            ),
371        );
372        flags.set(
373            LEFireFlags::WARHEAD_FUSE,
374            self.munition_descriptor.warhead_and_fuse.is_some(),
375        );
376        flags.set(
377            LEFireFlags::QUANTITY_RATE,
378            self.munition_descriptor.quantity_and_rate.is_some(),
379        );
380        flags.set(LEFireFlags::LOCATION, self.location.is_some());
381        flags
382    }
383}
384
385/// Whether a site and application are the firing entity's, so they are left
386/// out of a munition or event ID
387const fn same_site_application(site: u8, application: u8, firing: LEEntityId) -> bool {
388    site == firing.site_number && application == firing.application_number
389}
390
391/// Reads a site and application number, or takes the firing entity's when
392/// they aren't sent.
393fn read_site_application<R: Read + Seek>(
394    reader: &mut Reader<R>,
395    included: bool,
396    firing: LEEntityId,
397) -> Result<(u8, u8), DekuError> {
398    if included {
399        Ok((
400            u8::from_reader_with_ctx(reader, ())?,
401            u8::from_reader_with_ctx(reader, ())?,
402        ))
403    } else {
404        Ok((firing.site_number, firing.application_number))
405    }
406}
407
408fn write_site_application<W: Write + Seek>(
409    writer: &mut Writer<W>,
410    included: bool,
411    site: u8,
412    application: u8,
413) -> Result<(), DekuError> {
414    if included {
415        site.to_writer(writer, ())?;
416        application.to_writer(writer, ())?;
417    }
418    Ok(())
419}
420
421/// A munition ID: absent, or an optional site and application number then
422/// the entity number.
423fn read_compact_entity_id<R: Read + Seek>(
424    reader: &mut Reader<R>,
425    present: bool,
426    site_application_included: bool,
427    firing: LEEntityId,
428) -> Result<Option<LEEntityId>, DekuError> {
429    if !present {
430        return Ok(None);
431    }
432    let (site_number, application_number) =
433        read_site_application(reader, site_application_included, firing)?;
434    let entity_number = u16::from_reader_with_ctx(reader, deku::ctx::Endian::Big)?;
435    Ok(Some(LEEntityId {
436        site_number,
437        application_number,
438        entity_number,
439    }))
440}
441
442fn write_compact_entity_id<W: Write + Seek>(
443    writer: &mut Writer<W>,
444    id: Option<LEEntityId>,
445    site_application_included: bool,
446) -> Result<(), DekuError> {
447    let Some(id) = id else {
448        return Ok(());
449    };
450    write_site_application(
451        writer,
452        site_application_included,
453        id.site_number,
454        id.application_number,
455    )?;
456    id.entity_number.to_writer(writer, deku::ctx::Endian::Big)
457}
458
459/// An event ID: an optional site and application number then the event
460/// number.
461fn read_event_id<R: Read + Seek>(
462    reader: &mut Reader<R>,
463    site_application_included: bool,
464    firing: LEEntityId,
465) -> Result<LiveEventIdentifier, DekuError> {
466    let (site_number, application_number) =
467        read_site_application(reader, site_application_included, firing)?;
468    let event_number = u16::from_reader_with_ctx(reader, deku::ctx::Endian::Big)?;
469    Ok(LiveEventIdentifier::new(
470        site_number,
471        application_number,
472        event_number,
473    ))
474}
475
476fn write_event_id<W: Write + Seek>(
477    writer: &mut Writer<W>,
478    id: LiveEventIdentifier,
479    site_application_included: bool,
480) -> Result<(), DekuError> {
481    write_site_application(
482        writer,
483        site_application_included,
484        id.site_number,
485        id.application_number,
486    )?;
487    id.event_number.to_writer(writer, deku::ctx::Endian::Big)
488}
489
490bitflags! {
491    /// LE Detonation Flag-1 (IEEE 1278.1-2012 §9.4.6.2, Table 227): which
492    /// optional LE Detonation PDU fields are present. `serialize` sets it
493    /// from the fields.
494    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
495    pub struct LEDetonationFlags1: u8 {
496        const TARGET_ID                 = 1 << 0;
497        const MUNITION_SITE_APPLICATION = 1 << 1;
498        const MUNITION_ID               = 1 << 2;
499        const EVENT_SITE_APPLICATION    = 1 << 3;
500        const WARHEAD_FUSE              = 1 << 4;
501        const QUANTITY_RATE             = 1 << 5;
502        /// Location in Entity's Coordinates is included and Location in
503        /// Relative World Coordinates is not.
504        const ENTITY_LOCATION           = 1 << 6;
505        const FLAG_2                    = 1 << 7;
506    }
507}
508impl_deku_bitflags!(LEDetonationFlags1, u8);
509
510bitflags! {
511    /// LE Detonation Flag-2 (IEEE 1278.1-2012 §9.4.6.2, Table 228). Bits it
512    /// does not name are kept
513    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
514    pub struct LEDetonationFlags2: u8 {
515        const MUNITION_ORIENTATION = 1 << 0;
516        const EVENT_ID             = 1 << 1;
517    }
518}
519impl_deku_bitflags!(LEDetonationFlags2, u8);
520
521/// Implemented according to IEEE 1278.1-2012 §9.4.6.8
522///
523/// Set the optional fields you want to send; `serialize` sets the flags to
524/// match. The munition and event IDs' site and application numbers are sent
525/// only when they differ from the firing entity's, as the standard requires,
526/// and are filled in from it when they are not sent.
527///
528/// Exactly one of `location_in_world_coordinates` and
529/// `location_in_entity_coordinates` must be set, and the entity-coordinates
530/// location needs a target (§9.4.6.8 k). `serialize` returns an error
531/// otherwise. `new()` sets the world-coordinates location.
532#[derive(Debug, Clone, deku::DekuRead, deku::DekuWrite)]
533#[deku(endian = "big")]
534pub struct LiveEntityDetonationPdu {
535    #[deku(skip)]
536    header: LiveEntityPduHeader,
537    pub firing_live_entity_id: LEEntityId,
538    #[deku(update = "self.derived_flags_1()?")]
539    pub flags_1: LEDetonationFlags1,
540    #[deku(
541        cond = "flags_1.contains(LEDetonationFlags1::FLAG_2)",
542        update = "self.derived_flags_2()"
543    )]
544    pub flags_2: Option<LEDetonationFlags2>,
545    #[deku(cond = "flags_1.contains(LEDetonationFlags1::TARGET_ID)")]
546    pub target_live_entity_id: Option<LEEntityId>,
547    #[deku(
548        reader = "read_compact_entity_id(deku::reader, flags_1.contains(LEDetonationFlags1::MUNITION_ID), flags_1.contains(LEDetonationFlags1::MUNITION_SITE_APPLICATION), *firing_live_entity_id)",
549        writer = "write_compact_entity_id(deku::writer, *munition_live_entity_id, flags_1.contains(LEDetonationFlags1::MUNITION_SITE_APPLICATION))"
550    )]
551    pub munition_live_entity_id: Option<LEEntityId>,
552    #[deku(
553        reader = "read_optional_event_id(deku::reader, flags_2.is_some_and(|f| f.contains(LEDetonationFlags2::EVENT_ID)), flags_1.contains(LEDetonationFlags1::EVENT_SITE_APPLICATION), *firing_live_entity_id)",
554        writer = "write_optional_event_id(deku::writer, *event_id, flags_1.contains(LEDetonationFlags1::EVENT_SITE_APPLICATION))"
555    )]
556    pub event_id: Option<LiveEventIdentifier>,
557    #[deku(cond = "!flags_1.contains(LEDetonationFlags1::ENTITY_LOCATION)")]
558    pub location_in_world_coordinates: Option<RelativeWorldCoordinates>,
559    pub velocity: LELinearVelocity,
560    #[deku(cond = "flags_2.is_some_and(|f| f.contains(LEDetonationFlags2::MUNITION_ORIENTATION))")]
561    pub munition_orientation: Option<LiveEntityOrientation16>,
562    #[deku(
563        ctx = "flags_1.contains(LEDetonationFlags1::WARHEAD_FUSE), flags_1.contains(LEDetonationFlags1::QUANTITY_RATE)"
564    )]
565    pub munition_descriptor: LiveMunitionDescriptor,
566    #[deku(cond = "flags_1.contains(LEDetonationFlags1::ENTITY_LOCATION)")]
567    pub location_in_entity_coordinates: Option<LiveEntityRelativeLocation>,
568    pub detonation_result: DetonationResult,
569}
570impl_pdu!(
571    LiveEntityDetonationPdu,
572    LiveEntityPduHeader,
573    PduType::LiveEntityDetonation,
574    ProtocolFamily::LiveEntityInformationInteraction
575);
576
577impl Default for LiveEntityDetonationPdu {
578    fn default() -> Self {
579        Self {
580            header: LiveEntityPduHeader::default(),
581            firing_live_entity_id: LEEntityId::default(),
582            flags_1: LEDetonationFlags1::empty(),
583            flags_2: None,
584            target_live_entity_id: None,
585            munition_live_entity_id: None,
586            event_id: None,
587            location_in_world_coordinates: Some(RelativeWorldCoordinates::default()),
588            velocity: LELinearVelocity::default(),
589            munition_orientation: None,
590            munition_descriptor: LiveMunitionDescriptor::default(),
591            location_in_entity_coordinates: None,
592            detonation_result: DetonationResult::default(),
593        }
594    }
595}
596
597impl LiveEntityDetonationPdu {
598    /// Flag-2 as implied by the munition orientation and event ID. A Flag-2
599    /// that is already present is kept, with any bits it doesn't name.
600    fn derived_flags_2(&self) -> Option<LEDetonationFlags2> {
601        let orientation = self.munition_orientation.is_some();
602        let event = self.event_id.is_some();
603        if self.flags_2.is_none() && !orientation && !event {
604            return None;
605        }
606        let mut flags = self.flags_2.unwrap_or_default();
607        flags.set(LEDetonationFlags2::MUNITION_ORIENTATION, orientation);
608        flags.set(LEDetonationFlags2::EVENT_ID, event);
609        Some(flags)
610    }
611
612    /// Flag-1 as implied by the optional fields, after checking that exactly
613    /// one location is set and the entity-coordinates one has a target.
614    fn derived_flags_1(&self) -> Result<LEDetonationFlags1, DekuError> {
615        let entity_location = match (
616            self.location_in_world_coordinates.is_some(),
617            self.location_in_entity_coordinates.is_some(),
618        ) {
619            (true, false) => false,
620            (false, true) => true,
621            _ => {
622                return Err(DekuError::Assertion(
623                        "an LE Detonation PDU needs exactly one of location_in_world_coordinates and location_in_entity_coordinates".into(),
624                    ));
625            }
626        };
627        if entity_location && self.target_live_entity_id.is_none() {
628            return Err(DekuError::Assertion(
629                    "an LE Detonation PDU's location_in_entity_coordinates needs a target_live_entity_id".into(),
630                ));
631        }
632        let firing = self.firing_live_entity_id;
633        let mut flags = LEDetonationFlags1::empty();
634        flags.set(
635            LEDetonationFlags1::TARGET_ID,
636            self.target_live_entity_id.is_some(),
637        );
638        flags.set(
639            LEDetonationFlags1::MUNITION_ID,
640            self.munition_live_entity_id.is_some(),
641        );
642        flags.set(
643            LEDetonationFlags1::MUNITION_SITE_APPLICATION,
644            self.munition_live_entity_id.is_some_and(|id| {
645                !same_site_application(id.site_number, id.application_number, firing)
646            }),
647        );
648        flags.set(
649            LEDetonationFlags1::EVENT_SITE_APPLICATION,
650            self.event_id.is_some_and(|id| {
651                !same_site_application(id.site_number, id.application_number, firing)
652            }),
653        );
654        flags.set(
655            LEDetonationFlags1::WARHEAD_FUSE,
656            self.munition_descriptor.warhead_and_fuse.is_some(),
657        );
658        flags.set(
659            LEDetonationFlags1::QUANTITY_RATE,
660            self.munition_descriptor.quantity_and_rate.is_some(),
661        );
662        flags.set(LEDetonationFlags1::ENTITY_LOCATION, entity_location);
663        flags.set(LEDetonationFlags1::FLAG_2, self.derived_flags_2().is_some());
664        Ok(flags)
665    }
666}
667
668fn read_optional_event_id<R: Read + Seek>(
669    reader: &mut Reader<R>,
670    present: bool,
671    site_application_included: bool,
672    firing: LEEntityId,
673) -> Result<Option<LiveEventIdentifier>, DekuError> {
674    if present {
675        read_event_id(reader, site_application_included, firing).map(Some)
676    } else {
677        Ok(None)
678    }
679}
680
681fn write_optional_event_id<W: Write + Seek>(
682    writer: &mut Writer<W>,
683    id: Option<LiveEventIdentifier>,
684    site_application_included: bool,
685) -> Result<(), DekuError> {
686    id.map_or(Ok(()), |id| {
687        write_event_id(writer, id, site_application_included)
688    })
689}
690
691#[cfg(test)]
692mod tests {
693    use super::*;
694    use crate::{pdu::Pdu, pdu::pdu_tests};
695
696    /// Serialize a PDU, failing the test if serialization returns an error.
697    pub fn to_bytes<P: Pdu>(pdu: &mut P) -> Vec<u8> {
698        pdu.to_bytes().expect("serialize failed")
699    }
700
701    pdu_tests!(
702        time_space_position_information_pdu_tests, TimeSpacePositionInformationPdu,
703        pdu_type: PduType::TimeSpacePositionInformation,
704        default_bits: 200,
705        wrong_type: AppearancePdu,
706    );
707    pdu_tests!(
708        appearance_pdu_tests, AppearancePdu,
709        pdu_type: PduType::Appearance,
710        default_bits: 136,
711        wrong_type: TimeSpacePositionInformationPdu,
712    );
713
714    /// Table 222: Flag-2 bit 0 marks Appearance-EM and bit 1 Appearance-Audio
715    #[test]
716    fn appearance_flag_2_bits_follow_table_222() {
717        let mut pdu = AppearancePdu::new();
718        pdu.appearance_em = Some(EntityAppearance::default());
719        let em_only = to_bytes(&mut pdu);
720        // LE header (12) + Live Entity ID (4) + Flag-1 (1), then Flag-2
721        assert_eq!(em_only[16], 0b1000_0000);
722        assert_eq!(em_only[17], 0b0000_0001);
723
724        pdu.appearance_em = None;
725        pdu.appearance_audio = Some(EntityAppearance::default());
726        assert_eq!(to_bytes(&mut pdu)[17], 0b0000_0010);
727    }
728
729    pdu_tests!(
730        articulated_parts_pdu_tests, ArticulatedPartsPdu,
731        pdu_type: PduType::ArticulatedParts,
732        default_bits: 136,
733        wrong_type: AppearancePdu,
734    );
735
736    use crate::live_entity_records::{QuantityAndRate, WarheadAndFuse};
737
738    fn le_id(site_number: u8, application_number: u8, entity_number: u16) -> LEEntityId {
739        LEEntityId {
740            site_number,
741            application_number,
742            entity_number,
743        }
744    }
745
746    /// Table 226 with every flag set: 280 + 32F0 + (16F1 + 16)F2 + 16F3 +
747    /// 64F6 + 32F4 + 32F5 = 488 bits, with no padding after the flag.
748    #[test]
749    fn le_fire_with_every_optional_field_follows_table_226() {
750        let mut pdu = LiveEntityFirePdu::new();
751        pdu.firing_live_entity_id = le_id(1, 2, 10);
752        pdu.target_live_entity_id = Some(le_id(3, 4, 5));
753        pdu.munition_live_entity_id = Some(le_id(7, 8, 9));
754        pdu.event_id = LiveEventIdentifier::new(7, 8, 11);
755        pdu.location = Some(RelativeWorldCoordinates::default());
756        pdu.munition_descriptor.warhead_and_fuse = Some(WarheadAndFuse::default());
757        pdu.munition_descriptor.quantity_and_rate = Some(QuantityAndRate {
758            quantity: 6,
759            rate: 600,
760        });
761        pdu.range = 0xBEEF;
762        let bytes = to_bytes(&mut pdu);
763
764        assert_eq!(bytes.len(), 488 / 8);
765        assert_eq!(bytes[16], 0b0111_1111, "flags");
766        assert_eq!(&bytes[17..21], &[3, 4, 0, 5], "target");
767        assert_eq!(&bytes[21..25], &[7, 8, 0, 9], "munition ID");
768        assert_eq!(&bytes[25..29], &[7, 8, 0, 11], "event ID");
769        assert_eq!(&bytes[49..53], &[0, 6, 2, 88], "quantity and rate");
770        assert_eq!(&bytes[59..61], &[0xBE, 0xEF], "range");
771
772        let decoded = LiveEntityFirePdu::deserialize(&mut bytes.as_slice()).expect("deserialize");
773        assert_eq!(decoded.munition_live_entity_id, Some(le_id(7, 8, 9)));
774        assert_eq!(decoded.event_id, LiveEventIdentifier::new(7, 8, 11));
775        assert_eq!(decoded.munition_descriptor, pdu.munition_descriptor);
776    }
777
778    /// §9.4.5.6 e) and f): site and application numbers equal to the firing
779    /// entity's "shall not be included" and their flag bits are zero.
780    #[test]
781    fn le_fire_leaves_out_the_firing_entitys_site_and_application() {
782        let mut pdu = LiveEntityFirePdu::new();
783        pdu.firing_live_entity_id = le_id(1, 2, 10);
784        pdu.munition_live_entity_id = Some(le_id(1, 2, 9));
785        pdu.event_id = LiveEventIdentifier::new(1, 2, 11);
786        pdu.location = Some(RelativeWorldCoordinates::default());
787        let bytes = to_bytes(&mut pdu);
788
789        // 280 + 16 (munition entity number) + 64 (location) bits
790        assert_eq!(bytes.len(), 360 / 8);
791        assert_eq!(bytes[16], 0b0100_0100, "flags");
792        assert_eq!(&bytes[17..21], &[0, 9, 0, 11], "munition and event numbers");
793
794        let decoded = LiveEntityFirePdu::deserialize(&mut bytes.as_slice()).expect("deserialize");
795        assert_eq!(decoded.munition_live_entity_id, Some(le_id(1, 2, 9)));
796        assert_eq!(decoded.event_id, LiveEventIdentifier::new(1, 2, 11));
797    }
798
799    /// Table 229: Flag-2 follows Flag-1 bit 7; the Event ID needs Flag-2 bit 1;
800    /// Location in Entity's Coordinates replaces Location in Relative World
801    /// Coordinates when Flag-1 bit 6 is set; no padding after the result.
802    #[test]
803    fn le_detonation_follows_table_229() {
804        let mut pdu = LiveEntityDetonationPdu::new();
805        pdu.firing_live_entity_id = le_id(1, 2, 10);
806        pdu.target_live_entity_id = Some(le_id(3, 4, 5));
807        pdu.event_id = Some(LiveEventIdentifier::new(5, 6, 11));
808        pdu.location_in_world_coordinates = None;
809        pdu.location_in_entity_coordinates = Some(LiveEntityRelativeLocation { x: 1, y: 2, z: 3 });
810        pdu.munition_orientation = Some(LiveEntityOrientation16::new(4, 5, 6));
811        pdu.detonation_result =
812            num_traits::FromPrimitive::from_u8(5).expect("a defined detonation result");
813        let bytes = to_bytes(&mut pdu);
814
815        // 256 + 8F7 + 32F0 + (16F3 + 16)G1 + 48G0 + 48F6 bits.
816        assert_eq!(bytes.len(), 424 / 8);
817        assert_eq!(bytes[16], 0b1100_1001, "flag 1");
818        assert_eq!(bytes[17], 0b0000_0011, "flag 2");
819        assert_eq!(&bytes[18..22], &[3, 4, 0, 5], "target");
820        assert_eq!(&bytes[22..26], &[5, 6, 0, 11], "event ID");
821        assert_eq!(&bytes[32..38], &[0, 4, 0, 5, 0, 6], "munition orientation");
822        assert_eq!(
823            &bytes[46..52],
824            &[0, 1, 0, 2, 0, 3],
825            "location in entity coordinates"
826        );
827        assert_eq!(bytes[52], 5, "detonation result");
828
829        let decoded =
830            LiveEntityDetonationPdu::deserialize(&mut bytes.as_slice()).expect("deserialize");
831        assert_eq!(decoded.event_id, Some(LiveEventIdentifier::new(5, 6, 11)));
832        assert!(decoded.location_in_world_coordinates.is_none());
833        assert_eq!(
834            decoded.location_in_entity_coordinates,
835            Some(LiveEntityRelativeLocation { x: 1, y: 2, z: 3 })
836        );
837    }
838
839    #[test]
840    fn le_detonation_needs_exactly_one_location() {
841        let mut pdu = LiveEntityDetonationPdu::new();
842        pdu.location_in_world_coordinates = None;
843        assert!(pdu.to_bytes().is_err());
844
845        pdu.location_in_world_coordinates = Some(RelativeWorldCoordinates::default());
846        pdu.location_in_entity_coordinates = Some(LiveEntityRelativeLocation::default());
847        assert!(pdu.to_bytes().is_err());
848
849        // §9.4.6.8 k): no entity-coordinates location without a target.
850        pdu.location_in_world_coordinates = None;
851        assert!(pdu.to_bytes().is_err());
852        pdu.target_live_entity_id = Some(LEEntityId::default());
853        assert!(pdu.to_bytes().is_ok());
854    }
855
856    pdu_tests!(
857        live_entity_fire_pdu_tests, LiveEntityFirePdu,
858        pdu_type: PduType::LiveEntityFire,
859        default_bits: 280,
860        wrong_type: LiveEntityDetonationPdu,
861    );
862    pdu_tests!(
863        live_entity_detonation_pdu_tests, LiveEntityDetonationPdu,
864        pdu_type: PduType::LiveEntityDetonation,
865        default_bits: 320,
866        wrong_type: LiveEntityFirePdu,
867    );
868}