From 73de5a6f37da0e9c78ca4c0fb9886e1211150642 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 07:18:15 +0000 Subject: [PATCH] Add attribute classes, codes above 160 and LNAM helpers (#49) Items 1-3 of #49: - S57AttributeClass (Feature, National, Spatial, Cartographic) and S57AttributeDefinition.Class/IsNational, from the Class column of GDAL's s57attributes.csv (S-57 Appendix A, Chapter 2). The generator writes it and the IHO table is regenerated from GDAL v3.12.0; the Inland ENC table is unchanged. The AML tables aren't regenerated: their own attributes (20000 and up) take the constructor's Feature default, and the IHO attributes they include keep their IHO class. - S57ObjectCode gains ARCSLN (161), ASLXIS (162) and NEWOBJ (163), and the cartographic classes 500-504 as CartographicArea ($AREAS), CartographicLine ($LINES), CartographicSymbol ($CSYMB), CartographicCompass ($COMPS) and CartographicText ($TEXTS), since '$' can't appear in an identifier. The writer's DSSI counts use code ranges, so they're unchanged. - S57LongName.FromLnam, ToLnam, TryWriteLnam and LnamLength pack and unpack the 8-byte binary LNAM; the reader and writer now use them. S57RecordName.FromLongName(S57LongName) keeps a FIDN above int.MaxValue as the int with the same bits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VAmJZEwPd4NoCtWnEjgT9t --- docs/reading-aml-data-sets.md | 6 + docs/reading-s57-charts.md | 5 + scripts/GenerateObjectCatalogues.cs | 30 +++- src/EncDotNet.S57/S57AttributeClass.cs | 43 ++++++ src/EncDotNet.S57/S57AttributeDefinition.cs | 26 +++- src/EncDotNet.S57/S57DocumentReader.cs | 14 +- src/EncDotNet.S57/S57DocumentWriter.cs | 4 +- src/EncDotNet.S57/S57FieldEncoder.cs | 8 ++ src/EncDotNet.S57/S57LongName.cs | 76 ++++++++++ src/EncDotNet.S57/S57ObjectCatalogue.Iho.g.cs | 34 ++--- src/EncDotNet.S57/S57ObjectCode.cs | 47 +++++++ src/EncDotNet.S57/S57RecordName.cs | 29 ++++ tests/EncDotNet.UnitTests/S57LongNameTests.cs | 132 ++++++++++++++++++ .../S57ObjectCatalogueTests.cs | 102 +++++++++++++- 14 files changed, 515 insertions(+), 41 deletions(-) create mode 100644 src/EncDotNet.S57/S57AttributeClass.cs create mode 100644 tests/EncDotNet.UnitTests/S57LongNameTests.cs diff --git a/docs/reading-aml-data-sets.md b/docs/reading-aml-data-sets.md index 694b52e..86a6b53 100644 --- a/docs/reading-aml-data-sets.md +++ b/docs/reading-aml-data-sets.md @@ -127,6 +127,12 @@ Acronyms of AML classes and attributes are lower case, such as `atsctl` and `databa`, and acronym lookups are case-sensitive. The catalogues hold codes, acronyms, names, attribute types and enumerated values, but not definitions. +`S57AttributeDefinition.Class` says whether an attribute is a feature, +national, spatial or cartographic attribute, and `IsNational` whether a +feature stores it in `NATF` rather than `ATTF`. The AML catalogues don't +classify their own attributes, so codes 20000 and up are feature attributes; +the IHO attributes they include keep their IHO class. + ## Use the AML data set view `AmlDataSet` is a view over the `S57Chart` of an AML cell. It doesn't copy the diff --git a/docs/reading-s57-charts.md b/docs/reading-s57-charts.md index 64f30fb..c14bc55 100644 --- a/docs/reading-s57-charts.md +++ b/docs/reading-s57-charts.md @@ -170,6 +170,11 @@ foreach (S57TypedFeature feature in chart.AllFeatures.Values) `S57Document.GetFeatureRecord(S57LongName)` does the same on a document without building a chart, but searches every record on each call. +In the binary encoding the FFPT pointer packs the long name into one 8-byte +`LNAM` subfield. `S57LongName.FromLnam` and `ToLnam` convert between the two, +and `S57RecordName.FromLongName(S57LongName)` gives the record name of a +feature with that long name. + ## Apply update cells A base cell (`.000`) is followed by update cells (`.001`, `.002`, and so on) diff --git a/scripts/GenerateObjectCatalogues.cs b/scripts/GenerateObjectCatalogues.cs index 59180f2..8c61f76 100644 --- a/scripts/GenerateObjectCatalogues.cs +++ b/scripts/GenerateObjectCatalogues.cs @@ -12,7 +12,7 @@ // Source: the S-57 object catalogue tables GDAL ships with its S-57 driver // (ogr/ogrsf_frmts/s57/data in https://github.com/OSGeo/gdal, MIT licence): // s57objectclasses.csv object classes (code, name, acronym, class, primitives) -// s57attributes.csv attributes (code, name, acronym, type) +// s57attributes.csv attributes (code, name, acronym, type, class) // s57expectedinput.csv enumerated values (attribute code, ID, meaning) // GDAL derived them from the IHO S-57 Edition 3.1 Object Catalogue. Codes // 17000-19999 are the Inland ENC entries GDAL kept from its former @@ -20,8 +20,8 @@ // enumerations. Codes 20000 and up are AML entries and aren't used here. // // Without a data directory the script downloads the files from the GDAL tag -// below. Only codes, acronyms, names, classes, primitives, attribute types and -// enumerated values are written; definition text is never included. +// below. Only codes, acronyms, names, classes, primitives, attribute types, +// attribute classes and enumerated values are written; definition text is never included. // // Writes, in (default src/EncDotNet.S57): // S57ObjectCatalogue.Iho.g.cs codes 1-16999 @@ -51,7 +51,8 @@ int.Parse(row["Code"], CultureInfo.InvariantCulture), row["Acronym"].Trim(), Normalize(row["Attribute"]), - row["Attributetype"].Trim())) + row["Attributetype"].Trim(), + row["Class"].Trim())) .Where(row => row.Code > 0) .ToList(); @@ -155,6 +156,10 @@ public sealed partial class S57ObjectCatalogue foreach (var a in attributeList) { var head = $" new({a.Code}, {Literal(a.Acronym)}, {Literal(a.Name)}, {Type(a.Type)}"; + + // Feature is the constructor's default, so only the other classes are written. + var attributeClass = AttributeClass(a.Class, a.Code); + var tail = attributeClass == "Feature" ? ")" : $", attributeClass: S57AttributeClass.{attributeClass})"; if (values.TryGetValue(a.Code, out var list) && list.Count > 0) { builder.Append(head).Append(",\n [\n"); @@ -163,11 +168,11 @@ public sealed partial class S57ObjectCatalogue builder.Append(CultureInfo.InvariantCulture, $" new({value.Code}, {Literal(value.Name)}),\n"); } - builder.Append(" ]),\n"); + builder.Append(" ]").Append(tail).Append(",\n"); } else { - builder.Append(head).Append("),\n"); + builder.Append(head).Append(tail).Append(",\n"); } } @@ -210,6 +215,17 @@ static void Rename(List rows, int code, string from, string to) _ => "S57AttributeType.Unknown", }; +// The Class column of s57attributes.csv: S-57 Edition 3.1, Appendix A, Chapter 2 §2.2 (F), +// §2.3 (N) and §2.4 (S); $ marks the cartographic feature attributes. +static string AttributeClass(string value, int code) => value switch +{ + "F" => "Feature", + "N" => "National", + "S" => "Spatial", + "$" => "Cartographic", + _ => throw new InvalidDataException($"Attribute {code} has an unknown class '{value}'."), +}; + static string Primitives(string value) { var flags = new List(); @@ -336,6 +352,6 @@ static List ParseCsvLine(string line) record ObjectClassRow(int Code, string Acronym, string Name, string Category, string Primitives); -record AttributeRow(int Code, string Acronym, string Name, string Type); +record AttributeRow(int Code, string Acronym, string Name, string Type, string Class); record ValueRow(int Code, string Name); diff --git a/src/EncDotNet.S57/S57AttributeClass.cs b/src/EncDotNet.S57/S57AttributeClass.cs new file mode 100644 index 0000000..0dd715a --- /dev/null +++ b/src/EncDotNet.S57/S57AttributeClass.cs @@ -0,0 +1,43 @@ +namespace EncDotNet.S57; + +/// +/// The class of an S-57 attribute, as given in an object catalogue. +/// +/// +/// +/// S-57 Edition 3.1, Appendix A, Chapter 2 groups attributes into feature object attributes +/// (§2.2), national language attributes (§2.3) and spatial and meta object attributes (§2.4). +/// The catalogue tables mark the feature object attributes used for cartographic presentation, +/// whose acronyms start with $, as a fourth class. +/// +/// +/// The class decides where a feature record stores an attribute: national attributes are +/// encoded in the NATF field, at the data set's national lexical level (NALL), and +/// the other attributes of a feature in the ATTF field (S-57 Part 3, clauses 4.4, 4.5, +/// 7.6.3 and 7.6.4). Spatial attributes are encoded in the ATTV field of a vector record +/// (S-57 Part 3, clauses 5.1.2 and 7.7.1.2). +/// +/// +public enum S57AttributeClass +{ + /// + /// A feature object attribute (F), such as COLOUR, encoded in ATTF. + /// + Feature = 0, + + /// + /// A national language attribute (N), such as NOBJNM, encoded in NATF. + /// + National, + + /// + /// A spatial object attribute (S), such as POSACC, encoded in a vector + /// record's ATTV. + /// + Spatial, + + /// + /// A cartographic attribute ($), such as $SCODE, encoded in ATTF. + /// + Cartographic, +} diff --git a/src/EncDotNet.S57/S57AttributeDefinition.cs b/src/EncDotNet.S57/S57AttributeDefinition.cs index c322357..67d6e2d 100644 --- a/src/EncDotNet.S57/S57AttributeDefinition.cs +++ b/src/EncDotNet.S57/S57AttributeDefinition.cs @@ -12,13 +12,15 @@ internal S57AttributeDefinition( string acronym, string name, S57AttributeType type, - IReadOnlyList? values = null) + IReadOnlyList? values = null, + S57AttributeClass attributeClass = S57AttributeClass.Feature) { Code = code; Acronym = acronym; Name = name; Type = type; Values = values ?? []; + Class = attributeClass; } /// Gets the attribute code, as it's encoded in ATTL. @@ -34,6 +36,28 @@ internal S57AttributeDefinition( /// Gets the type of the attribute's value. public S57AttributeType Type { get; } + /// + /// Gets the class of the attribute: feature, national, spatial or cartographic. + /// + /// + /// The class comes from S-57 Edition 3.1, Appendix A, Chapter 2. The AML catalogues don't + /// classify their attributes (codes 20000 and up), so those attributes are + /// ; the IHO attributes the AML catalogues include + /// keep their IHO class. + /// + public S57AttributeClass Class { get; } + + /// + /// Gets a value indicating whether the attribute is a national attribute, which a feature + /// record stores in its NATF field rather than its ATTF field (S-57 Part 3, + /// clause 4.5). + /// + /// + /// National attributes hold text in a national language, such as NOBJNM, and may use + /// any lexical level; see . + /// + public bool IsNational => Class == S57AttributeClass.National; + /// /// Gets the predefined values of an or /// attribute, in code order. diff --git a/src/EncDotNet.S57/S57DocumentReader.cs b/src/EncDotNet.S57/S57DocumentReader.cs index 071d88e..465542a 100644 --- a/src/EncDotNet.S57/S57DocumentReader.cs +++ b/src/EncDotNet.S57/S57DocumentReader.cs @@ -1101,18 +1101,8 @@ private static S57RecordName DecomposeNameField(ReadOnlySpan data) /// /// Decomposes a LNAM composite subfield (8 bytes: AGEN(2) + FIDN(4) + FIDS(2)) into an S57LongName. /// - private static S57LongName DecomposeLongNameField(ReadOnlySpan data) - { - if (data.Length < 8) - { - return default; - } - - var agen = BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(0, 2)); - var fidn = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(2, 4)); - var fids = BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(6, 2)); - return new S57LongName(agen, fidn, fids); - } + private static S57LongName DecomposeLongNameField(ReadOnlySpan data) => + data.Length < S57LongName.LnamLength ? default : S57LongName.FromLnam(data[..S57LongName.LnamLength]); /// /// Parses an update control field (FSPC, FFPC, VRPC, or SGCC) from a record. diff --git a/src/EncDotNet.S57/S57DocumentWriter.cs b/src/EncDotNet.S57/S57DocumentWriter.cs index 8d661d1..cf16a95 100644 --- a/src/EncDotNet.S57/S57DocumentWriter.cs +++ b/src/EncDotNet.S57/S57DocumentWriter.cs @@ -441,9 +441,7 @@ private static Iso8211Record FeatureRecord( encoder.Begin($"{S57FieldTags.FFPT} ({name})"); foreach (var pointer in feature.FeaturePointers) { - encoder.B12(pointer.Name.AgencyCode, S57SubfieldNames.AGEN) - .B14(pointer.Name.FeatureId, S57SubfieldNames.FIDN) - .B12(pointer.Name.FeatureSubdivision, S57SubfieldNames.FIDS) + encoder.Lnam(pointer.Name) .B11((byte)pointer.Relationship, S57SubfieldNames.RIND) .Text(pointer.Comment, S57SubfieldNames.COMT, S57FieldEncoder.Latin1); } diff --git a/src/EncDotNet.S57/S57FieldEncoder.cs b/src/EncDotNet.S57/S57FieldEncoder.cs index a82b437..12f4f32 100644 --- a/src/EncDotNet.S57/S57FieldEncoder.cs +++ b/src/EncDotNet.S57/S57FieldEncoder.cs @@ -74,6 +74,14 @@ public S57FieldEncoder B14(long value, string subfield) return this; } + /// Writes a binary LNAM subfield (B(64), S-57 Part 3, clause 4.3). + public S57FieldEncoder Lnam(S57LongName name) + { + name.TryWriteLnam(_buffer.GetSpan(S57LongName.LnamLength)); + _buffer.Advance(S57LongName.LnamLength); + return this; + } + /// Writes a b24 subfield. public S57FieldEncoder B24(int value) { diff --git a/src/EncDotNet.S57/S57LongName.cs b/src/EncDotNet.S57/S57LongName.cs index c8f4bdb..33be98d 100644 --- a/src/EncDotNet.S57/S57LongName.cs +++ b/src/EncDotNet.S57/S57LongName.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using System.Globalization; namespace EncDotNet.S57; @@ -7,10 +8,18 @@ namespace EncDotNet.S57; /// object and that feature-to-feature pointers use to refer to it (S-57 Part 3, 4.3 and 4.6). /// /// +/// /// A long name is the feature's producing agency (AGEN), feature identification number (FIDN) /// and feature identification subdivision (FIDS), from its FOID field. Unlike a record's /// (RCNM and RCID), it stays the same across editions and updates, /// which is why FFPT pointers use it as their foreign key. +/// +/// +/// In the binary implementation an FFPT pointer encodes the long name as a single 64-bit +/// LNAM subfield: AGEN (b12), FIDN (b14) and FIDS (b12), each +/// little-endian (S-57 Part 3, clauses 4.3, 7.2.2.1 and 7.6.6). Use , +/// and to convert between the two. +/// /// public readonly record struct S57LongName { @@ -36,6 +45,73 @@ public S57LongName(ushort agencyCode, uint featureId, ushort featureSubdivision) /// Gets the feature identification subdivision (FIDS). public ushort FeatureSubdivision { get; init; } + /// + /// The length of a binary LNAM subfield, in bytes. + /// + public const int LnamLength = 8; + + /// + /// Decodes a long name from a binary LNAM subfield (S-57 Part 3, clause 4.3). + /// + /// + /// The bytes of the subfield: AGEN, FIDN and FIDS, each little-endian. + /// + /// The long name. + /// + /// isn't bytes long. + /// + public static S57LongName FromLnam(ReadOnlySpan lnam) + { + if (lnam.Length != LnamLength) + { + throw new ArgumentException( + $"An LNAM subfield is {LnamLength} bytes long, but {lnam.Length} bytes were given.", + nameof(lnam)); + } + + return new S57LongName( + BinaryPrimitives.ReadUInt16LittleEndian(lnam), + BinaryPrimitives.ReadUInt32LittleEndian(lnam[2..]), + BinaryPrimitives.ReadUInt16LittleEndian(lnam[6..])); + } + + /// + /// Encodes the long name as a binary LNAM subfield (S-57 Part 3, clause 4.3). + /// + /// + /// A new array of bytes: AGEN, FIDN and FIDS, each little-endian. + /// + public byte[] ToLnam() + { + var lnam = new byte[LnamLength]; + TryWriteLnam(lnam); + return lnam; + } + + /// + /// Tries to encode the long name as a binary LNAM subfield (S-57 Part 3, clause 4.3). + /// + /// + /// The span to write to. The first bytes receive AGEN, FIDN and + /// FIDS, each little-endian. + /// + /// + /// true when the long name was written; false when + /// is shorter than bytes, in which case nothing is written. + /// + public bool TryWriteLnam(Span destination) + { + if (destination.Length < LnamLength) + { + return false; + } + + BinaryPrimitives.WriteUInt16LittleEndian(destination, AgencyCode); + BinaryPrimitives.WriteUInt32LittleEndian(destination[2..], FeatureId); + BinaryPrimitives.WriteUInt16LittleEndian(destination[6..], FeatureSubdivision); + return true; + } + /// public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"AGEN={AgencyCode}, FIDN={FeatureId}, FIDS={FeatureSubdivision}"); diff --git a/src/EncDotNet.S57/S57ObjectCatalogue.Iho.g.cs b/src/EncDotNet.S57/S57ObjectCatalogue.Iho.g.cs index 076118c..f201e7e 100644 --- a/src/EncDotNet.S57/S57ObjectCatalogue.Iho.g.cs +++ b/src/EncDotNet.S57/S57ObjectCatalogue.Iho.g.cs @@ -983,8 +983,8 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => [ new(1, "expanded/condensed"), new(2, "standard"), - ]), - new(74, "$CHARS", "Character specification", CodedString), + ], attributeClass: S57AttributeClass.Cartographic), + new(74, "$CHARS", "Character specification", CodedString, attributeClass: S57AttributeClass.Cartographic), new(75, "COLOUR", "Colour", List, [ new(1, "white"), @@ -1011,7 +1011,7 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(6, "border stripes"), ]), new(77, "COMCHA", "Communication channel", CodedString), - new(78, "$CSIZE", "Compass size", Float), + new(78, "$CSIZE", "Compass size", Float, attributeClass: S57AttributeClass.Cartographic), new(79, "CPDATE", "Compilation date", CodedString), new(80, "CSCALE", "Compilation scale", Integer), new(81, "CONDTN", "Condition", Enumerated, @@ -1127,13 +1127,13 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(1, "centre justified"), new(2, "right justified"), new(3, "left justified"), - ]), + ], attributeClass: S57AttributeClass.Cartographic), new(105, "$JUSTV", "Justification - vertical", Enumerated, [ new(1, "bottom justified"), new(2, "centre justified"), new(3, "top justified"), - ]), + ], attributeClass: S57AttributeClass.Cartographic), new(106, "LIFCAP", "Lifting capacity", Float), new(107, "LITCHR", "Light characteristic", Enumerated, [ @@ -1349,8 +1349,8 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(5, "passage survey"), new(6, "remotely sensed"), ]), - new(154, "$SCALE", "Symbol scaling factor", Float), - new(155, "$SCODE", "Symbolization code", CodedString), + new(154, "$SCALE", "Symbol scaling factor", Float, attributeClass: S57AttributeClass.Cartographic), + new(155, "$SCODE", "Symbolization code", CodedString, attributeClass: S57AttributeClass.Cartographic), new(156, "TECSOU", "Technique of sounding measurement", List, [ new(1, "found by echo-sounder"), @@ -1368,7 +1368,7 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(13, "swept by side-scan sonar"), new(14, "computer generated"), ]), - new(157, "$TXSTR", "Text string", FreeText), + new(157, "$TXSTR", "Text string", FreeText, attributeClass: S57AttributeClass.Cartographic), new(158, "TXTDSC", "Textual description", FreeText), new(159, "TS_TSP", "Tidal stream - panel values", CodedString), new(160, "TS_TSV", "Tidal stream, current - time series values", CodedString), @@ -1395,7 +1395,7 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(1, "darkest blue"), new(2, "medium blue"), new(3, "lightest blue"), - ]), + ], attributeClass: S57AttributeClass.Cartographic), new(171, "TOPSHP", "Topmark/daymark shape", Enumerated, [ new(1, "cone, point up"), @@ -1510,11 +1510,11 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(190, "CLSDEF", "Object class definition", FreeText), new(191, "CLSNAM", "Object class name", FreeText), new(192, "SYMINS", "Symbol instruction", FreeText), - new(300, "NINFOM", "Information in national language", FreeText), - new(301, "NOBJNM", "Object name in national language", FreeText), - new(302, "NPLDST", "Pilot district in national language", FreeText), - new(303, "$NTXST", "Text string in national language", FreeText), - new(304, "NTXTDS", "Textual description in national language", FreeText), + new(300, "NINFOM", "Information in national language", FreeText, attributeClass: S57AttributeClass.National), + new(301, "NOBJNM", "Object name in national language", FreeText, attributeClass: S57AttributeClass.National), + new(302, "NPLDST", "Pilot district in national language", FreeText, attributeClass: S57AttributeClass.National), + new(303, "$NTXST", "Text string in national language", FreeText, attributeClass: S57AttributeClass.National), + new(304, "NTXTDS", "Textual description in national language", FreeText, attributeClass: S57AttributeClass.National), new(400, "HORDAT", "Horizontal datum", Enumerated, [ new(1, "WGS 72"), @@ -1617,8 +1617,8 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(98, ""), new(99, "South Asia"), new(100, "Tananarive Observatory 1925"), - ]), - new(401, "POSACC", "Positional Accuracy", Float), + ], attributeClass: S57AttributeClass.Spatial), + new(401, "POSACC", "Positional Accuracy", Float, attributeClass: S57AttributeClass.Spatial), new(402, "QUAPOS", "Quality of position", Enumerated, [ new(1, "surveyed"), @@ -1632,6 +1632,6 @@ private static S57AttributeDefinition[] CreateIhoAttributes() => new(9, "estimated"), new(10, "precisely known"), new(11, "calculated"), - ]), + ], attributeClass: S57AttributeClass.Spatial), ]; } diff --git a/src/EncDotNet.S57/S57ObjectCode.cs b/src/EncDotNet.S57/S57ObjectCode.cs index a28b57d..cab39b1 100644 --- a/src/EncDotNet.S57/S57ObjectCode.cs +++ b/src/EncDotNet.S57/S57ObjectCode.cs @@ -3,6 +3,22 @@ namespace EncDotNet.S57; /// /// S-57 object class codes (OBJL) as defined in IHO S-57 Appendix A - Object Catalogue. /// +/// +/// +/// Each member is named after the class's acronym, except the cartographic object classes +/// (codes 500 and up). Their acronyms start with $, which a C# identifier can't contain, +/// so their members are named Cartographic followed by the class name: +/// ($AREAS), ($LINES), +/// ($CSYMB), +/// ($COMPS) and ($TEXTS). Use +/// to get any code's acronym. +/// +/// +/// A data set can hold codes this enumeration doesn't name, such as the Inland ENC (17000 and up) +/// and AML (20000 and up) classes; look those up in the data set's +/// . +/// +/// public enum S57ObjectCode { // --- Geo Object Classes --- @@ -487,6 +503,19 @@ public enum S57ObjectCode /// Tidal stream, flood/ebb (TS_FEB). TS_FEB = 160, + /// Archipelagic sea lane (ARCSLN), added by a supplement to S-57 Edition 3.1. + ARCSLN = 161, + + /// Archipelagic sea lane axis (ASLXIS), added by a supplement to S-57 Edition 3.1. + ASLXIS = 162, + + /// + /// New object (NEWOBJ), added by a supplement to S-57 Edition 3.1 to encode object classes + /// the catalogue doesn't define, such as virtual AIS aids to navigation (S-57 Appendix B.1, + /// Annex A). + /// + NEWOBJ = 163, + // --- Meta Object Classes --- /// Accuracy of data (M_ACCY). @@ -538,4 +567,22 @@ public enum S57ObjectCode /// Stacked on/stacked under (C_STAC). C_STAC = 402, + + // --- Cartographic Object Classes --- + // The acronyms start with '$', which an identifier can't contain; see the remarks above. + + /// Cartographic area ($AREAS). + CartographicArea = 500, + + /// Cartographic line ($LINES). + CartographicLine = 501, + + /// Cartographic symbol ($CSYMB). + CartographicSymbol = 502, + + /// Compass ($COMPS). + CartographicCompass = 503, + + /// Text ($TEXTS). + CartographicText = 504, } diff --git a/src/EncDotNet.S57/S57RecordName.cs b/src/EncDotNet.S57/S57RecordName.cs index 3da6bc5..185b730 100644 --- a/src/EncDotNet.S57/S57RecordName.cs +++ b/src/EncDotNet.S57/S57RecordName.cs @@ -27,6 +27,11 @@ public readonly record struct S57RecordName /// /// Gets the feature identification number (FIDN). /// + /// + /// FIDN is an unsigned 32-bit number (b14), so a value above + /// is held as the negative with the same bits. Use + /// for the unsigned value. + /// public int FeatureId { get; init; } /// @@ -49,6 +54,10 @@ public static S57RecordName FromRcnmRcid(int rcnm, int rcid) /// /// Creates a record name from the long name values (AGEN, FIDN, FIDS). /// + /// The producing agency (AGEN). + /// The feature identification number (FIDN). + /// The feature identification subdivision (FIDS). + /// A record name with the long name values and no RCNM or RCID. public static S57RecordName FromLongName(int agencyCode, int featureId, int featureSubdivision) { return new S57RecordName @@ -59,6 +68,26 @@ public static S57RecordName FromLongName(int agencyCode, int featureId, int feat }; } + /// + /// Creates a record name from a feature's long name. + /// + /// The long name (AGEN, FIDN, FIDS). + /// A record name with the long name's values and no RCNM or RCID. + /// + /// A FIDN above is stored in as the + /// negative with the same bits, so gives back + /// for every long name other than all zeros. + /// + public static S57RecordName FromLongName(S57LongName longName) + { + return new S57RecordName + { + AgencyCode = longName.AgencyCode, + FeatureId = unchecked((int)longName.FeatureId), + FeatureSubdivision = longName.FeatureSubdivision + }; + } + /// /// Gets the feature's long name (AGEN, FIDN, FIDS), or null when the record has none, /// such as a vector record or a feature record without a FOID field. diff --git a/tests/EncDotNet.UnitTests/S57LongNameTests.cs b/tests/EncDotNet.UnitTests/S57LongNameTests.cs new file mode 100644 index 0000000..76cd96d --- /dev/null +++ b/tests/EncDotNet.UnitTests/S57LongNameTests.cs @@ -0,0 +1,132 @@ +using EncDotNet.S57; + +namespace EncDotNet.UnitTests; + +/// +/// Unit tests for and its conversions to and from LNAM and +/// . +/// +public class S57LongNameTests +{ + public static TheoryData LongNames => new() + { + { 540, 12345, 1 }, + { 0, 0, 0 }, + { ushort.MaxValue, uint.MaxValue, ushort.MaxValue }, + { 1, (uint)int.MaxValue, 1 }, + { 1, (uint)int.MaxValue + 1, 1 }, + { ushort.MaxValue, 1, 0 }, + { 0, 1, ushort.MaxValue }, + }; + + [Fact] + public void ToLnam_WritesAgenFidnFidsLittleEndian() + { + var name = new S57LongName(0x0102, 0x03040506, 0x0708); + + Assert.Equal([0x02, 0x01, 0x06, 0x05, 0x04, 0x03, 0x08, 0x07], name.ToLnam()); + } + + [Fact] + public void FromLnam_ReadsAgenFidnFidsLittleEndian() + { + // AGEN 550 (0x0226), FIDN 4294967294 (0xFFFFFFFE), FIDS 2 (0x0002). + byte[] lnam = [0x26, 0x02, 0xFE, 0xFF, 0xFF, 0xFF, 0x02, 0x00]; + + var name = S57LongName.FromLnam(lnam); + + Assert.Equal(new S57LongName(550, 4294967294, 2), name); + } + + [Theory] + [MemberData(nameof(LongNames))] + public void Lnam_RoundTrips(ushort agencyCode, uint featureId, ushort featureSubdivision) + { + var name = new S57LongName(agencyCode, featureId, featureSubdivision); + + var lnam = name.ToLnam(); + + Assert.Equal(S57LongName.LnamLength, lnam.Length); + Assert.Equal(name, S57LongName.FromLnam(lnam)); + } + + [Fact] + public void TryWriteLnam_WritesFirstEightBytes() + { + var name = new S57LongName(ushort.MaxValue, (uint)int.MaxValue + 1, 1); + var buffer = new byte[10]; + Array.Fill(buffer, (byte)0xAA); + + Assert.True(name.TryWriteLnam(buffer)); + + Assert.Equal([0xFF, 0xFF, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0xAA, 0xAA], buffer); + } + + [Fact] + public void TryWriteLnam_ShortDestination_ReturnsFalseAndWritesNothing() + { + var buffer = new byte[S57LongName.LnamLength - 1]; + + Assert.False(new S57LongName(1, 2, 3).TryWriteLnam(buffer)); + Assert.All(buffer, b => Assert.Equal(0, b)); + } + + [Theory] + [InlineData(0)] + [InlineData(7)] + [InlineData(9)] + public void FromLnam_WrongLength_Throws(int length) + { + Assert.Throws(() => S57LongName.FromLnam(new byte[length])); + } + + [Theory] + [MemberData(nameof(LongNames))] + public void RecordName_FromLongName_RoundTrips(ushort agencyCode, uint featureId, ushort featureSubdivision) + { + var name = new S57LongName(agencyCode, featureId, featureSubdivision); + + var recordName = S57RecordName.FromLongName(name); + + Assert.Equal(agencyCode, recordName.AgencyCode); + Assert.Equal(unchecked((int)featureId), recordName.FeatureId); + Assert.Equal(featureSubdivision, recordName.FeatureSubdivision); + Assert.Equal(0, recordName.RecordNameCode); + Assert.Equal(0, recordName.RecordId); + + // An all-zero long name reads back as no long name. + Assert.Equal(name == default ? null : name, recordName.LongName); + } + + [Fact] + public void RecordName_FromLongName_FidnAboveIntMaxValue_KeepsBits() + { + var recordName = S57RecordName.FromLongName(new S57LongName(1, uint.MaxValue, 1)); + + Assert.Equal(-1, recordName.FeatureId); + Assert.Equal(uint.MaxValue, recordName.LongName?.FeatureId); + } + + [Fact] + public void FeaturePointer_LongNameAtLimits_RoundTripsThroughWriter() + { + var cell = S57WriterTestCells.SmallCell(); + var index = cell.FeatureRecords.ToList().FindIndex(f => f.FeaturePointers.Count > 0); + var feature = cell.FeatureRecords[index]; + var target = new S57LongName(ushort.MaxValue, uint.MaxValue, ushort.MaxValue); + feature = feature with + { + FeaturePointers = [feature.FeaturePointers[0] with { Name = target }, .. feature.FeaturePointers.Skip(1)] + }; + cell = cell with + { + FeatureRecords = [.. cell.FeatureRecords.Take(index), feature, .. cell.FeatureRecords.Skip(index + 1)] + }; + + var written = S57DocumentWriter.Write(cell); + var reread = S57DocumentReader.Read(written); + + Assert.True(written.AsSpan().IndexOf(target.ToLnam()) >= 0); + Assert.Equal(target, reread.FeatureRecords[index].FeaturePointers[0].Name); + } +} diff --git a/tests/EncDotNet.UnitTests/S57ObjectCatalogueTests.cs b/tests/EncDotNet.UnitTests/S57ObjectCatalogueTests.cs index af05a12..af78286 100644 --- a/tests/EncDotNet.UnitTests/S57ObjectCatalogueTests.cs +++ b/tests/EncDotNet.UnitTests/S57ObjectCatalogueTests.cs @@ -18,11 +18,48 @@ public void Iho_ResolvesEveryObjectCode_WithMatchingAcronym(S57ObjectCode code) Assert.NotNull(objectClass); Assert.Equal((int)code, objectClass.Code); - Assert.Equal(code.ToString(), objectClass.Acronym); + Assert.Equal(ExpectedAcronym(code), objectClass.Acronym); Assert.False(string.IsNullOrWhiteSpace(objectClass.Name)); Assert.Same(objectClass, S57ObjectCatalogue.Iho.GetObjectClass(objectClass.Acronym)); } + [Theory] + [InlineData(S57ObjectCode.CartographicArea, 500, "$AREAS")] + [InlineData(S57ObjectCode.CartographicLine, 501, "$LINES")] + [InlineData(S57ObjectCode.CartographicSymbol, 502, "$CSYMB")] + [InlineData(S57ObjectCode.CartographicCompass, 503, "$COMPS")] + [InlineData(S57ObjectCode.CartographicText, 504, "$TEXTS")] + public void ObjectCode_CartographicMember_MapsToDollarAcronym(S57ObjectCode code, int value, string acronym) + { + Assert.Equal(value, (int)code); + + var objectClass = S57ObjectCatalogue.Iho.GetObjectClass(code); + Assert.NotNull(objectClass); + Assert.Equal(acronym, objectClass.Acronym); + Assert.Equal(S57ObjectClassCategory.Cartographic, objectClass.Category); + } + + [Theory] + [InlineData(S57ObjectCode.ARCSLN, 161)] + [InlineData(S57ObjectCode.ASLXIS, 162)] + [InlineData(S57ObjectCode.NEWOBJ, 163)] + public void ObjectCode_SupplementClasses_HaveCatalogueCodes(S57ObjectCode code, int value) + { + Assert.Equal(value, (int)code); + Assert.Equal(S57ObjectClassCategory.Geo, S57ObjectCatalogue.Iho.GetObjectClass(code)?.Category); + } + + [Fact] + public void Iho_EveryCartographicClass_HasObjectCode() + { + var cartographic = S57ObjectCatalogue.Iho.ObjectClasses + .Where(c => c.Category == S57ObjectClassCategory.Cartographic) + .ToList(); + + Assert.NotEmpty(cartographic); + Assert.All(cartographic, c => Assert.True(Enum.IsDefined((S57ObjectCode)c.Code), c.Acronym)); + } + [Fact] public void Iho_ObjectClass_HasNameCategoryAndPrimitives() { @@ -267,4 +304,67 @@ public void ToString_DescribesEntries() Assert.Equal("1: white", S57ObjectCatalogue.Iho.GetAttribute(75)?.GetValue(1)?.ToString()); Assert.Equal("IHO S-57 Edition 3.1", S57ObjectCatalogue.Iho.ToString()); } + + [Theory] + [InlineData("COLOUR", S57AttributeClass.Feature)] + [InlineData("OBJNAM", S57AttributeClass.Feature)] + [InlineData("NINFOM", S57AttributeClass.National)] + [InlineData("NOBJNM", S57AttributeClass.National)] + [InlineData("NPLDST", S57AttributeClass.National)] + [InlineData("$NTXST", S57AttributeClass.National)] + [InlineData("NTXTDS", S57AttributeClass.National)] + [InlineData("HORDAT", S57AttributeClass.Spatial)] + [InlineData("POSACC", S57AttributeClass.Spatial)] + [InlineData("QUAPOS", S57AttributeClass.Spatial)] + [InlineData("$SCODE", S57AttributeClass.Cartographic)] + [InlineData("$TXSTR", S57AttributeClass.Cartographic)] + public void Iho_Attribute_HasClass(string acronym, S57AttributeClass attributeClass) + { + var attribute = S57ObjectCatalogue.Iho.GetAttribute(acronym); + + Assert.NotNull(attribute); + Assert.Equal(attributeClass, attribute.Class); + Assert.Equal(attributeClass == S57AttributeClass.National, attribute.IsNational); + } + + [Fact] + public void Iho_NationalAttributes_AreTheNationalLanguageAttributes() + { + // S-57 Edition 3.1, Appendix A, Chapter 2, §2.3. + var national = S57ObjectCatalogue.Iho.Attributes.Where(a => a.IsNational).Select(a => a.Code).Order(); + + Assert.Equal([300, 301, 302, 303, 304], national); + } + + [Fact] + public void InlandEnc_OwnAttributes_AreFeatureAttributes() + { + var inland = S57ObjectCatalogue.InlandEnc.Attributes.Where(a => a.Code >= 17000).ToList(); + + Assert.NotEmpty(inland); + Assert.All(inland, a => Assert.Equal(S57AttributeClass.Feature, a.Class)); + Assert.True(S57ObjectCatalogue.InlandEnc.GetAttribute("NOBJNM")?.IsNational); + } + + [Fact] + public void Aml_AttributesDefaultToFeature_AndIhoAttributesKeepTheirClass() + { + foreach (var catalogue in new[] { S57ObjectCatalogue.Aml10, S57ObjectCatalogue.Aml21, S57ObjectCatalogue.Aml30 }) + { + Assert.All(catalogue.Attributes.Where(a => a.Code >= 20000), a => Assert.Equal(S57AttributeClass.Feature, a.Class)); + Assert.True(catalogue.GetAttribute("NOBJNM")?.IsNational); + Assert.Equal(S57AttributeClass.Spatial, catalogue.GetAttribute("POSACC")?.Class); + } + } + + // The cartographic members are named for their class, because '$' can't start an identifier. + private static string ExpectedAcronym(S57ObjectCode code) => code switch + { + S57ObjectCode.CartographicArea => "$AREAS", + S57ObjectCode.CartographicLine => "$LINES", + S57ObjectCode.CartographicSymbol => "$CSYMB", + S57ObjectCode.CartographicCompass => "$COMPS", + S57ObjectCode.CartographicText => "$TEXTS", + _ => code.ToString(), + }; }