cadmpeg-asm 0.6.1

Parse and write Autodesk Shape Manager record streams.
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
// SPDX-License-Identifier: Apache-2.0
//! Format-independent native record types retained from a decoded ASM stream.

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use cadmpeg_ir::ids::{EdgeId, FaceId, VertexId};

/// Source namespaces used to derive native record ids.
pub mod identity;

macro_rules! native_record {
    (
        $(#[doc = $record_doc:literal])*
        $name:ident, $wire:ident, $kind:literal,
        #[doc = $index_doc:literal]
        record_index,
        $(#[doc = $entity_doc:literal])*
        $entity:ident: $entity_ty:ty,
        $(
            $(#[doc = $field_doc:literal])*
            $field:ident: $field_ty:ty $([$($wire_attr:meta),*])?,
        )*
    ) => {
        $(#[doc = $record_doc])*
        #[derive(Debug, Clone, PartialEq)]
        pub struct $name {
            /// Source namespace of the native record.
            pub source_namespace: identity::NativeRecordNamespace,
            #[doc = $index_doc]
            pub record_index: u32,
            $(#[doc = $entity_doc])*
            pub $entity: $entity_ty,
            $(
                $(#[doc = $field_doc])*
                pub $field: $field_ty,
            )*
        }

        impl $name {
            /// Derive the native record id from its source identity.
            #[must_use]
            pub fn id(&self) -> String {
                self.source_namespace.id($kind, self.record_index)
            }
        }

        mod $wire {
            #[cfg(feature = "schema")]
            use schemars::JsonSchema;
            use serde::Deserialize;

            $(#[doc = $record_doc])*
            #[derive(Deserialize)]
            #[cfg_attr(feature = "schema", derive(JsonSchema))]
            #[serde(deny_unknown_fields)]
            pub(super) struct Wire {
                /// Globally unique deterministic identifier for this native record.
                #[cfg_attr(feature = "schema", schemars(with = "cadmpeg_ir::ids::Identity"))]
                pub(super) id: String,
                $(#[doc = $entity_doc])*
                pub(super) $entity: $entity_ty,
                #[doc = $index_doc]
                pub(super) record_index: u32,
                $(
                    $(#[doc = $field_doc])*
                    $($(#[$wire_attr])*)?
                    pub(super) $field: $field_ty,
                )*
            }
        }

        impl Serialize for $name {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                #[derive(Serialize)]
                struct Wire<'a> {
                    id: identity::NativeRecordIdentity<'a>,
                    $entity: &'a $entity_ty,
                    record_index: u32,
                    $(
                        $($(#[$wire_attr])*)?
                        $field: &'a $field_ty,
                    )*
                }
                Wire {
                    id: self.source_namespace.serialized_id($kind, self.record_index),
                    $entity: &self.$entity,
                    record_index: self.record_index,
                    $($field: &self.$field,)*
                }.serialize(serializer)
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let wire = $wire::Wire::deserialize(deserializer)?;
                let source_namespace = identity::NativeRecordNamespace::from_wire(&wire.id, wire.record_index, $kind)
                    .map_err(serde::de::Error::custom)?;
                Ok(Self {
                    source_namespace,
                    record_index: wire.record_index,
                    $entity: wire.$entity,
                    $($field: wire.$field,)*
                })
            }
        }

        impl cadmpeg_ir::schema::rewrite::typed::RewriteIdentities for $name {
            fn visit_identity_references(&self, ctx: &cadmpeg_core::decode::DecodeContext<'_>, visitor: &mut dyn FnMut(&str) -> Result<(), cadmpeg_core::CodecError>) -> Result<(), cadmpeg_core::CodecError> {
                let _depth = ctx.enter_nested("walk ASM native references")?;
                ctx.charge_work(1, "walk ASM native references")?;
                self.source_namespace.visit(ctx, $kind, self.record_index, visitor)?;
                cadmpeg_ir::schema::rewrite::typed::RewriteIdentities::visit_identity_references(&self.$entity, ctx, visitor)?;
                $(cadmpeg_ir::schema::rewrite::typed::RewriteIdentities::visit_identity_references(&self.$field, ctx, visitor)?;)*
                Ok(())
            }
            fn rewrite_identities<F: FnMut(&str) -> Result<String, cadmpeg_core::CodecError>>(mut self, ctx: &cadmpeg_core::decode::DecodeContext<'_>, map: &mut cadmpeg_ir::schema::rewrite::typed::IdentityMap<'_, F>) -> Result<Self, cadmpeg_core::CodecError> {
                let _depth = ctx.enter_nested("rewrite ASM native fields")?;
                ctx.charge_work(1, "rewrite ASM native fields")?;
                self.source_namespace = self.source_namespace.rewrite(ctx, $kind, self.record_index, map)?;
                self.$entity = cadmpeg_ir::schema::rewrite::typed::RewriteIdentities::rewrite_identities(self.$entity, ctx, map)?;
                $(self.$field = cadmpeg_ir::schema::rewrite::typed::RewriteIdentities::rewrite_identities(self.$field, ctx, map)?;)*
                Ok(self)
            }
        }

        #[cfg(feature = "schema")]
        impl JsonSchema for $name {
            fn schema_name() -> std::borrow::Cow<'static, str> {
                stringify!($name).into()
            }

            fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
                $wire::Wire::json_schema(generator)
            }
        }
    };
}

native_record! {
    /// Kernel continuity classification stored on one solved ASM edge record.
    EdgeContinuity, edge_continuity, "edge-continuity",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep edge carrying the classification.
    edge: cadmpeg_ir::ids::EdgeId,
    /// Native curve-parameterization sense before IR carrier normalization.
    sense: cadmpeg_ir::topology::Sense,
    /// Native continuity token, normally `tangent` or `unknown`.
    continuity: String,
}

native_record! {
    /// Native owner-coedge selector stored on one ASM edge record.
    EdgeOwnership, edge_ownership, "edge-ownership",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep edge carrying the selector.
    edge: cadmpeg_ir::ids::EdgeId,
    /// Selected coedge, or null when the native edge has no owner back-reference.
    owner_coedge: Option<cadmpeg_ir::ids::CoedgeId> [serde(default, skip_serializing_if = "Option::is_none")],
}

native_record! {
    /// Native owner-edge and endpoint-slot fields stored on one ASM vertex.
    VertexOwnership, vertex_ownership, "vertex-ownership",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep vertex carrying the fields.
    vertex: cadmpeg_ir::ids::VertexId,
    /// Edge selected as this vertex record's native owner.
    owning_edge: cadmpeg_ir::ids::EdgeId,
    /// Endpoint slot on `owning_edge`: `0` for start, `1` for end.
    endpoint_index: crate::brep::records::EndpointSlot,
}

/// Endpoint selected by a native vertex ownership record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "u8", into = "u8")]
pub enum EndpointSlot {
    /// Start vertex of the owning edge.
    Start,
    /// End vertex of the owning edge.
    End,
}

impl EndpointSlot {
    /// Native endpoint index.
    #[must_use]
    pub const fn code(self) -> u8 {
        match self {
            Self::Start => 0,
            Self::End => 1,
        }
    }
}

impl From<EndpointSlot> for u8 {
    fn from(value: EndpointSlot) -> Self {
        value.code()
    }
}

impl TryFrom<u8> for EndpointSlot {
    type Error = &'static str;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Start),
            1 => Ok(Self::End),
            _ => Err("endpoint_index must be 0 or 1"),
        }
    }
}

/// Conditional containment direction on a double-sided ASM face.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FaceContainment {
    /// The face bounds the inside side of its surface.
    In,
    /// The face bounds the outside side of its surface.
    Out,
}

/// Native sidedness fields stored on one ASM face record.
#[derive(Debug, Clone, PartialEq)]
pub struct FaceSidedness {
    /// Source namespace of the native record.
    pub source_namespace: identity::NativeRecordNamespace,
    /// Source SAB record index.
    pub record_index: u32,
    /// Solved B-rep face carrying the fields.
    pub face: FaceId,
    /// Sense token stored in the native face record before carrier normalization.
    pub native_sense: cadmpeg_ir::topology::Sense,
    /// Whether decoding reversed the native surface carrier orientation.
    pub carrier_flipped: bool,
    /// Conditional containment direction; absence denotes a single-sided face.
    pub containment: Option<FaceContainment>,
}

impl Serialize for FaceSidedness {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Wire<'a> {
            id: identity::NativeRecordIdentity<'a>,
            face: &'a FaceId,
            record_index: u32,
            native_sense: cadmpeg_ir::topology::Sense,
            normalized_sense: cadmpeg_ir::topology::Sense,
            #[serde(skip_serializing_if = "Option::is_none")]
            containment: Option<FaceContainment>,
        }
        Wire {
            id: self
                .source_namespace
                .serialized_id("face-sidedness", self.record_index),
            face: &self.face,
            record_index: self.record_index,
            native_sense: self.native_sense,
            normalized_sense: self.normalized_sense(),
            containment: self.containment,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for FaceSidedness {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        FaceSidednessWire::deserialize(deserializer)
            .and_then(|w| FaceSidedness::try_from(w).map_err(serde::de::Error::custom))
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for FaceSidedness {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "FaceSidedness".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        FaceSidednessWire::json_schema(generator)
    }
}

impl FaceSidedness {
    fn normalized_sense(&self) -> cadmpeg_ir::topology::Sense {
        use cadmpeg_ir::topology::Sense;
        match (self.native_sense, self.carrier_flipped) {
            (Sense::Forward, true) => Sense::Reversed,
            (Sense::Reversed, true) => Sense::Forward,
            (sense, false) => sense,
        }
    }

    /// Derive the native record id from its source identity.
    #[must_use]
    pub fn id(&self) -> String {
        self.source_namespace
            .id("face-sidedness", self.record_index)
    }
}

/// Serialized face sidedness with the native and normalized senses.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FaceSidednessWire {
    #[cfg_attr(feature = "schema", schemars(with = "cadmpeg_ir::ids::Identity"))]
    id: String,
    face: FaceId,
    record_index: u32,
    native_sense: cadmpeg_ir::topology::Sense,
    normalized_sense: cadmpeg_ir::topology::Sense,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_containment"
    )]
    containment: Option<FaceContainment>,
}

impl From<FaceSidedness> for FaceSidednessWire {
    fn from(value: FaceSidedness) -> Self {
        let normalized_sense = value.normalized_sense();
        Self {
            id: value.id(),
            face: value.face,
            record_index: value.record_index,
            native_sense: value.native_sense,
            normalized_sense,
            containment: value.containment,
        }
    }
}

impl TryFrom<FaceSidednessWire> for FaceSidedness {
    type Error = String;

    fn try_from(value: FaceSidednessWire) -> Result<Self, Self::Error> {
        let source_namespace = identity::NativeRecordNamespace::from_wire(
            &value.id,
            value.record_index,
            "face-sidedness",
        )?;
        Ok(Self {
            source_namespace,
            record_index: value.record_index,
            face: value.face,
            native_sense: value.native_sense,
            carrier_flipped: value.native_sense != value.normalized_sense,
            containment: value.containment,
        })
    }
}

native_record! {
    /// Native Design-join key stored on one ASM face record.
    FaceNativeKey, face_native_key, "face-native-key",
    /// Source SAB face record index.
    record_index,
    /// Solved face carrying the key.
    face: cadmpeg_ir::ids::FaceId,
    /// Non-negative Design-join key; absence is the native `-1` null value.
    asm_face_key: Option<u64> [serde(default, skip_serializing_if = "Option::is_none")],
}

/// Shape of the evaluated tolerance slot of one tolerant ASM vertex record,
/// with the version-gated LONG that follows the slot when it is present.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case", tag = "slot", deny_unknown_fields)]
pub enum EvaluatedToleranceSlot {
    /// The record ends before the slot; the vertex carries no tolerance and
    /// there is no trailing field.
    Absent {},
    /// The slot holds the `-1` unset sentinel; the vertex carries no tolerance.
    Unset {
        /// Trailing LONG following the slot, retained verbatim; absent in
        /// older streams, a small non-negative per-entity change counter when
        /// present.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_trailing"
        )]
        trailing: Option<i64>,
    },
    /// The slot holds a tolerance, stored on the vertex.
    Evaluated {
        /// Trailing LONG following the slot, retained verbatim; absent in
        /// older streams, a small non-negative per-entity change counter when
        /// present.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_trailing"
        )]
        trailing: Option<i64>,
    },
}

impl EvaluatedToleranceSlot {
    /// The trailing LONG following the slot, when the slot is present.
    #[must_use]
    pub fn trailing(self) -> Option<i64> {
        match self {
            Self::Absent {} => None,
            Self::Unset { trailing } | Self::Evaluated { trailing } => trailing,
        }
    }
}

native_record! {
    /// Native leading tolerance slots retained from one tolerant ASM vertex
    /// record. The record's three f64 tolerance slots are three independent
    /// tolerance evaluations, each using `-1` as its unset sentinel; the third
    /// slot is the effective vertex tolerance and is stored on the vertex, while
    /// the first two are retained here verbatim.
    TolerantVertexTail, tolerant_vertex_tail, "tolerant-vertex-tail",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep vertex carrying the tolerant record.
    vertex: cadmpeg_ir::ids::VertexId,
    /// The first two independent tolerance evaluations, retained verbatim in
    /// native centimetres; `-1` denotes an unset evaluation.
    leading_tolerances: [cadmpeg_ir::scalar::FiniteReal; 2],
    /// Shape of the evaluated tolerance slot, carrying the trailing LONG that
    /// follows it. The unset sentinel is a marker rather than a length, so the
    /// neutral vertex carries no tolerance and this record keeps whether the
    /// slot was unset or absent.
    evaluated_slot: crate::brep::records::EvaluatedToleranceSlot,
}

native_record! {
    /// Native tail retained from one tolerant ASM edge record: the entity
    /// serializer revision stamp followed by a version-gated LONG.
    TolerantEdgeTail, tolerant_edge_tail, "tolerant-edge-tail",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep edge carrying the tolerant record.
    edge: cadmpeg_ir::ids::EdgeId,
    /// Per-entity serializer revision stamp following the model-space
    /// tolerance, matching the stream's revision value space.
    entity_revision: i64,
    /// Version-gated trailing LONG following the revision stamp, retained
    /// verbatim; absent in older streams, a small non-negative per-entity
    /// change counter when present.
    trailing_field: Option<i64>,
}

native_record! {
    /// Parameter interval stored by one tolerant ASM coedge.
    TolerantCoedgeParameters, tolerant_coedge_parameters, "tolerant-coedge-parameters",
    /// Source SAB record index.
    record_index,
    /// Solved B-rep coedge carrying the tolerant interval.
    coedge: cadmpeg_ir::ids::CoedgeId,
    /// Native start and end parameters following the base coedge fields.
    parameter_range: cadmpeg_ir::units::FiniteVector<2>,
    /// Release-selected fixed fields following the parameter interval.
    extension: crate::brep::records::TolerantCoedgeExtension [serde(default)],
}

/// Release-selected fixed fields following a tolerant-coedge parameter interval.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case", tag = "layout", deny_unknown_fields)]
pub enum TolerantCoedgeExtension {
    /// Releases below 215 have no fixed extension fields.
    None {},
    /// Releases 215 through 219 carry one nullable entity reference.
    Reference {
        /// Referenced record index; `None` is the native null reference.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        target: Option<i64>,
    },
    /// Modern releases carry no embedded tolerant-curve payload.
    Empty {
        /// Nullable record reference preceding the zero selector.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        target: Option<i64>,
    },
    /// Modern releases carry one balanced embedded tolerant-curve payload.
    EmbeddedCurve {
        /// Nullable record reference preceding the one selector.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        target: Option<i64>,
        /// Whether the embedded intcurve is evaluated with parameter negation.
        curve_reversed: bool,
        /// Number of tokens inside the balanced outer subtype delimiters.
        payload_token_count: u32,
        /// Optional parameter interval following the embedded subtype.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        parameter_range: Option<cadmpeg_ir::units::FiniteVector<2>>,
    },
}

impl Default for TolerantCoedgeExtension {
    fn default() -> Self {
        Self::None {}
    }
}

native_record! {
    /// Zero-payload ASM surface sentinel whose shape is supplied only by tessellation attributes.
    MeshSurfaceSentinel, mesh_surface_sentinel, "mesh-surface-sentinel",
    /// Source SAB record index.
    record_index,
    /// Unknown exact-surface placeholder emitted for the sentinel record.
    surface: cadmpeg_ir::ids::SurfaceId,
}

/// Native side classification stored on an ASM wire record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WireSide {
    /// Wire bounds the inside side.
    In,
    /// Wire bounds the outside side.
    Out,
}

native_record! {
    /// Native wire record projected onto one neutral-IR shell.
    WireTopology, wire_topology, "wire-topology",
    /// Source SAB record index.
    record_index,
    /// Neutral shell containing the wire.
    shell: cadmpeg_ir::ids::ShellId,
    /// Edge ring or isolated vertex owned by the native wire.
    members: crate::brep::records::WireMembers [serde(flatten)],
    /// Native side classification.
    side: crate::brep::records::WireSide,
}

/// Mutually exclusive native wire members.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "WireMembersWire")]
pub enum WireMembers {
    /// Ordered edges reached from the first coedge; empty when none resolve.
    Edges(Vec<EdgeId>),
    /// Isolated vertex of a wire with no first coedge.
    Vertex(VertexId),
}

impl WireMembers {
    /// Ordered edge membership, empty for an isolated vertex.
    #[must_use]
    pub fn edges(&self) -> &[EdgeId] {
        match self {
            Self::Edges(edges) => edges,
            Self::Vertex(_) => &[],
        }
    }

    /// Isolated vertex membership.
    #[must_use]
    pub fn free_vertex(&self) -> Option<&VertexId> {
        match self {
            Self::Edges(_) => None,
            Self::Vertex(vertex) => Some(vertex),
        }
    }
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct WireMembersWire {
    /// Ordered edges reached from the first coedge; empty when none resolve.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    edges: Vec<EdgeId>,
    /// Isolated vertex of a wire with no first coedge.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_free_vertex"
    )]
    free_vertex: Option<VertexId>,
}

impl Serialize for WireMembers {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        let mut map = serializer.serialize_map(None)?;
        match self {
            Self::Edges(edges) if !edges.is_empty() => map.serialize_entry("edges", edges)?,
            Self::Edges(_) => {}
            Self::Vertex(vertex) => map.serialize_entry("free_vertex", vertex)?,
        }
        map.end()
    }
}

impl TryFrom<WireMembersWire> for WireMembers {
    type Error = &'static str;

    fn try_from(wire: WireMembersWire) -> Result<Self, Self::Error> {
        match wire.free_vertex {
            None => Ok(Self::Edges(wire.edges)),
            Some(vertex) if wire.edges.is_empty() => Ok(Self::Vertex(vertex)),
            Some(_) => Err("wire edges and free_vertex are mutually exclusive"),
        }
    }
}

native_record! {
    /// Native Design-join key stored on one ASM body record.
    BodyNativeKey, body_native_key, "body-native-key",
    /// Source SAB body record index.
    record_index,
    /// Solved body carrying the key.
    body: cadmpeg_ir::ids::BodyId,
    /// Zero-based body-record position within the BREP blob.
    body_ordinal: u32,
    /// Basename of the BREP blob containing this body.
    source_brep: Option<String> [serde(default, skip_serializing_if = "Option::is_none")],
    /// Non-negative Design-join key; absence is the native `-1` null value.
    asm_body_key: Option<u64> [serde(default, skip_serializing_if = "Option::is_none")],
}

native_record! {
    /// Native rotation, reflection, and shear classifications on an ASM transform.
    TransformHints, transform_hints, "transform-hints",
    /// Source SAB transform record index.
    record_index,
    /// Solved body referencing the transform record.
    body: cadmpeg_ir::ids::BodyId,
    /// The linear transform includes rotation.
    rotation: bool,
    /// The linear transform includes reflection.
    reflection: bool,
    /// The linear transform includes shear.
    shear: bool,
}

#[cfg(test)]
mod tests {
    use super::{EndpointSlot, TolerantCoedgeParameters, TolerantVertexTail, WireMembers};
    use cadmpeg_ir::ids::{EdgeId, VertexId};
    use serde::Deserialize;

    #[test]
    fn tolerant_vertex_tail_json_keeps_sentinel_and_refuses_nonfinite_value() {
        use serde_value::Value;

        let json = serde_json::json!({
            "id": "f3d:asm:tolerant-vertex-tail#1",
            "record_index": 1,
            "vertex": "f3d:brep:entity#1",
            "leading_tolerances": [-1.0, 0.03],
            "evaluated_slot": {"slot": "unset", "trailing": 0},
        });
        let tail: TolerantVertexTail = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(serde_json::to_value(&tail).unwrap(), json);

        let mut wire = serde_value::to_value(&tail).unwrap();
        let Value::Map(ref mut members) = wire else {
            panic!("native record wire must be a map");
        };
        members.insert(
            Value::String("leading_tolerances".into()),
            Value::Seq(vec![Value::F64(f64::INFINITY), Value::F64(-1.0)]),
        );
        let error = TolerantVertexTail::deserialize(wire).unwrap_err();
        assert!(error.to_string().contains("FiniteReal must be finite"));
    }

    #[test]
    fn tolerant_coedge_interval_json_refuses_nonfinite_endpoints() {
        use serde_value::Value;

        let json = serde_json::json!({
            "id": "f3d:asm:tolerant-coedge-parameters#1",
            "record_index": 1,
            "coedge": "f3d:brep:entity#1",
            "parameter_range": [-1.0, 2.0],
            "extension": {"layout": "none"},
        });
        let parameters: TolerantCoedgeParameters = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(serde_json::to_value(&parameters).unwrap(), json);

        let mut wire = serde_value::to_value(&parameters).unwrap();
        let Value::Map(ref mut members) = wire else {
            panic!("native record wire must be a map");
        };
        members.insert(
            Value::String("parameter_range".into()),
            Value::Seq(vec![Value::F64(f64::INFINITY), Value::F64(2.0)]),
        );
        let error = TolerantCoedgeParameters::deserialize(wire).unwrap_err();
        assert!(error.to_string().contains("finite"));
    }

    fn assert_empty_slot_refuses_extra_keys<T>(arena: &str, field: &str, record: &serde_json::Value)
    where
        T: serde::de::DeserializeOwned + serde::Serialize + std::fmt::Debug,
    {
        let mut document = serde_json::to_value(cadmpeg_ir::CadIr::empty()).unwrap();
        document["native"] = serde_json::json!({"f3d": {arena: [record.clone()]}});
        let admitted: cadmpeg_ir::CadIr = serde_json::from_value(document.clone()).unwrap();
        let typed: Vec<T> = admitted
            .native
            .namespace("f3d")
            .unwrap()
            .arena_as(arena)
            .unwrap();
        assert_eq!(&serde_json::to_value(&typed[0]).unwrap(), record);

        for extra in [
            serde_json::Value::Null,
            serde_json::json!(false),
            serde_json::json!(0),
            serde_json::json!(1.25),
            serde_json::json!("extra"),
            serde_json::json!([]),
            serde_json::json!({}),
        ] {
            let mut invalid = document.clone();
            invalid["native"]["f3d"][arena][0][field]["zz_bogus"] = extra;
            let admitted: cadmpeg_ir::CadIr = serde_json::from_value(invalid).unwrap();
            let error = admitted
                .native
                .namespace("f3d")
                .unwrap()
                .arena_as::<T>(arena)
                .unwrap_err()
                .to_string();
            assert!(error.contains("zz_bogus"), "{error}");
            assert!(error.contains(arena), "{error}");
            assert!(error.contains(record["id"].as_str().unwrap()), "{error}");
        }
    }

    #[test]
    fn absent_vertex_tolerance_refuses_extra_keys_after_document_admission() {
        assert_empty_slot_refuses_extra_keys::<super::TolerantVertexTail>(
            "tolerant_vertex_tails",
            "evaluated_slot",
            &serde_json::json!({
                "id": "f3d:asm:tolerant-vertex-tail#1",
                "record_index": 1,
                "vertex": "f3d:brep:entity#1",
                "leading_tolerances": [-1.0, -1.0],
                "evaluated_slot": {"slot": "absent"},
            }),
        );
    }

    #[test]
    fn absent_coedge_extension_refuses_extra_keys_after_document_admission() {
        assert_empty_slot_refuses_extra_keys::<super::TolerantCoedgeParameters>(
            "tolerant_coedge_parameters",
            "extension",
            &serde_json::json!({
                "id": "f3d:asm:tolerant-coedge-parameters#1",
                "record_index": 1,
                "coedge": "f3d:brep:entity#1",
                "parameter_range": [0.0, 1.0],
                "extension": {"layout": "none"},
            }),
        );
    }

    #[test]
    fn tolerant_coedge_curve_sense_requires_the_current_wire_name() {
        let extension = super::TolerantCoedgeExtension::EmbeddedCurve {
            target: None,
            curve_reversed: true,
            payload_token_count: 0,
            parameter_range: None,
        };
        let wire = serde_value::to_value(&extension).unwrap();
        assert_eq!(
            super::TolerantCoedgeExtension::deserialize(wire.clone()).unwrap(),
            extension
        );
        let serde_value::Value::Map(mut fields) = wire else {
            panic!("extension map")
        };
        let value = fields
            .remove(&serde_value::Value::String("curve_reversed".into()))
            .unwrap();
        fields.insert(serde_value::Value::String("flag".into()), value);
        let error = super::TolerantCoedgeExtension::deserialize(serde_value::Value::Map(fields))
            .unwrap_err();
        assert!(error.to_string().contains("curve_reversed"));
    }

    #[test]
    fn body_native_key_requires_explicit_body_ordinal() {
        let key = super::BodyNativeKey {
            source_namespace: super::identity::NativeRecordNamespace::new(crate::asm_format!(
                "f3d"
            )),
            record_index: 17,
            body: cadmpeg_ir::ids::BodyId::mint("f3d:brep:entity#17").unwrap(),
            body_ordinal: 0,
            source_brep: Some("Body1.sab".into()),
            asm_body_key: None,
        };
        let wire = serde_value::to_value(&key).unwrap();
        assert_eq!(
            super::BodyNativeKey::deserialize(wire.clone()).unwrap(),
            key
        );
        let serde_value::Value::Map(mut fields) = wire else {
            panic!("record map")
        };
        assert_eq!(
            fields.remove(&serde_value::Value::String("body_ordinal".into())),
            Some(serde_value::Value::U32(0))
        );
        let error = super::BodyNativeKey::deserialize(serde_value::Value::Map(fields)).unwrap_err();
        assert!(error.to_string().contains("body_ordinal"));
    }

    #[test]
    fn endpoint_slot_preserves_numeric_wire_and_rejects_other_indices() {
        for (slot, code) in [(EndpointSlot::Start, 0), (EndpointSlot::End, 1)] {
            let wire = serde_value::to_value(slot).expect("serialize endpoint");
            assert_eq!(wire, serde_value::Value::U8(code));
            assert_eq!(
                EndpointSlot::deserialize(wire).expect("read endpoint"),
                slot
            );
        }
        for code in [2, u8::MAX] {
            let error = EndpointSlot::deserialize(serde_value::Value::U8(code))
                .expect_err("undefined endpoint");
            assert!(error.to_string().contains("endpoint_index"));
        }
    }

    #[test]
    fn wire_members_preserve_flat_fields_and_reject_mixed_membership() {
        use serde_value::Value;

        let edge = EdgeId::mint("asm:test:edge#1").expect("edge id");
        let vertex = VertexId::mint("asm:test:vertex#2").expect("vertex id");
        let edge_value = serde_value::to_value(&edge).expect("edge wire");
        let vertex_value = serde_value::to_value(&vertex).expect("vertex wire");
        for (members, fields) in [
            (WireMembers::Edges(Vec::new()), Vec::new()),
            (
                WireMembers::Edges(vec![edge]),
                vec![(
                    Value::String("edges".into()),
                    Value::Seq(vec![edge_value.clone()]),
                )],
            ),
            (
                WireMembers::Vertex(vertex),
                vec![(Value::String("free_vertex".into()), vertex_value.clone())],
            ),
        ] {
            let wire = Value::Map(fields.into_iter().collect());
            assert_eq!(
                serde_value::to_value(&members).expect("serialize members"),
                wire
            );
            assert_eq!(
                WireMembers::deserialize(wire).expect("read members"),
                members
            );
        }
        let mixed = Value::Map(
            [
                (Value::String("edges".into()), Value::Seq(vec![edge_value])),
                (Value::String("free_vertex".into()), vertex_value),
            ]
            .into_iter()
            .collect(),
        );
        let error = WireMembers::deserialize(mixed).expect_err("mixed wire members");
        assert!(error.to_string().contains("edges and free_vertex"));
    }
    /// `free_vertex` is written by omission, so absence is the one spelling of
    /// an edge-ring wire and a stated `null` is refused by name.
    #[test]
    fn a_stated_null_free_vertex_is_refused() {
        let error = serde_json::from_str::<WireMembers>("{\"free_vertex\":null}")
            .expect_err("a stated null is not a second spelling of absence")
            .to_string();
        assert!(
            error.contains("this key states a value or is left out; it does not state null"),
            "{error}"
        );
        assert_eq!(
            serde_json::from_str::<WireMembers>("{}").expect("an omitted free_vertex"),
            WireMembers::Edges(Vec::new())
        );
    }

    /// `WireMembers` writes a map keyed by `edges` or `free_vertex`, and the
    /// `JsonSchema` derive reads `#[serde(try_from = "WireMembersWire")]`, so
    /// the published schema states those two properties rather than the
    /// neutral enum's `Edges` and `Vertex` arms.
    #[cfg(feature = "schema")]
    #[test]
    fn the_wire_member_schema_states_the_keys_the_writer_states() {
        let schema =
            serde_json::to_value(schemars::schema_for!(WireMembers)).expect("members schema");
        let properties: std::collections::BTreeSet<String> = schema["properties"]
            .as_object()
            .expect("the members schema states properties")
            .keys()
            .cloned()
            .collect();
        let edge = EdgeId::mint("asm:test:edge#1").expect("edge id");
        let vertex = VertexId::mint("asm:test:vertex#2").expect("vertex id");
        let written: std::collections::BTreeSet<String> =
            [WireMembers::Edges(vec![edge]), WireMembers::Vertex(vertex)]
                .iter()
                .flat_map(|members| {
                    serde_json::to_value(members)
                        .expect("serialize members")
                        .as_object()
                        .expect("members write a map")
                        .keys()
                        .cloned()
                        .collect::<Vec<_>>()
                })
                .collect();
        assert_eq!(properties, written);
    }

    /// `target` carries no `skip_serializing_if`, so its writer states `null`
    /// for the native null reference and the reader admits that spelling.
    #[test]
    fn a_stated_null_tolerant_coedge_target_is_the_native_null_reference() {
        assert_eq!(
            serde_json::from_str::<super::TolerantCoedgeExtension>(
                "{\"layout\":\"reference\",\"target\":null}"
            )
            .expect("a stated null target"),
            super::TolerantCoedgeExtension::Reference { target: None }
        );
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_containment, FaceContainment, "containment");
cadmpeg_core::named_optional_field!(deserialize_trailing, i64, "trailing");
cadmpeg_core::named_optional_field!(deserialize_free_vertex, VertexId, "free_vertex");

mod identity_rewrite;