diff --git a/Directory.Packages.props b/Directory.Packages.props
index 6c4d9d3..a43ae92 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -6,6 +6,12 @@
+
+
+
+
+
+
diff --git a/README.md b/README.md
index 749c59a..c4b42ae 100644
--- a/README.md
+++ b/README.md
@@ -92,6 +92,22 @@ tdbio info list.tpl --encoding cp1252
tdbio info list.xsr --json
```
+Export decoded Tekla model objects to JSON, Industry Foundation Classes (IFC) or a standalone 3D HTML viewer:
+
+```sh
+# Export to Tekla object model JSON
+tdbio export model.db1 model.json
+
+# Export to neutral IOScene JSON
+tdbio export model.db1 model.scene.json --scene-json
+
+# Export to IFC (IFC2x3 / IFC4)
+tdbio export model.db1 model.ifc
+
+# Generate an interactive 3D WebGL HTML viewer that works offline
+tdbio export model.db1 viewer.html
+```
+
Every command takes `--json` to write one JSON object instead of text. Warnings go to standard error and do not change
the exit code. The outputs above come from small synthetic files; the values are made up. Run `tdbio --help` for the
usage, and see [the command line](docs/cli.md) for every key, column and JSON property.
diff --git a/TdbIO.slnx b/TdbIO.slnx
index 73223bd..b613cbd 100644
--- a/TdbIO.slnx
+++ b/TdbIO.slnx
@@ -1,7 +1,9 @@
+
+
diff --git a/docs/dependencies.md b/docs/dependencies.md
index 424f027..458b11b 100644
--- a/docs/dependencies.md
+++ b/docs/dependencies.md
@@ -10,8 +10,11 @@ Build settings shared by every project live in `Directory.Build.props`; the SDK
## Runtime packages
-None. The library and the command line tool reference no packages and contain no third-party code. They use only the
-.NET runtime libraries:
+None for the core engine (`TdbIO`). The engine library references no external packages and contains no third-party code.
+`TdbIO.Scene` references `IOScene` `[0.1.0, 0.2.0-0.0)` as the neutral scene contract.
+`TdbIO.Cli` references `TdbIO.Scene` and `IOViewer` `0.3.1` for standalone HTML 3D viewer export.
+
+They use the following .NET runtime libraries:
| Runtime library | Used for |
| --- | --- |
diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs
index 2dda55f..1987752 100644
--- a/src/TdbIO.Cli/Cli.cs
+++ b/src/TdbIO.Cli/Cli.cs
@@ -1,5 +1,9 @@
using System.Reflection;
+using System.Runtime.InteropServices;
using System.Text;
+using IOScene;
+using IOViewer.Exporters;
+using TdbIO.Scene;
namespace TdbIO.CommandLine;
@@ -15,19 +19,27 @@ internal static class Cli
Usage: tdbio info [--json] [--encoding ascii|utf-8|cp1251|cp1252]
tdbio tables [--json]
tdbio text [--json]
- tdbio export [--indent]
+ tdbio export [output] [--indent] [--scene-json] [--ifc] [--html]
tdbio --help | -h | --version
Commands:
info The kind of the file and its main values.
tables The table sections of a model database (.db1) or a DBV@ file, one line each.
text The text chains of a model database (.db1), one line each. Save stamps show only their date.
- export Decodes the object model of a model database (.db1) and writes it as JSON.
+ export Decodes the object model of a model database (.db1) and writes it as JSON, IFC, or 3D HTML viewer.
+
+ Arguments:
+ Path to input file (.db1, .db2, DBV@, etc.).
+ [output] Destination path for exported file (.json, .ifc, or .html).
+ If omitted, JSON is written to stdout.
Options:
- --json Write one JSON object instead of text.
- --indent Format the JSON output with indentation (export only).
- --encoding The encoding of a template or report, instead of detecting it (info only).
+ --json Write one JSON object instead of text (info, tables, text).
+ --indent Format the JSON output with indentation (export only).
+ --scene-json Export as IOScene neutral scene JSON instead of Tekla object model JSON.
+ --ifc Force export format to IFC STEP physical file.
+ --html Force export format to standalone interactive 3D WebGL HTML viewer.
+ --encoding The encoding of a template or report, instead of detecting it (info only).
Warnings go to stderr and do not change the exit code.
Exit codes: 0 done, 1 usage error, 2 input error (missing, malformed or unsupported file).
@@ -37,7 +49,16 @@ export Decodes the object model of a model database (.db1) and writes it as J
private static readonly string[] TextColumns = ["section", "headId", "rows", "length", "stamp", "savedAt", "text"];
private static readonly string[] OrphanColumns = ["section", "id"];
- private sealed record Command(string Name, string Path, bool Json, bool Indent, Encoding? Encoding);
+ private sealed record Command(
+ string Name,
+ string Path,
+ string? OutputPath,
+ bool Json,
+ bool Indent,
+ bool SceneJson,
+ bool Ifc,
+ bool Html,
+ Encoding? Encoding);
// A usage error found while parsing or after the kind is known.
private sealed class UsageException(string message) : Exception(message);
@@ -77,7 +98,7 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)
{
case "info": error = Info(output, doc, command.Json); break;
case "tables": Tables(output, doc, command.Json); break;
- case "export": Export(output, doc, command.Indent); break;
+ case "export": Export(output, doc, command); break;
default: Text(output, doc, command.Json); break;
}
stdout.Write(output.ToString());
@@ -110,9 +131,14 @@ private static Command Parse(string[] args)
if (name is not ("info" or "tables" or "text" or "export")) throw new UsageException($"Unknown command '{name}'.");
string? path = null;
+ string? outputPath = null;
string? encodingName = null;
bool json = false;
bool indent = false;
+ bool sceneJson = false;
+ bool ifc = false;
+ bool html = false;
+
for (int i = 1; i < args.Length; i++)
{
string arg = args[i];
@@ -126,6 +152,21 @@ private static Command Parse(string[] args)
if (indent) throw new UsageException("Option '--indent' is repeated.");
indent = true;
}
+ else if (arg == "--scene-json" && name == "export")
+ {
+ if (sceneJson) throw new UsageException("Option '--scene-json' is repeated.");
+ sceneJson = true;
+ }
+ else if (arg == "--ifc" && name == "export")
+ {
+ if (ifc) throw new UsageException("Option '--ifc' is repeated.");
+ ifc = true;
+ }
+ else if (arg == "--html" && name == "export")
+ {
+ if (html) throw new UsageException("Option '--html' is repeated.");
+ html = true;
+ }
else if (arg == "--encoding" && name == "info")
{
if (encodingName != null) throw new UsageException("Option '--encoding' is repeated.");
@@ -134,11 +175,44 @@ private static Command Parse(string[] args)
}
else if (string.IsNullOrWhiteSpace(arg)) throw new UsageException("The file name is empty.");
else if (arg[0] == '-') throw new UsageException($"Unknown option '{arg}' for '{name}'.");
- else if (path != null) throw new UsageException($"Unexpected argument '{arg}'.");
- else path = arg;
+ else if (path == null) path = arg;
+ else if (outputPath == null && name == "export") outputPath = arg;
+ else throw new UsageException($"Unexpected argument '{arg}'.");
}
if (path == null) throw new UsageException("No file given.");
- return new Command(name, path, json, indent, encodingName == null ? null : EncodingOf(encodingName));
+
+ if (name == "export")
+ {
+ if (outputPath != null && AreSameFile(path, outputPath))
+ {
+ throw new UsageException("The output file path must not be the same as the input file.");
+ }
+
+ int formatFlags = (sceneJson ? 1 : 0) + (ifc ? 1 : 0) + (html ? 1 : 0);
+ if (formatFlags > 1)
+ {
+ throw new UsageException("Options '--scene-json', '--ifc', and '--html' are mutually exclusive.");
+ }
+
+ if (formatFlags == 0 && outputPath != null)
+ {
+ string ext = Path.GetExtension(outputPath);
+ if (ext.Equals(".ifc", StringComparison.OrdinalIgnoreCase))
+ {
+ ifc = true;
+ }
+ else if (ext.Equals(".html", StringComparison.OrdinalIgnoreCase) || ext.Equals(".htm", StringComparison.OrdinalIgnoreCase))
+ {
+ html = true;
+ }
+ else if (outputPath.EndsWith(".scene.json", StringComparison.OrdinalIgnoreCase))
+ {
+ sceneJson = true;
+ }
+ }
+ }
+
+ return new Command(name, path, outputPath, json, indent, sceneJson, ifc, html, encodingName == null ? null : EncodingOf(encodingName));
}
// Strict encodings: a byte the encoding does not define is an input error, never replaced.
@@ -300,13 +374,241 @@ private static void Text(TextWriter w, TdbDocument doc, bool json)
}
}
- private static void Export(TextWriter w, TdbDocument doc, bool indent)
+ private static void Export(TextWriter w, TdbDocument doc, Command cmd)
{
if (doc is not Db1Document db1) throw new WrongKindException($"'export' needs a model database (.db1), not {doc.Kind}.");
var model = db1.ReadModel();
- w.WriteLine(model.ToJson(indent));
+ model.ValidateFiniteNumbers();
+
+ if (cmd.Ifc)
+ {
+ if (cmd.OutputPath != null)
+ {
+ WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp => model.WriteIfc(tmp));
+ }
+ else
+ {
+ w.Write(model.ToIfc());
+ }
+ }
+ else if (cmd.Html)
+ {
+ if (cmd.OutputPath == null)
+ {
+ throw new UsageException("HTML viewer export requires an output file path (e.g. 'tdbio export model.db1 viewer.html').");
+ }
+ var sceneResult = TdbSceneReader.Read(model, new TdbSceneOptions
+ {
+ ModelKey = Path.GetFileNameWithoutExtension(cmd.Path)
+ });
+ var errors = sceneResult.Document.Validate().Where(d => d.Severity == SceneSeverity.Error).ToList();
+ if (errors.Count > 0)
+ {
+ throw new InvalidDataException(errors[0].Message);
+ }
+ WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp => HtmlViewerExporter.Save(sceneResult.Document, tmp));
+ }
+ else if (cmd.SceneJson)
+ {
+ var sceneResult = TdbSceneReader.Read(model, new TdbSceneOptions
+ {
+ ModelKey = Path.GetFileNameWithoutExtension(cmd.Path)
+ });
+ var errors = sceneResult.Document.Validate().Where(d => d.Severity == SceneSeverity.Error).ToList();
+ if (errors.Count > 0)
+ {
+ throw new InvalidDataException(errors[0].Message);
+ }
+ if (cmd.OutputPath != null)
+ {
+ WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp =>
+ {
+ if (cmd.Indent)
+ {
+ using var fs = File.Create(tmp);
+ var options = SceneJson.CreateOptions();
+ options.WriteIndented = true;
+ System.Text.Json.JsonSerializer.Serialize(fs, sceneResult.Document, options);
+ }
+ else
+ {
+ SceneJson.Save(sceneResult.Document, tmp);
+ }
+ });
+ }
+ else if (cmd.Indent)
+ {
+ var options = SceneJson.CreateOptions();
+ options.WriteIndented = true;
+ w.WriteLine(System.Text.Json.JsonSerializer.Serialize(sceneResult.Document, options));
+ }
+ else
+ {
+ w.WriteLine(SceneJson.Write(sceneResult.Document));
+ }
+ }
+ else
+ {
+ if (cmd.OutputPath != null)
+ {
+ WriteFileAtomically(cmd.Path, cmd.OutputPath, tmp =>
+ {
+ using var fs = File.Create(tmp);
+ model.WriteJson(fs, cmd.Indent);
+ });
+ }
+ else
+ {
+ w.WriteLine(model.ToJson(cmd.Indent));
+ }
+ }
}
+ private static void WriteFileAtomically(string inputPath, string outputPath, Action writeAction)
+ {
+ if (AreSameFile(inputPath, outputPath))
+ {
+ throw new UsageException("The output file path must not be the same as the input file.");
+ }
+
+ string fullPath = Path.GetFullPath(outputPath);
+ string? dir = Path.GetDirectoryName(fullPath);
+ if (string.IsNullOrEmpty(dir))
+ {
+ dir = ".";
+ }
+ string tempPath = Path.Combine(dir, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
+ try
+ {
+ writeAction(tempPath);
+ if (AreSameFile(inputPath, outputPath))
+ {
+ throw new UsageException("The output file path must not be the same as the input file.");
+ }
+ File.Move(tempPath, fullPath, overwrite: true);
+ }
+ finally
+ {
+ if (File.Exists(tempPath))
+ {
+ try { File.Delete(tempPath); } catch { /* ignore temp cleanup error */ }
+ }
+ }
+ }
+
+ internal static string ResolveCanonicalPath(string path)
+ {
+ string fullPath = Path.GetFullPath(path);
+ string? root = Path.GetPathRoot(fullPath);
+ if (string.IsNullOrEmpty(root))
+ {
+ return fullPath;
+ }
+
+ string remaining = fullPath[root.Length..];
+ string current = root;
+ string[] segments = remaining.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries);
+
+ foreach (string segment in segments)
+ {
+ current = Path.Combine(current, segment);
+ if (Directory.Exists(current))
+ {
+ try
+ {
+ var target = Directory.ResolveLinkTarget(current, returnFinalTarget: true);
+ if (target != null)
+ {
+ current = target.FullName;
+ }
+ }
+ catch (IOException) { }
+ }
+ else if (File.Exists(current))
+ {
+ try
+ {
+ var target = File.ResolveLinkTarget(current, returnFinalTarget: true);
+ if (target != null)
+ {
+ current = target.FullName;
+ }
+ }
+ catch (IOException) { }
+ }
+ }
+
+ return Path.GetFullPath(current);
+ }
+
+ internal static bool AreSameFile(string path1, string path2)
+ {
+ string r1 = ResolveCanonicalPath(path1);
+ string r2 = ResolveCanonicalPath(path2);
+ if (string.Equals(r1, r2, OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
+ {
+ return true;
+ }
+
+ if (File.Exists(path1) && File.Exists(path2))
+ {
+ try
+ {
+ var f1 = new FileInfo(path1);
+ var f2 = new FileInfo(path2);
+ string? t1 = f1.ResolveLinkTarget(true)?.FullName;
+ string? t2 = f2.ResolveLinkTarget(true)?.FullName;
+ string comp1 = t1 != null ? ResolveCanonicalPath(t1) : r1;
+ string comp2 = t2 != null ? ResolveCanonicalPath(t2) : r2;
+ if (string.Equals(comp1, comp2, OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
+ {
+ return true;
+ }
+ }
+ catch (IOException) { }
+
+ if (OperatingSystem.IsWindows())
+ {
+ try
+ {
+ using var s1 = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ using var s2 = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ if (GetFileInformationByHandle(s1.SafeFileHandle.DangerousGetHandle(), out var i1) &&
+ GetFileInformationByHandle(s2.SafeFileHandle.DangerousGetHandle(), out var i2))
+ {
+ if (i1.VolumeSerialNumber == i2.VolumeSerialNumber &&
+ i1.FileIndexHigh == i2.FileIndexHigh &&
+ i1.FileIndexLow == i2.FileIndexLow)
+ {
+ return true;
+ }
+ }
+ }
+ catch (Exception) { }
+ }
+ }
+
+ return false;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BY_HANDLE_FILE_INFORMATION
+ {
+ public uint FileAttributes;
+ public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
+ public uint VolumeSerialNumber;
+ public uint FileSizeHigh;
+ public uint FileSizeLow;
+ public uint NumberOfLinks;
+ public uint FileIndexHigh;
+ public uint FileIndexLow;
+ }
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
+
// The number of blocks below the root and the deepest level (the root is level 0).
private static (int Blocks, int Depth) Measure(TemplateBlock block)
{
diff --git a/src/TdbIO.Cli/TdbIO.Cli.csproj b/src/TdbIO.Cli/TdbIO.Cli.csproj
index 2bc98c7..2b14a44 100644
--- a/src/TdbIO.Cli/TdbIO.Cli.csproj
+++ b/src/TdbIO.Cli/TdbIO.Cli.csproj
@@ -12,6 +12,13 @@
+
+
+
+
+
+
+
diff --git a/src/TdbIO.Scene/TdbIO.Scene.csproj b/src/TdbIO.Scene/TdbIO.Scene.csproj
new file mode 100644
index 0000000..073459c
--- /dev/null
+++ b/src/TdbIO.Scene/TdbIO.Scene.csproj
@@ -0,0 +1,31 @@
+
+
+
+ Converts Tekla Structures models read by TdbIO into IOScene documents in metres with Z up, keeping assemblies, parts, bolts, welds and properties.
+ true
+ net8.0;net10.0
+
+ $(NoWarn);NU5104
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ <_Pinned Include="@(_ProjectReferencesWithVersions)">[%(_ProjectReferencesWithVersions.ProjectVersion)]
+ <_ProjectReferencesWithVersions Remove="@(_ProjectReferencesWithVersions)" />
+ <_ProjectReferencesWithVersions Include="@(_Pinned)" />
+
+
+
+
diff --git a/src/TdbIO.Scene/TdbSceneOptions.cs b/src/TdbIO.Scene/TdbSceneOptions.cs
new file mode 100644
index 0000000..72e57ec
--- /dev/null
+++ b/src/TdbIO.Scene/TdbSceneOptions.cs
@@ -0,0 +1,30 @@
+namespace TdbIO.Scene;
+
+///
+/// Options for .
+///
+public sealed class TdbSceneOptions
+{
+ ///
+ /// The key of the scene model (SceneModel.Key), which with each element's SourceId forms the identity
+ /// that may be stored outside the scene. Null uses the file name without directory, for example model.db1.
+ /// Required when the model is converted from memory, where there is no file name. An empty key is invalid, and
+ /// throws for it.
+ ///
+ public string? ModelKey { get; set; }
+
+ ///
+ /// Whether to include bolt groups in the scene hierarchy. Default is true.
+ ///
+ public bool IncludeBolts { get; set; } = true;
+
+ ///
+ /// Whether to include welds in the scene hierarchy. Default is true.
+ ///
+ public bool IncludeWelds { get; set; } = true;
+
+ ///
+ /// Whether to generate 3D mesh geometry for parts with start and end points. Default is true.
+ ///
+ public bool GenerateGeometry { get; set; } = true;
+}
diff --git a/src/TdbIO.Scene/TdbSceneReader.cs b/src/TdbIO.Scene/TdbSceneReader.cs
new file mode 100644
index 0000000..e391fd1
--- /dev/null
+++ b/src/TdbIO.Scene/TdbSceneReader.cs
@@ -0,0 +1,556 @@
+using System.Globalization;
+using System.Reflection;
+using IOScene;
+using TdbIO;
+using Vector3d = IOScene.Vector3d;
+using RgbaColor = IOScene.RgbaColor;
+
+namespace TdbIO.Scene;
+
+///
+/// Converts Tekla Structures models () or model files into an .
+///
+public static class TdbSceneReader
+{
+ private const int ModelId = 1;
+
+ private static readonly string Producer = "TdbIO.Scene "
+ + (typeof(TdbSceneReader).Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? "0.1.0");
+
+ /// Reads a Tekla model database file (.db1) and converts it into a scene.
+ /// Path to the model database file (.db1).
+ /// Conversion options, or null for defaults.
+ /// The scene and conversion report.
+ public static TdbSceneResult Read(string path, TdbSceneOptions? options = null)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(path);
+ string key = options?.ModelKey ?? Path.GetFileName(path);
+ if (key.Length == 0)
+ {
+ throw new ArgumentException("TdbSceneOptions.ModelKey must not be empty; leave it null to use the file name.", nameof(options));
+ }
+
+ var doc = TdbFile.Open(path);
+ if (doc is not Db1Document db1)
+ {
+ throw new NotSupportedException($"TdbIO.Scene requires a Tekla model database (.db1), but found '{doc.Kind}'.");
+ }
+
+ var model = db1.ReadModel();
+ return Convert(model, key, path, options);
+ }
+
+ /// Converts an in-memory into a scene.
+ /// The decoded Tekla model.
+ /// Conversion options.
+ /// The scene and conversion report.
+ public static TdbSceneResult Read(TeklaModel model, TdbSceneOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ if (options?.ModelKey != null && options.ModelKey.Length == 0)
+ {
+ throw new ArgumentException("TdbSceneOptions.ModelKey must not be empty.", nameof(options));
+ }
+
+ string key = options?.ModelKey
+ ?? (model.ModelGuid != Guid.Empty ? $"model_{model.ModelGuid:N}.db1" : "model.db1");
+
+ return Convert(model, key, null, options);
+ }
+
+ private static TdbSceneResult Convert(TeklaModel model, string key, string? path, TdbSceneOptions? options)
+ {
+ model.ValidateFiniteNumbers();
+ options ??= new TdbSceneOptions();
+ var scene = new SceneDocument { Title = key };
+
+ scene.Models.Add(new SceneModel
+ {
+ Id = ModelId,
+ Key = key,
+ Name = key,
+ Path = path,
+ SourceFormat = "db1",
+ Producer = Producer,
+ SourceLengthUnit = "mm",
+ Application = "Tekla Structures",
+ CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
+ });
+
+ // Root element of the model
+ const long rootElemId = 1L;
+ scene.Elements.Add(new SceneElement
+ {
+ Id = rootElemId,
+ ModelId = ModelId,
+ Kind = SceneNodeKind.Model,
+ Name = key,
+ });
+
+ long nextElemId = 2L;
+ int nextPsetId = 1;
+ int nextGeomId = 1;
+ int nextMatId = 1;
+
+ var materialCache = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ var asmElementMap = new Dictionary(model.Assemblies.Count);
+
+ int convertedElements = 0;
+ int elementsWithGeometry = 0;
+
+ // 1. Assemblies
+ foreach (var asm in model.Assemblies)
+ {
+ long asmId = nextElemId++;
+ asmElementMap[asm.Id] = asmId;
+ convertedElements++;
+
+ string asmMark = $"{asm.Prefix}{asm.PositionNumber}".Trim();
+ string asmName = string.IsNullOrEmpty(asm.Name) ? "Assembly" : asm.Name;
+ if (!string.IsNullOrEmpty(asmMark))
+ {
+ asmName = $"{asmMark} {asmName}";
+ }
+
+ var asmElement = new SceneElement
+ {
+ Id = asmId,
+ ModelId = ModelId,
+ Kind = SceneNodeKind.Group,
+ ParentId = rootElemId,
+ Name = asmName,
+ Category = "Assembly",
+ TypeName = string.IsNullOrEmpty(asm.Prefix) ? "Assembly" : asm.Prefix,
+ SourceId = asm.Guid != Guid.Empty ? asm.Guid.ToString("D") : $"asm:{asm.Id}",
+ IfcGuid = asm.IfcGuid,
+ };
+
+ // Assembly PropertySet
+ var asmProps = new List();
+ void AddProp(string name, string? keyNamespace, SceneValue val) =>
+ asmProps.Add(new SceneProperty { Name = name, Key = keyNamespace, Value = val });
+
+ AddProp("Assembly Mark", "tekla:assembly:mark", SceneValue.FromText($"{asm.Prefix}{asm.PositionNumber}"));
+ AddProp("Prefix", "tekla:assembly:prefix", SceneValue.FromText(asm.Prefix));
+ AddProp("Start Number", "tekla:assembly:start_number", SceneValue.FromInteger(asm.StartNumber, asm.StartNumber.ToString(CultureInfo.InvariantCulture)));
+ AddProp("Position Number", "tekla:assembly:position_number", SceneValue.FromInteger(asm.PositionNumber, asm.PositionNumber.ToString(CultureInfo.InvariantCulture)));
+ AddProp("Class", "tekla:assembly:class", SceneValue.FromInteger(asm.Class, asm.Class.ToString(CultureInfo.InvariantCulture)));
+ AddProp("Phase", "tekla:assembly:phase", SceneValue.FromInteger(asm.Phase, asm.Phase.ToString(CultureInfo.InvariantCulture)));
+ AddProp("Assembly Type", "tekla:assembly:type", SceneValue.FromInteger(asm.AssemblyType, asm.AssemblyType.ToString(CultureInfo.InvariantCulture)));
+
+ foreach (var (k, v) in asm.StringAttributes)
+ {
+ AddProp(k, $"tekla:attr:{k}", SceneValue.FromText(v));
+ }
+ foreach (var (k, v) in asm.NumericAttributes)
+ {
+ AddProp(k, $"tekla:attr:{k}", SceneValue.FromNumber(v, null, v.ToString("G", CultureInfo.InvariantCulture)));
+ }
+
+ var asmPset = new ScenePropertySet
+ {
+ Id = nextPsetId++,
+ Name = "Assembly",
+ Key = "tekla:assembly",
+ Properties = asmProps,
+ };
+ scene.PropertySets.Add(asmPset);
+ asmElement.PropertySetIds.Add(asmPset.Id);
+
+ scene.Elements.Add(asmElement);
+ }
+
+ // 2. Parts
+ foreach (var part in model.Parts)
+ {
+ long partId = nextElemId++;
+ convertedElements++;
+
+ long parentId = (part.Assembly != null && asmElementMap.TryGetValue(part.Assembly.Id, out var asmElemId))
+ ? asmElemId
+ : rootElemId;
+
+ string partName = string.IsNullOrEmpty(part.Name) ? "Part" : part.Name;
+ string partMark = $"{part.Prefix}{part.PositionNumber}".Trim();
+ if (!string.IsNullOrEmpty(partMark))
+ {
+ partName = $"{partMark} {partName}";
+ }
+
+ var partElement = new SceneElement
+ {
+ Id = partId,
+ ModelId = ModelId,
+ Kind = SceneNodeKind.Element,
+ ParentId = parentId,
+ Name = partName,
+ Category = "Part",
+ TypeName = string.IsNullOrEmpty(part.Profile) ? "Part" : part.Profile,
+ SourceId = part.Guid != Guid.Empty ? part.Guid.ToString("D") : $"part:{part.Id}",
+ IfcGuid = part.IfcGuid,
+ };
+
+ // Part PropertySet
+ var partProps = new List();
+ void AddPartProp(string name, string? keyNamespace, SceneValue val) =>
+ partProps.Add(new SceneProperty { Name = name, Key = keyNamespace, Value = val });
+
+ AddPartProp("Part Mark", "tekla:part:mark", SceneValue.FromText($"{part.Prefix}{part.PositionNumber}"));
+ AddPartProp("Profile", "tekla:part:profile", SceneValue.FromText(part.Profile));
+ AddPartProp("Material", "tekla:part:material", SceneValue.FromText(part.Material));
+ AddPartProp("Class", "tekla:part:class", SceneValue.FromInteger(part.Class, part.Class.ToString(CultureInfo.InvariantCulture)));
+ AddPartProp("Phase", "tekla:part:phase", SceneValue.FromInteger(part.Phase, part.Phase.ToString(CultureInfo.InvariantCulture)));
+ if (!string.IsNullOrEmpty(part.Finish))
+ {
+ AddPartProp("Finish", "tekla:part:finish", SceneValue.FromText(part.Finish));
+ }
+ if (part.Length > 0)
+ {
+ AddPartProp("Length", "tekla:part:length", SceneValue.FromNumber(part.Length * 0.001, "m", $"{part.Length:F1} mm"));
+ }
+
+ foreach (var (k, v) in part.StringAttributes)
+ {
+ AddPartProp(k, $"tekla:attr:{k}", SceneValue.FromText(v));
+ }
+ foreach (var (k, v) in part.NumericAttributes)
+ {
+ AddPartProp(k, $"tekla:attr:{k}", SceneValue.FromNumber(v, null, v.ToString("G", CultureInfo.InvariantCulture)));
+ }
+
+ var partPset = new ScenePropertySet
+ {
+ Id = nextPsetId++,
+ Name = "Part",
+ Key = "tekla:part",
+ Properties = partProps,
+ };
+ scene.PropertySets.Add(partPset);
+ partElement.PropertySetIds.Add(partPset.Id);
+
+ scene.Elements.Add(partElement);
+
+ // Material
+ string matKey = $"{part.Class}_{part.Material}";
+ if (!materialCache.TryGetValue(matKey, out int matId))
+ {
+ matId = nextMatId++;
+ var color = ColorForClass(part.Class);
+ scene.Materials.Add(new SceneMaterial
+ {
+ Id = matId,
+ Name = string.IsNullOrEmpty(part.Material) ? $"Class {part.Class}" : part.Material,
+ Color = color,
+ Roughness = 0.4,
+ Metalness = 0.6,
+ });
+ materialCache[matKey] = matId;
+ }
+
+ // Geometry (in metres, scale factor 0.001)
+ if (options.GenerateGeometry && part.StartPoint.HasValue && part.EndPoint.HasValue)
+ {
+ var p0 = part.StartPoint.Value;
+ var p1 = part.EndPoint.Value;
+
+ var (geomVertices, geomNormals, geomIndices) = BuildBoxMesh(p0, p1, part.Profile, 0.001);
+ if (geomVertices.Count > 0)
+ {
+ int geomId = nextGeomId++;
+ scene.Geometries.Add(new SceneGeometry
+ {
+ Id = geomId,
+ Topology = SceneTopology.Triangles,
+ Vertices = geomVertices,
+ Normals = geomNormals,
+ Indices = geomIndices,
+ });
+
+ scene.Instances.Add(new SceneInstance
+ {
+ ElementId = partId,
+ GeometryId = geomId,
+ MaterialId = matId,
+ Color = ColorForClass(part.Class),
+ });
+
+ elementsWithGeometry++;
+ }
+ }
+ }
+
+ // 3. Bolts
+ if (options.IncludeBolts)
+ {
+ foreach (var bolt in model.Bolts)
+ {
+ long boltId = nextElemId++;
+ convertedElements++;
+
+ long parentId = (bolt.Assembly != null && asmElementMap.TryGetValue(bolt.Assembly.Id, out var asmElemId))
+ ? asmElemId
+ : rootElemId;
+
+ var boltElement = new SceneElement
+ {
+ Id = boltId,
+ ModelId = ModelId,
+ Kind = SceneNodeKind.Element,
+ ParentId = parentId,
+ Name = $"Bolt Group ({bolt.Holes.Count} holes)",
+ Category = "Bolt",
+ TypeName = "Bolt Group",
+ SourceId = bolt.Guid != Guid.Empty ? bolt.Guid.ToString("D") : $"bolt:{bolt.Id}",
+ IfcGuid = bolt.IfcGuid,
+ };
+
+ var boltProps = new List
+ {
+ new() { Name = "Hole Count", Key = "tekla:bolt:hole_count", Value = SceneValue.FromInteger(bolt.Holes.Count, bolt.Holes.Count.ToString(CultureInfo.InvariantCulture)) },
+ new() { Name = "Position Count", Key = "tekla:bolt:position_count", Value = SceneValue.FromInteger(bolt.Positions.Count, bolt.Positions.Count.ToString(CultureInfo.InvariantCulture)) },
+ new() { Name = "Phase", Key = "tekla:bolt:phase", Value = SceneValue.FromInteger(bolt.Phase, bolt.Phase.ToString(CultureInfo.InvariantCulture)) }
+ };
+
+ foreach (var (k, v) in bolt.StringAttributes)
+ {
+ boltProps.Add(new SceneProperty { Name = k, Key = $"tekla:attr:{k}", Value = SceneValue.FromText(v) });
+ }
+
+ var boltPset = new ScenePropertySet
+ {
+ Id = nextPsetId++,
+ Name = "Bolt Group",
+ Key = "tekla:bolt",
+ Properties = boltProps,
+ };
+ scene.PropertySets.Add(boltPset);
+ boltElement.PropertySetIds.Add(boltPset.Id);
+
+ scene.Elements.Add(boltElement);
+ }
+ }
+
+ // 4. Welds
+ if (options.IncludeWelds)
+ {
+ foreach (var weld in model.Welds)
+ {
+ long weldId = nextElemId++;
+ convertedElements++;
+
+ long parentId = (weld.Assembly != null && asmElementMap.TryGetValue(weld.Assembly.Id, out var asmElemId))
+ ? asmElemId
+ : rootElemId;
+
+ var weldElement = new SceneElement
+ {
+ Id = weldId,
+ ModelId = ModelId,
+ Kind = SceneNodeKind.Element,
+ ParentId = parentId,
+ Name = "Weld",
+ Category = "Weld",
+ TypeName = "Weld",
+ SourceId = weld.Guid != Guid.Empty ? weld.Guid.ToString("D") : $"weld:{weld.Id}",
+ IfcGuid = weld.IfcGuid,
+ };
+
+ var weldProps = new List
+ {
+ new() { Name = "Common Attr Id", Key = "tekla:weld:common_attr_id", Value = SceneValue.FromInteger(weld.CommonAttrId, weld.CommonAttrId.ToString(CultureInfo.InvariantCulture)) },
+ new() { Name = "Phase", Key = "tekla:weld:phase", Value = SceneValue.FromInteger(weld.Phase, weld.Phase.ToString(CultureInfo.InvariantCulture)) }
+ };
+
+ foreach (var (k, v) in weld.StringAttributes)
+ {
+ weldProps.Add(new SceneProperty { Name = k, Key = $"tekla:attr:{k}", Value = SceneValue.FromText(v) });
+ }
+
+ var weldPset = new ScenePropertySet
+ {
+ Id = nextPsetId++,
+ Name = "Weld",
+ Key = "tekla:weld",
+ Properties = weldProps,
+ };
+ scene.PropertySets.Add(weldPset);
+ weldElement.PropertySetIds.Add(weldPset.Id);
+
+ scene.Elements.Add(weldElement);
+ }
+ }
+
+ var diagnostics = scene.Validate();
+ return new TdbSceneResult(scene, diagnostics, convertedElements, elementsWithGeometry);
+ }
+
+ private static RgbaColor ColorForClass(int teklaClass) => teklaClass switch
+ {
+ 1 => new RgbaColor(178, 178, 178), // Grey
+ 2 => new RgbaColor(217, 56, 58), // Red
+ 3 => new RgbaColor(92, 184, 92), // Green
+ 4 => new RgbaColor(51, 122, 183), // Blue
+ 5 => new RgbaColor(91, 192, 222), // Cyan
+ 6 => new RgbaColor(217, 83, 79), // Magenta
+ 7 => new RgbaColor(240, 173, 78), // Orange / Yellow
+ 8 => new RgbaColor(139, 69, 19), // Brown
+ 9 => new RgbaColor(46, 125, 50), // Dark Green
+ 10 => new RgbaColor(21, 101, 192), // Dark Blue
+ 11 => new RgbaColor(123, 31, 162), // Purple
+ 12 => new RgbaColor(0, 137, 123), // Teal
+ 13 => new RgbaColor(233, 30, 99), // Pink
+ 14 => new RgbaColor(84, 110, 122), // Dark Grey
+ _ => new RgbaColor(144, 202, 249), // Default Light Blue
+ };
+
+ private static (List Vertices, List Normals, List Indices) BuildBoxMesh(
+ ModelPoint p0, ModelPoint p1, string profile, double scale)
+ {
+ double dx = (p1.X - p0.X) * scale;
+ double dy = (p1.Y - p0.Y) * scale;
+ double dz = (p1.Z - p0.Z) * scale;
+ double len = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+
+ if (len < 1e-6)
+ {
+ return ([], [], []);
+ }
+
+ double dirX = dx / len;
+ double dirY = dy / len;
+ double dirZ = dz / len;
+
+ double perpX, perpY, perpZ;
+ if (Math.Abs(dirZ) < 0.9)
+ {
+ perpX = dirY;
+ perpY = -dirX;
+ perpZ = 0.0;
+ }
+ else
+ {
+ perpX = -dirZ;
+ perpY = 0.0;
+ perpZ = dirX;
+ }
+ double perpLen = Math.Sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
+ if (perpLen > 1e-6)
+ {
+ perpX /= perpLen;
+ perpY /= perpLen;
+ perpZ /= perpLen;
+ }
+
+ double vX = dirY * perpZ - dirZ * perpY;
+ double vY = dirZ * perpX - dirX * perpZ;
+ double vZ = dirX * perpY - dirY * perpX;
+
+ (double hw, double hh) = EstimateProfileDimensions(profile, scale);
+
+ double x0 = p0.X * scale;
+ double y0 = p0.Y * scale;
+ double z0 = p0.Z * scale;
+ double x1 = p1.X * scale;
+ double y1 = p1.Y * scale;
+ double z1 = p1.Z * scale;
+
+ // 8 corner positions
+ var c0 = new Vector3d(x0 - perpX * hw - vX * hh, y0 - perpY * hw - vY * hh, z0 - perpZ * hw - vZ * hh);
+ var c1 = new Vector3d(x0 + perpX * hw - vX * hh, y0 + perpY * hw - vY * hh, z0 + perpZ * hw - vZ * hh);
+ var c2 = new Vector3d(x0 + perpX * hw + vX * hh, y0 + perpY * hw + vY * hh, z0 + perpZ * hw + vZ * hh);
+ var c3 = new Vector3d(x0 - perpX * hw + vX * hh, y0 - perpY * hw + vY * hh, z0 - perpZ * hw + vZ * hh);
+ var c4 = new Vector3d(x1 - perpX * hw - vX * hh, y1 - perpY * hw - vY * hh, z1 - perpZ * hw - vZ * hh);
+ var c5 = new Vector3d(x1 + perpX * hw - vX * hh, y1 + perpY * hw - vY * hh, z1 + perpZ * hw - vZ * hh);
+ var c6 = new Vector3d(x1 + perpX * hw + vX * hh, y1 + perpY * hw + vY * hh, z1 + perpZ * hw + vZ * hh);
+ var c7 = new Vector3d(x1 - perpX * hw + vX * hh, y1 - perpY * hw + vY * hh, z1 - perpZ * hw + vZ * hh);
+
+ var vertices = new List(24);
+ var normals = new List(24);
+ var indices = new List(36);
+
+ void AddFace(Vector3d a, Vector3d b, Vector3d c, Vector3d d, Vector3d normal)
+ {
+ int baseIdx = vertices.Count;
+ vertices.Add(a);
+ vertices.Add(b);
+ vertices.Add(c);
+ vertices.Add(d);
+ normals.Add(normal);
+ normals.Add(normal);
+ normals.Add(normal);
+ normals.Add(normal);
+ indices.Add(baseIdx);
+ indices.Add(baseIdx + 1);
+ indices.Add(baseIdx + 2);
+ indices.Add(baseIdx);
+ indices.Add(baseIdx + 2);
+ indices.Add(baseIdx + 3);
+ }
+
+ var nStart = new Vector3d(-dirX, -dirY, -dirZ);
+ var nEnd = new Vector3d(dirX, dirY, dirZ);
+ var nBottom = new Vector3d(-vX, -vY, -vZ);
+ var nRight = new Vector3d(perpX, perpY, perpZ);
+ var nTop = new Vector3d(vX, vY, vZ);
+ var nLeft = new Vector3d(-perpX, -perpY, -perpZ);
+
+ AddFace(c3, c2, c1, c0, nStart); // Start cap
+ AddFace(c4, c5, c6, c7, nEnd); // End cap
+ AddFace(c0, c1, c5, c4, nBottom); // Bottom
+ AddFace(c1, c2, c6, c5, nRight); // Right
+ AddFace(c2, c3, c7, c6, nTop); // Top
+ AddFace(c3, c0, c4, c7, nLeft); // Left
+
+ return (vertices, normals, indices);
+ }
+
+ private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(string profile, double scale)
+ {
+ double widthMm = 150.0;
+ double heightMm = 150.0;
+
+ if (!string.IsNullOrEmpty(profile))
+ {
+ string p = profile.ToUpperInvariant();
+ if (p.StartsWith("PL", StringComparison.OrdinalIgnoreCase))
+ {
+ var parts = p[2..].Split(['*', 'x', 'X']);
+ if (parts.Length >= 2)
+ {
+ bool parsedT = double.TryParse(parts[0], CultureInfo.InvariantCulture, out double t);
+ bool parsedW = double.TryParse(parts[1], CultureInfo.InvariantCulture, out double w);
+
+ if ((parsedT && !double.IsFinite(t)) || (parsedW && !double.IsFinite(w)))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite dimension in profile '{profile}'."));
+ }
+
+ if (parsedT && parsedW && t > 0 && w > 0)
+ {
+ heightMm = t;
+ widthMm = w;
+ }
+ }
+ }
+ else
+ {
+ int idx = 0;
+ while (idx < p.Length && !char.IsDigit(p[idx])) idx++;
+ int end = idx;
+ while (end < p.Length && char.IsDigit(p[end])) end++;
+ if (end > idx && int.TryParse(p[idx..end], CultureInfo.InvariantCulture, out int size) && size > 10)
+ {
+ heightMm = size;
+ widthMm = p.StartsWith("IPE") ? size * 0.5 : size;
+ }
+ }
+ }
+
+ if (!double.IsFinite(widthMm) || !double.IsFinite(heightMm))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite dimension in profile '{profile}'."));
+ }
+
+ return (widthMm * 0.5 * scale, heightMm * 0.5 * scale);
+ }
+}
diff --git a/src/TdbIO.Scene/TdbSceneResult.cs b/src/TdbIO.Scene/TdbSceneResult.cs
new file mode 100644
index 0000000..4a1d69a
--- /dev/null
+++ b/src/TdbIO.Scene/TdbSceneResult.cs
@@ -0,0 +1,39 @@
+using IOScene;
+
+namespace TdbIO.Scene;
+
+///
+/// The result of : the scene and what happened to the model's data.
+///
+public sealed class TdbSceneResult
+{
+ internal TdbSceneResult(
+ SceneDocument document,
+ IReadOnlyList diagnostics,
+ int elementCount,
+ int elementsWithGeometry)
+ {
+ Document = document;
+ Diagnostics = diagnostics;
+ ElementCount = elementCount;
+ ElementsWithGeometry = elementsWithGeometry;
+ }
+
+ /// The scene, in metres with Z up.
+ public SceneDocument Document { get; }
+
+ /// Findings of the conversion.
+ public IReadOnlyList Diagnostics { get; }
+
+ /// The exact factor applied to every coordinate: Tekla millimetres to metres (0.001).
+ public double MetresPerUnit => 0.001;
+
+ /// Number of converted Tekla model elements, with or without geometry (excluding model root).
+ public int ElementCount { get; }
+
+ /// Number of converted elements that have geometry.
+ public int ElementsWithGeometry { get; }
+
+ /// Number of unique geometries in the scene.
+ public int GeometryCount => Document.Geometries.Count;
+}
diff --git a/src/TdbIO/Internal/Export/IfcExporter.cs b/src/TdbIO/Internal/Export/IfcExporter.cs
new file mode 100644
index 0000000..f631821
--- /dev/null
+++ b/src/TdbIO/Internal/Export/IfcExporter.cs
@@ -0,0 +1,623 @@
+using System.Globalization;
+using System.Text;
+using TdbIO;
+
+namespace TdbIO.Internal.Export;
+
+///
+/// Exports to Industry Foundation Classes (IFC2x3 / IFC4)
+/// in ISO 10303-21 STEP physical file format.
+///
+internal static class IfcExporter
+{
+ private const string DegreeInRadians = "0.017453292519943278";
+
+ /// Writes a to an IFC file at the specified path.
+ public static void WriteFile(TeklaModel model, string path, TeklaIfcExportOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ ArgumentNullException.ThrowIfNull(path);
+
+ using var fs = File.Create(path);
+ using var writer = new StreamWriter(fs, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), bufferSize: 65536);
+ Write(model, writer, options, Path.GetFileName(path));
+ }
+
+ /// Writes a to a .
+ public static void Write(TeklaModel model, Stream stream, TeklaIfcExportOptions? options = null, string? fileName = null)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ ArgumentNullException.ThrowIfNull(stream);
+
+ using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), bufferSize: 65536, leaveOpen: true);
+ Write(model, writer, options, fileName);
+ }
+
+ /// Converts a to an IFC STEP string.
+ public static string ToString(TeklaModel model, TeklaIfcExportOptions? options = null)
+ {
+ using var sw = new StringWriter(CultureInfo.InvariantCulture);
+ Write(model, sw, options, "model.ifc");
+ return sw.ToString();
+ }
+
+ /// Writes a to a .
+ public static void Write(
+ TeklaModel model,
+ TextWriter writer,
+ TeklaIfcExportOptions? options = null,
+ string? fileName = null)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ ArgumentNullException.ThrowIfNull(writer);
+
+ model.ValidateFiniteNumbers();
+
+ options ??= new TeklaIfcExportOptions();
+ fileName ??= "model.ifc";
+
+ bool isIfc4 = string.Equals(options.SchemaVersion, "IFC4", StringComparison.OrdinalIgnoreCase);
+ string schemaName = isIfc4 ? "IFC4" : "IFC2X3";
+ string viewDef = isIfc4 ? "ViewDefinition [DesignTransferView_1.0]" : "ViewDefinition [CoordinationView_V2.0]";
+
+ var w = new StepWriter();
+
+ // 1. Project infrastructure & Owner History
+ int personId = w.Add("IFCPERSON", $"$,{StepWriter.Str(options.Author)},$,$,$,$,$,$");
+ int orgId = w.Add("IFCORGANIZATION", $"$,{StepWriter.Str(options.Organization)},$,$,$");
+ int personOrgId = w.Add("IFCPERSONANDORGANIZATION", $"{StepWriter.Ref(personId)},{StepWriter.Ref(orgId)},$");
+ int appId = w.Add("IFCAPPLICATION", $"{StepWriter.Ref(orgId)},'0.1.0',{StepWriter.Str(options.Application)},'TdbIO'");
+
+ int epochSeconds = (int)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
+ int ownerHistoryId = w.Add("IFCOWNERHISTORY",
+ $"{StepWriter.Ref(personOrgId)},{StepWriter.Ref(appId)},.READWRITE.,.NOCHANGE.,$,$,$,{epochSeconds}");
+
+ // 2. Units & Geometric Context
+ int lengthUnitId = w.Add("IFCSIUNIT", options.ConvertMmToMetres ? "*,.LENGTHUNIT.,$,.METRE." : "*,.LENGTHUNIT.,.MILLI.,.METRE.");
+ int radianId = w.Add("IFCSIUNIT", "*,.PLANEANGLEUNIT.,$,.RADIAN.");
+ int dimExpId = w.Add("IFCDIMENSIONALEXPONENTS", "0,0,0,0,0,0,0");
+ int angleMeasureId = w.Add("IFCMEASUREWITHUNIT", $"IFCPLANEANGLEMEASURE({DegreeInRadians}),{StepWriter.Ref(radianId)}");
+ int degreeUnitId = w.Add("IFCCONVERSIONBASEDUNIT", $"{StepWriter.Ref(dimExpId)},.PLANEANGLEUNIT.,'DEGREE',{StepWriter.Ref(angleMeasureId)}");
+ int areaUnitId = w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE.");
+ int volumeUnitId = w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE.");
+
+ int unitAssignmentId = w.Add("IFCUNITASSIGNMENT",
+ StepWriter.List(StepWriter.Ref(lengthUnitId), StepWriter.Ref(degreeUnitId), StepWriter.Ref(areaUnitId), StepWriter.Ref(volumeUnitId)));
+
+ int originPointId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(0), StepWriter.Real(0), StepWriter.Real(0)));
+ int axisZId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(0), StepWriter.Real(0), StepWriter.Real(1)));
+ int axisXId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(1), StepWriter.Real(0), StepWriter.Real(0)));
+ int worldPlacement3dId = w.Add("IFCAXIS2PLACEMENT3D",
+ $"{StepWriter.Ref(originPointId)},{StepWriter.Ref(axisZId)},{StepWriter.Ref(axisXId)}");
+
+ int mainContextId = w.Add("IFCGEOMETRICREPRESENTATIONCONTEXT",
+ $"$,'Model',3,1.E-05,{StepWriter.Ref(worldPlacement3dId)},$");
+ int bodySubContextId = w.Add("IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
+ $"'Body','Model',*,*,*,*,{StepWriter.Ref(mainContextId)},$,.MODEL_VIEW.,$");
+
+ // 3. Spatial Hierarchy: Project -> Site -> Building -> Storey
+ string projectName = options.ProjectName
+ ?? (model.ModelGuid != Guid.Empty ? $"Tekla Model {model.ModelGuid:D}" : "Tekla Model");
+ string buildingName = options.BuildingName;
+ string storeyName = options.StoreyName;
+
+ string projectGuid = model.ModelGuid != Guid.Empty
+ ? IfcGuid.ToIfcGuid(model.ModelGuid)
+ : IfcGuid.NewGuid();
+
+ int projectId = w.Add("IFCPROJECT",
+ $"{StepWriter.Str(projectGuid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(projectName)},$,$,$,$,({StepWriter.Ref(mainContextId)}),{StepWriter.Ref(unitAssignmentId)}");
+
+ int sitePlacementId = w.Add("IFCLOCALPLACEMENT", $"$,{StepWriter.Ref(worldPlacement3dId)}");
+ int siteId = w.Add("IFCSITE",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},'Default Site',$,$,{StepWriter.Ref(sitePlacementId)},$,$,.ELEMENT.,$,$,$,$,$");
+
+ int buildingPlacementId = w.Add("IFCLOCALPLACEMENT", $"{StepWriter.Ref(sitePlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+ int buildingId = w.Add("IFCBUILDING",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(buildingName)},$,$,{StepWriter.Ref(buildingPlacementId)},$,$,.ELEMENT.,$,$,$");
+
+ int storeyPlacementId = w.Add("IFCLOCALPLACEMENT", $"{StepWriter.Ref(buildingPlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+ int storeyId = w.Add("IFCBUILDINGSTOREY",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(storeyName)},$,$,{StepWriter.Ref(storeyPlacementId)},$,$,.ELEMENT.,{StepWriter.Real(0)}");
+
+ w.Add("IFCRELAGGREGATES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(projectId)},({StepWriter.Ref(siteId)})");
+ w.Add("IFCRELAGGREGATES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(siteId)},({StepWriter.Ref(buildingId)})");
+ w.Add("IFCRELAGGREGATES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(buildingId)},({StepWriter.Ref(storeyId)})");
+
+ // 4. Material Cache
+ var materialCache = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ // 5. Parts Mapping
+ double scale = options.ConvertMmToMetres ? 0.001 : 1.0;
+ var partStepIds = new Dictionary();
+ var standalonePartIds = new List();
+
+ foreach (var part in model.Parts)
+ {
+ int? shapeRepId = null;
+ if (options.ExportGeometry && part.StartPoint.HasValue && part.EndPoint.HasValue)
+ {
+ var p0 = part.StartPoint.Value;
+ var p1 = part.EndPoint.Value;
+ int geomId = WritePartFacetedBrep(w, p0, p1, part.Profile, scale);
+ shapeRepId = w.Add("IFCSHAPEREPRESENTATION",
+ $"{StepWriter.Ref(bodySubContextId)},'Body','Brep',({StepWriter.Ref(geomId)})");
+ }
+
+ int? prodShapeId = shapeRepId.HasValue
+ ? w.Add("IFCPRODUCTDEFINITIONSHAPE", $"$,$,({StepWriter.Ref(shapeRepId.Value)})")
+ : null;
+
+ int elemPlacementId = w.Add("IFCLOCALPLACEMENT",
+ $"{StepWriter.Ref(storeyPlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+
+ string ifcType = ClassifyPart(part);
+ string elemGuid = part.IfcGuid;
+ string elemName = string.IsNullOrEmpty(part.Name) ? $"Part_{part.Id}" : part.Name;
+ string elemTag = part.Id.ToString(CultureInfo.InvariantCulture);
+
+ int partStepId = AddIfcProduct(w, ifcType, elemGuid, ownerHistoryId, elemName, elemPlacementId, prodShapeId, elemTag, isIfc4);
+ partStepIds[part.Id] = partStepId;
+
+ // Material
+ if (!string.IsNullOrEmpty(part.Material))
+ {
+ if (!materialCache.TryGetValue(part.Material, out int matId))
+ {
+ matId = w.Add("IFCMATERIAL", isIfc4 ? $"{StepWriter.Str(part.Material)},$,$" : StepWriter.Str(part.Material));
+ materialCache[part.Material] = matId;
+ }
+ w.Add("IFCRELASSOCIATESMATERIAL",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(partStepId)}),{StepWriter.Ref(matId)}");
+ }
+
+ // Properties
+ if (options.ExportProperties)
+ {
+ WritePartProperties(w, partStepId, part, ownerHistoryId, scale);
+ }
+
+ if (!options.ExportAssemblies || part.Assembly == null)
+ {
+ standalonePartIds.Add(partStepId);
+ }
+ }
+
+ // 6. Assemblies Mapping
+ var assemblyStepIds = new List();
+ if (options.ExportAssemblies)
+ {
+ foreach (var asm in model.Assemblies)
+ {
+ int asmPlacementId = w.Add("IFCLOCALPLACEMENT",
+ $"{StepWriter.Ref(storeyPlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+
+ string asmGuid = asm.IfcGuid;
+ string asmName = string.IsNullOrEmpty(asm.Name) ? $"Assembly_{asm.Id}" : asm.Name;
+ string asmTag = asm.Id.ToString(CultureInfo.InvariantCulture);
+
+ int asmStepId = w.Add("IFCELEMENTASSEMBLY",
+ $"{StepWriter.Str(asmGuid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(asmName)},$,$,{StepWriter.Ref(asmPlacementId)},$,{StepWriter.Str(asmTag)},.NOTDEFINED.,.NOTDEFINED.");
+ assemblyStepIds.Add(asmStepId);
+
+ // Relate parts to this assembly
+ var childPartStepIds = new List();
+ foreach (var childPart in asm.Parts)
+ {
+ if (partStepIds.TryGetValue(childPart.Id, out int childStepId))
+ {
+ childPartStepIds.Add(childStepId);
+ }
+ }
+
+ if (childPartStepIds.Count > 0)
+ {
+ w.Add("IFCRELAGGREGATES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(asmStepId)},{StepWriter.List(childPartStepIds.Select(StepWriter.Ref))}");
+ }
+
+ if (options.ExportProperties)
+ {
+ WriteAssemblyProperties(w, asmStepId, asm, ownerHistoryId);
+ }
+ }
+ }
+
+ // 7. Bolts Mapping
+ var boltStepIds = new List();
+ if (options.ExportBolts)
+ {
+ foreach (var bolt in model.Bolts)
+ {
+ int boltPlacementId = w.Add("IFCLOCALPLACEMENT",
+ $"{StepWriter.Ref(storeyPlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+
+ string boltGuid = bolt.IfcGuid;
+ string boltTag = bolt.Id.ToString(CultureInfo.InvariantCulture);
+
+ int boltStepId = w.Add("IFCMECHANICALFASTENER",
+ isIfc4
+ ? $"{StepWriter.Str(boltGuid)},{StepWriter.Ref(ownerHistoryId)},'Bolt Group',$,$,{StepWriter.Ref(boltPlacementId)},$,{StepWriter.Str(boltTag)},$,$,.BOLT."
+ : $"{StepWriter.Str(boltGuid)},{StepWriter.Ref(ownerHistoryId)},'Bolt Group',$,$,{StepWriter.Ref(boltPlacementId)},$,{StepWriter.Str(boltTag)},$,$");
+ boltStepIds.Add(boltStepId);
+
+ if (options.ExportProperties)
+ {
+ WriteBoltProperties(w, boltStepId, bolt, ownerHistoryId);
+ }
+ }
+ }
+
+ // 8. Welds Mapping
+ var weldStepIds = new List();
+ if (options.ExportWelds)
+ {
+ foreach (var weld in model.Welds)
+ {
+ int weldPlacementId = w.Add("IFCLOCALPLACEMENT",
+ $"{StepWriter.Ref(storeyPlacementId)},{StepWriter.Ref(worldPlacement3dId)}");
+
+ string weldGuid = weld.IfcGuid;
+ string weldTag = weld.Id.ToString(CultureInfo.InvariantCulture);
+
+ int weldStepId = w.Add("IFCFASTENER",
+ isIfc4
+ ? $"{StepWriter.Str(weldGuid)},{StepWriter.Ref(ownerHistoryId)},'Weld',$,$,{StepWriter.Ref(weldPlacementId)},$,{StepWriter.Str(weldTag)},.WELD."
+ : $"{StepWriter.Str(weldGuid)},{StepWriter.Ref(ownerHistoryId)},'Weld',$,$,{StepWriter.Ref(weldPlacementId)},$,{StepWriter.Str(weldTag)}");
+ weldStepIds.Add(weldStepId);
+
+ if (options.ExportProperties)
+ {
+ WriteWeldProperties(w, weldStepId, weld, ownerHistoryId);
+ }
+ }
+ }
+
+ // 9. Spatial Containment in Storey
+ var containedIds = new List();
+ containedIds.AddRange(assemblyStepIds);
+ containedIds.AddRange(standalonePartIds);
+ containedIds.AddRange(boltStepIds);
+ containedIds.AddRange(weldStepIds);
+
+ if (containedIds.Count > 0)
+ {
+ w.Add("IFCRELCONTAINEDINSPATIALSTRUCTURE",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.List(containedIds.Select(StepWriter.Ref))},{StepWriter.Ref(storeyId)}");
+ }
+
+ // 10. Write complete STEP file
+ w.WriteTo(writer, fileName, schemaName, viewDef, options.Application, options.Organization, options.Author);
+ }
+
+ private static string ClassifyPart(ModelPart part)
+ {
+ string name = part.Name.ToUpperInvariant();
+ string profile = part.Profile.ToUpperInvariant();
+
+ if (name.Contains("BEAM") || name.Contains("BALKA") || name.Contains("GIRDER") ||
+ name.Contains("JOIST") || name.Contains("PURLIN") || name.Contains("RAFTER") || name.Contains("RIGEL"))
+ {
+ return "IFCBEAM";
+ }
+
+ if (name.Contains("COLUMN") || name.Contains("KOLONNA") || name.Contains("PILLAR") ||
+ name.Contains("POST") || name.Contains("STANCHION") || name.Contains("STOIKA"))
+ {
+ return "IFCCOLUMN";
+ }
+
+ if (name.Contains("PLATE") || name.Contains("PLASTINA") || name.Contains("LIST") ||
+ name.Contains("SLAB") || name.Contains("FLANGE") || name.Contains("WEB") ||
+ name.Contains("STIFFENER") || profile.StartsWith("PL", StringComparison.OrdinalIgnoreCase))
+ {
+ return "IFCPLATE";
+ }
+
+ return "IFCMEMBER";
+ }
+
+ private static int AddIfcProduct(
+ StepWriter w,
+ string ifcType,
+ string guid,
+ int ownerHistoryId,
+ string name,
+ int placementId,
+ int? shapeId,
+ string tag,
+ bool isIfc4)
+ {
+ string shapeArg = shapeId.HasValue ? StepWriter.Ref(shapeId.Value) : "$";
+ return ifcType switch
+ {
+ "IFCBEAM" => w.Add("IFCBEAM",
+ $"{StepWriter.Str(guid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(name)},$,$,{StepWriter.Ref(placementId)},{shapeArg},{StepWriter.Str(tag)}" + (isIfc4 ? ",.BEAM." : "")),
+ "IFCCOLUMN" => w.Add("IFCCOLUMN",
+ $"{StepWriter.Str(guid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(name)},$,$,{StepWriter.Ref(placementId)},{shapeArg},{StepWriter.Str(tag)}" + (isIfc4 ? ",.COLUMN." : "")),
+ "IFCPLATE" => w.Add("IFCPLATE",
+ $"{StepWriter.Str(guid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(name)},$,$,{StepWriter.Ref(placementId)},{shapeArg},{StepWriter.Str(tag)}" + (isIfc4 ? ",.NOTDEFINED." : "")),
+ _ => w.Add("IFCMEMBER",
+ $"{StepWriter.Str(guid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(name)},$,$,{StepWriter.Ref(placementId)},{shapeArg},{StepWriter.Str(tag)}" + (isIfc4 ? ",.MEMBER." : "")),
+ };
+ }
+
+ private static int WritePartFacetedBrep(StepWriter w, ModelPoint p0, ModelPoint p1, string profile, double scale)
+ {
+ // Vector along the beam axis
+ double dx = (p1.X - p0.X) * scale;
+ double dy = (p1.Y - p0.Y) * scale;
+ double dz = (p1.Z - p0.Z) * scale;
+ double len = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+
+ // Normalize direction
+ double dirX = len > 1e-6 ? dx / len : 1.0;
+ double dirY = len > 1e-6 ? dy / len : 0.0;
+ double dirZ = len > 1e-6 ? dz / len : 0.0;
+
+ // Find perpendicular vectors (u and v)
+ double perpX, perpY, perpZ;
+ if (Math.Abs(dirZ) < 0.9)
+ {
+ // Cross product with Z (0, 0, 1)
+ perpX = dirY;
+ perpY = -dirX;
+ perpZ = 0.0;
+ }
+ else
+ {
+ // Cross product with Y (0, 1, 0)
+ perpX = -dirZ;
+ perpY = 0.0;
+ perpZ = dirX;
+ }
+ double perpLen = Math.Sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
+ if (perpLen > 1e-6)
+ {
+ perpX /= perpLen;
+ perpY /= perpLen;
+ perpZ /= perpLen;
+ }
+
+ // Second perpendicular vector: cross(dir, perp)
+ double vX = dirY * perpZ - dirZ * perpY;
+ double vY = dirZ * perpX - dirX * perpZ;
+ double vZ = dirX * perpY - dirY * perpX;
+
+ // Default half-width and half-height (approximate from profile if possible)
+ (double hw, double hh) = EstimateProfileDimensions(profile, scale);
+
+ // 8 box vertices: 4 at p0, 4 at p1
+ double x0 = p0.X * scale;
+ double y0 = p0.Y * scale;
+ double z0 = p0.Z * scale;
+ double x1 = p1.X * scale;
+ double y1 = p1.Y * scale;
+ double z1 = p1.Z * scale;
+
+ int[] pts = new int[8];
+ // At start p0
+ pts[0] = AddPoint(w, x0 - perpX * hw - vX * hh, y0 - perpY * hw - vY * hh, z0 - perpZ * hw - vZ * hh);
+ pts[1] = AddPoint(w, x0 + perpX * hw - vX * hh, y0 + perpY * hw - vY * hh, z0 + perpZ * hw - vZ * hh);
+ pts[2] = AddPoint(w, x0 + perpX * hw + vX * hh, y0 + perpY * hw + vY * hh, z0 + perpZ * hw + vZ * hh);
+ pts[3] = AddPoint(w, x0 - perpX * hw + vX * hh, y0 - perpY * hw + vY * hh, z0 - perpZ * hw + vZ * hh);
+ // At end p1
+ pts[4] = AddPoint(w, x1 - perpX * hw - vX * hh, y1 - perpY * hw - vY * hh, z1 - perpZ * hw - vZ * hh);
+ pts[5] = AddPoint(w, x1 + perpX * hw - vX * hh, y1 + perpY * hw - vY * hh, z1 + perpZ * hw - vZ * hh);
+ pts[6] = AddPoint(w, x1 + perpX * hw + vX * hh, y1 + perpY * hw + vY * hh, z1 + perpZ * hw + vZ * hh);
+ pts[7] = AddPoint(w, x1 - perpX * hw + vX * hh, y1 - perpY * hw + vY * hh, z1 - perpZ * hw + vZ * hh);
+
+ // 6 faces (each as outer polyloop)
+ var faces = new List(6);
+ faces.Add(CreateFace(w, pts[3], pts[2], pts[1], pts[0])); // start cap
+ faces.Add(CreateFace(w, pts[4], pts[5], pts[6], pts[7])); // end cap
+ faces.Add(CreateFace(w, pts[0], pts[1], pts[5], pts[4])); // bottom
+ faces.Add(CreateFace(w, pts[1], pts[2], pts[6], pts[5])); // right
+ faces.Add(CreateFace(w, pts[2], pts[3], pts[7], pts[6])); // top
+ faces.Add(CreateFace(w, pts[3], pts[0], pts[4], pts[7])); // left
+
+ int shellId = w.Add("IFCCLOSEDSHELL", StepWriter.List(faces.Select(StepWriter.Ref)));
+ return w.Add("IFCFACETEDBREP", StepWriter.Ref(shellId));
+ }
+
+ private static (double HalfWidth, double HalfHeight) EstimateProfileDimensions(string profile, double scale)
+ {
+ double widthMm = 150.0;
+ double heightMm = 150.0;
+
+ if (!string.IsNullOrEmpty(profile))
+ {
+ string p = profile.ToUpperInvariant();
+ if (p.StartsWith("PL", StringComparison.OrdinalIgnoreCase))
+ {
+ // PL10*150 or PL10X150
+ var parts = p[2..].Split(['*', 'x', 'X']);
+ if (parts.Length >= 2)
+ {
+ bool parsedT = double.TryParse(parts[0], CultureInfo.InvariantCulture, out double t);
+ bool parsedW = double.TryParse(parts[1], CultureInfo.InvariantCulture, out double w);
+
+ if ((parsedT && !double.IsFinite(t)) || (parsedW && !double.IsFinite(w)))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite dimension in profile '{profile}'."));
+ }
+
+ if (parsedT && parsedW && t > 0 && w > 0)
+ {
+ heightMm = t;
+ widthMm = w;
+ }
+ }
+ }
+ else
+ {
+ // HEA300, IPE200, etc. Extract first integer
+ int idx = 0;
+ while (idx < p.Length && !char.IsDigit(p[idx])) idx++;
+ int end = idx;
+ while (end < p.Length && char.IsDigit(p[end])) end++;
+ if (end > idx && int.TryParse(p[idx..end], CultureInfo.InvariantCulture, out int size) && size > 10)
+ {
+ heightMm = size;
+ widthMm = p.StartsWith("IPE") ? size * 0.5 : size;
+ }
+ }
+ }
+
+ if (!double.IsFinite(widthMm) || !double.IsFinite(heightMm))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite dimension in profile '{profile}'."));
+ }
+
+ return (widthMm * 0.5 * scale, heightMm * 0.5 * scale);
+ }
+
+ private static int AddPoint(StepWriter w, double x, double y, double z) =>
+ w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(x), StepWriter.Real(y), StepWriter.Real(z)));
+
+ private static int CreateFace(StepWriter w, int p0, int p1, int p2, int p3)
+ {
+ int loopId = w.Add("IFCPOLYLOOP",
+ StepWriter.List(StepWriter.Ref(p0), StepWriter.Ref(p1), StepWriter.Ref(p2), StepWriter.Ref(p3)));
+ int boundId = w.Add("IFCFACEOUTERBOUND", $"{StepWriter.Ref(loopId)},.T.");
+ return w.Add("IFCFACE", StepWriter.List(StepWriter.Ref(boundId)));
+ }
+
+ private static void WritePartProperties(StepWriter w, int partStepId, ModelPart part, int ownerHistoryId, double scale)
+ {
+ var props = new List();
+
+ void AddLabel(string name, string? val)
+ {
+ if (!string.IsNullOrEmpty(val))
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str(name)},$,IFCLABEL({StepWriter.Str(val)}),$"));
+ }
+ }
+
+ void AddInteger(string name, int val)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str(name)},$,IFCINTEGER({val}),$"));
+ }
+
+ void AddReal(string name, double val)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str(name)},$,IFCREAL({StepWriter.RealExact(val)}),$"));
+ }
+
+ AddLabel("Tekla_PartMark", $"{part.Prefix}{part.PositionNumber}");
+ AddLabel("Tekla_Profile", part.Profile);
+ AddLabel("Tekla_Material", part.Material);
+ AddLabel("Tekla_Finish", part.Finish);
+ AddInteger("Tekla_Class", part.Class);
+ AddInteger("Tekla_Phase", part.Phase);
+ if (part.Length > 0)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str("Tekla_Length")},$,IFCLENGTHMEASURE({StepWriter.RealExact(part.Length * scale)}),$"));
+ }
+
+ foreach (var (k, v) in part.StringAttributes)
+ {
+ AddLabel($"Tekla_{k}", v);
+ }
+
+ foreach (var (k, v) in part.NumericAttributes)
+ {
+ AddReal($"Tekla_{k}", v);
+ }
+
+ if (props.Count > 0)
+ {
+ int psetId = w.Add("IFCPROPERTYSET",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},'Tekla_PartAttributes',$,{StepWriter.List(props.Select(StepWriter.Ref))}");
+ w.Add("IFCRELDEFINESBYPROPERTIES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(partStepId)}),{StepWriter.Ref(psetId)}");
+ }
+ }
+
+ private static void WriteAssemblyProperties(StepWriter w, int asmStepId, ModelAssembly asm, int ownerHistoryId)
+ {
+ var props = new List();
+
+ void AddLabel(string name, string? val)
+ {
+ if (!string.IsNullOrEmpty(val))
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str(name)},$,IFCLABEL({StepWriter.Str(val)}),$"));
+ }
+ }
+
+ void AddInteger(string name, int val)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str(name)},$,IFCINTEGER({val}),$"));
+ }
+
+ AddLabel("Tekla_AssemblyMark", $"{asm.Prefix}{asm.PositionNumber}");
+ AddLabel("Tekla_Prefix", asm.Prefix);
+ AddInteger("Tekla_StartNumber", asm.StartNumber);
+ AddInteger("Tekla_PositionNumber", asm.PositionNumber);
+ AddInteger("Tekla_Class", asm.Class);
+ AddInteger("Tekla_Phase", asm.Phase);
+ AddInteger("Tekla_AssemblyType", asm.AssemblyType);
+
+ foreach (var (k, v) in asm.StringAttributes)
+ {
+ AddLabel($"Tekla_{k}", v);
+ }
+
+ foreach (var (k, v) in asm.NumericAttributes)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str($"Tekla_{k}")},$,IFCREAL({StepWriter.RealExact(v)}),$"));
+ }
+
+ if (props.Count > 0)
+ {
+ int psetId = w.Add("IFCPROPERTYSET",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},'Tekla_AssemblyAttributes',$,{StepWriter.List(props.Select(StepWriter.Ref))}");
+ w.Add("IFCRELDEFINESBYPROPERTIES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(asmStepId)}),{StepWriter.Ref(psetId)}");
+ }
+ }
+
+ private static void WriteBoltProperties(StepWriter w, int boltStepId, ModelBolt bolt, int ownerHistoryId)
+ {
+ var props = new List
+ {
+ w.Add("IFCPROPERTYSINGLEVALUE", $"'Tekla_HoleCount',$,IFCINTEGER({bolt.Holes.Count}),$"),
+ w.Add("IFCPROPERTYSINGLEVALUE", $"'Tekla_PositionCount',$,IFCINTEGER({bolt.Positions.Count}),$"),
+ w.Add("IFCPROPERTYSINGLEVALUE", $"'Tekla_Phase',$,IFCINTEGER({bolt.Phase}),$")
+ };
+
+ foreach (var (k, v) in bolt.StringAttributes)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str($"Tekla_{k}")},$,IFCLABEL({StepWriter.Str(v)}),$"));
+ }
+
+ int psetId = w.Add("IFCPROPERTYSET",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},'Tekla_BoltAttributes',$,{StepWriter.List(props.Select(StepWriter.Ref))}");
+ w.Add("IFCRELDEFINESBYPROPERTIES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(boltStepId)}),{StepWriter.Ref(psetId)}");
+ }
+
+ private static void WriteWeldProperties(StepWriter w, int weldStepId, ModelWeld weld, int ownerHistoryId)
+ {
+ var props = new List
+ {
+ w.Add("IFCPROPERTYSINGLEVALUE", $"'Tekla_CommonAttrId',$,IFCINTEGER({weld.CommonAttrId}),$"),
+ w.Add("IFCPROPERTYSINGLEVALUE", $"'Tekla_Phase',$,IFCINTEGER({weld.Phase}),$")
+ };
+
+ foreach (var (k, v) in weld.StringAttributes)
+ {
+ props.Add(w.Add("IFCPROPERTYSINGLEVALUE", $"{StepWriter.Str($"Tekla_{k}")},$,IFCLABEL({StepWriter.Str(v)}),$"));
+ }
+
+ int psetId = w.Add("IFCPROPERTYSET",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},'Tekla_WeldAttributes',$,{StepWriter.List(props.Select(StepWriter.Ref))}");
+ w.Add("IFCRELDEFINESBYPROPERTIES",
+ $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(weldStepId)}),{StepWriter.Ref(psetId)}");
+ }
+}
diff --git a/src/TdbIO/Internal/Export/IfcGuid.cs b/src/TdbIO/Internal/Export/IfcGuid.cs
new file mode 100644
index 0000000..99fb399
--- /dev/null
+++ b/src/TdbIO/Internal/Export/IfcGuid.cs
@@ -0,0 +1,90 @@
+using System.Security.Cryptography;
+using System.Text;
+
+namespace TdbIO.Internal.Export;
+
+///
+/// IFC GlobalId encoding: 128-bit GUID to 22-character base64-like string.
+/// Uses IFC-specific alphabet: 0-9, A-Z, a-z, _, $.
+/// Algorithm standardized by buildingSMART IFC specification.
+///
+internal static class IfcGuid
+{
+ private const string Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
+
+ /// Convert a .NET Guid to IFC GlobalId (22 chars).
+ public static string ToIfcGuid(Guid guid)
+ {
+ var b = guid.ToByteArray();
+
+ // Rearrange .NET byte order (little-endian fields) to UUID big-endian
+ var u = new byte[16];
+ u[0] = b[3]; u[1] = b[2]; u[2] = b[1]; u[3] = b[0];
+ u[4] = b[5]; u[5] = b[4];
+ u[6] = b[7]; u[7] = b[6];
+ Array.Copy(b, 8, u, 8, 8);
+
+ // 128 bits -> 22 base-64 chars (22 * 6 = 132 bits, so 4 padding bits)
+ // Split into two 64-bit halves
+ ulong hi = 0, lo = 0;
+ for (int i = 0; i < 8; i++) hi = (hi << 8) | u[i];
+ for (int i = 8; i < 16; i++) lo = (lo << 8) | u[i];
+
+ var result = new char[22];
+ // Char 0: top 2 bits (padded to 6)
+ result[0] = Chars[(int)(hi >> 62) & 0x3F];
+ // Chars 1-10: next 60 bits from hi
+ result[1] = Chars[(int)(hi >> 56) & 0x3F];
+ result[2] = Chars[(int)(hi >> 50) & 0x3F];
+ result[3] = Chars[(int)(hi >> 44) & 0x3F];
+ result[4] = Chars[(int)(hi >> 38) & 0x3F];
+ result[5] = Chars[(int)(hi >> 32) & 0x3F];
+ result[6] = Chars[(int)(hi >> 26) & 0x3F];
+ result[7] = Chars[(int)(hi >> 20) & 0x3F];
+ result[8] = Chars[(int)(hi >> 14) & 0x3F];
+ result[9] = Chars[(int)(hi >> 8) & 0x3F];
+ result[10] = Chars[(int)(hi >> 2) & 0x3F];
+ // Char 11: 2 bits from hi + 4 bits from lo
+ result[11] = Chars[(int)(((hi & 0x03) << 4) | ((lo >> 60) & 0x0F))];
+ // Chars 12-21: remaining 60 bits from lo
+ result[12] = Chars[(int)(lo >> 54) & 0x3F];
+ result[13] = Chars[(int)(lo >> 48) & 0x3F];
+ result[14] = Chars[(int)(lo >> 42) & 0x3F];
+ result[15] = Chars[(int)(lo >> 36) & 0x3F];
+ result[16] = Chars[(int)(lo >> 30) & 0x3F];
+ result[17] = Chars[(int)(lo >> 24) & 0x3F];
+ result[18] = Chars[(int)(lo >> 18) & 0x3F];
+ result[19] = Chars[(int)(lo >> 12) & 0x3F];
+ result[20] = Chars[(int)(lo >> 6) & 0x3F];
+ result[21] = Chars[(int)lo & 0x3F];
+
+ return new string(result);
+ }
+
+ /// Generate a new random IFC GUID (22 chars).
+ public static string NewGuid() => ToIfcGuid(Guid.NewGuid());
+
+ /// Generate a deterministic IFC GUID from element ID and a namespace string.
+ public static string FromElementId(int elemId, string ns = "Tekla")
+ {
+ var bytes = Encoding.UTF8.GetBytes($"{ns}:{elemId}");
+ var hash = SHA256.HashData(bytes);
+ var guidBytes = new byte[16];
+ Array.Copy(hash, 0, guidBytes, 0, 16);
+ guidBytes[6] = (byte)((guidBytes[6] & 0x0F) | 0x30); // version 3/4
+ guidBytes[8] = (byte)((guidBytes[8] & 0x3F) | 0x80); // RFC 4122 variant
+ return ToIfcGuid(new Guid(guidBytes));
+ }
+
+ /// Generate a deterministic IFC GUID from a string key.
+ public static string FromKey(string key)
+ {
+ var bytes = Encoding.UTF8.GetBytes($"Tekla:key:{key}");
+ var hash = SHA256.HashData(bytes);
+ var guidBytes = new byte[16];
+ Array.Copy(hash, 0, guidBytes, 0, 16);
+ guidBytes[6] = (byte)((guidBytes[6] & 0x0F) | 0x30);
+ guidBytes[8] = (byte)((guidBytes[8] & 0x3F) | 0x80);
+ return ToIfcGuid(new Guid(guidBytes));
+ }
+}
diff --git a/src/TdbIO/Internal/Export/StepWriter.cs b/src/TdbIO/Internal/Export/StepWriter.cs
new file mode 100644
index 0000000..5e7246a
--- /dev/null
+++ b/src/TdbIO/Internal/Export/StepWriter.cs
@@ -0,0 +1,158 @@
+using System.Globalization;
+using System.Text;
+
+namespace TdbIO.Internal.Export;
+
+///
+/// Low-level IFC STEP physical file writer (ISO 10303-21).
+/// Manages entity IDs, argument formatting, Unicode character escaping, and file structure.
+///
+internal sealed class StepWriter
+{
+ private int _nextId = 1;
+ private readonly List<(int Id, string Type, string Args)> _entities = new(4096);
+
+ public int NextId() => _nextId++;
+
+ /// Adds an entity and returns its assigned #ID.
+ public int Add(string type, string args)
+ {
+ int id = _nextId++;
+ _entities.Add((id, type, args));
+ return id;
+ }
+
+ public int EntityCount => _entities.Count;
+
+ public (int Id, string Type, string Args) EntityAt(int index) => _entities[index];
+
+ public void ReplaceArgs(int index, string args)
+ {
+ var (id, type, _) = _entities[index];
+ _entities[index] = (id, type, args);
+ }
+
+ /// Writes the complete IFC STEP file to a .
+ public void WriteTo(
+ TextWriter w,
+ string fileName,
+ string schema = "IFC2X3",
+ string description = "ViewDefinition [CoordinationView_V2.0]",
+ string application = "TdbIO",
+ string organization = "IOExtend",
+ string author = "")
+ {
+ var now = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
+
+ w.WriteLine("ISO-10303-21;");
+ w.WriteLine("HEADER;");
+ w.WriteLine($"FILE_DESCRIPTION(('{Escape(description)}'),'2;1');");
+ w.WriteLine($"FILE_NAME('{Escape(fileName)}','{now}',('{Escape(author)}'),('{Escape(organization)}'),'{Escape(application)}','TdbIO','');");
+ w.WriteLine($"FILE_SCHEMA(('{Escape(schema)}'));");
+ w.WriteLine("ENDSEC;");
+ w.WriteLine("DATA;");
+
+ for (int i = 0; i < _entities.Count; i++)
+ {
+ var (id, type, args) = _entities[i];
+ w.Write('#');
+ w.Write(id);
+ w.Write('=');
+ w.Write(type);
+ w.Write('(');
+ w.Write(args);
+ w.WriteLine(");");
+ }
+
+ w.WriteLine("ENDSEC;");
+ w.WriteLine("END-ISO-10303-21;");
+ }
+
+ public static string Ref(int id) => $"#{id}";
+
+ public static string Str(string? s) => s is null ? "$" : $"'{Escape(s)}'";
+
+ public static string Enum(string v) => $".{v}.";
+
+ public static string List(params string[] items) => $"({string.Join(",", items)})";
+
+ public static string List(IEnumerable items) => $"({string.Join(",", items)})";
+
+ public static string Real(double v)
+ {
+ if (!double.IsFinite(v))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite number {v} cannot be written to IFC."));
+ }
+ string text = v.ToString("0.######", CultureInfo.InvariantCulture);
+ return text.Contains('.') ? text : text + ".";
+ }
+
+ public static string RealExact(double v)
+ {
+ if (!double.IsFinite(v))
+ {
+ throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, $"Non-finite number {v} cannot be written to IFC."));
+ }
+ string text = v.ToString("G17", CultureInfo.InvariantCulture);
+ int expIdx = text.IndexOfAny(['e', 'E']);
+ if (expIdx >= 0)
+ {
+ string mantissa = text[..expIdx];
+ if (!mantissa.Contains('.'))
+ {
+ text = string.Concat(mantissa, ".", text.AsSpan(expIdx));
+ }
+ }
+ else if (!text.Contains('.'))
+ {
+ text += ".";
+ }
+ return text;
+ }
+
+ ///
+ /// Escapes string according to ISO 10303-21 STEP rules:
+ /// - Extended Unicode characters (e.g. Cyrillic) encoded as \X2\HHHH...\X0\
+ /// - Single quotes escaped as ''
+ /// - Backslashes escaped as \\
+ ///
+ public static string Escape(string s)
+ {
+ if (string.IsNullOrEmpty(s))
+ {
+ return string.Empty;
+ }
+
+ var sb = new StringBuilder(s.Length * 2);
+ bool inUnicode = false;
+
+ foreach (char c in s)
+ {
+ if (c < 0x100 && (c > 0x7E || c < 0x20))
+ {
+ if (inUnicode) { sb.Append("\\X0\\"); inUnicode = false; }
+ sb.Append("\\X\\").Append(((int)c).ToString("X2", CultureInfo.InvariantCulture));
+ }
+ else if (c > 0x7E || c < 0x20)
+ {
+ if (!inUnicode) { sb.Append("\\X2\\"); inUnicode = true; }
+ sb.Append(((int)c).ToString("X4", CultureInfo.InvariantCulture));
+ }
+ else
+ {
+ if (inUnicode) { sb.Append("\\X0\\"); inUnicode = false; }
+ if (c == '\\') sb.Append("\\\\");
+ else if (c == '\'') sb.Append("''");
+ else sb.Append(c);
+ }
+ }
+
+ if (inUnicode)
+ {
+ sb.Append("\\X0\\");
+ }
+
+ return sb.ToString();
+ }
+}
diff --git a/src/TdbIO/TdbIO.csproj b/src/TdbIO/TdbIO.csproj
index f0cd92b..1d9b823 100644
--- a/src/TdbIO/TdbIO.csproj
+++ b/src/TdbIO/TdbIO.csproj
@@ -11,6 +11,7 @@
+
diff --git a/src/TdbIO/TeklaIfcExportOptions.cs b/src/TdbIO/TeklaIfcExportOptions.cs
new file mode 100644
index 0000000..503487b
--- /dev/null
+++ b/src/TdbIO/TeklaIfcExportOptions.cs
@@ -0,0 +1,46 @@
+namespace TdbIO;
+
+///
+/// Options controlling IFC STEP physical file export from .
+///
+public sealed class TeklaIfcExportOptions
+{
+ /// The IFC schema version to export (e.g. "IFC2X3" or "IFC4"). Default is "IFC2X3".
+ public string SchemaVersion { get; set; } = "IFC2X3";
+
+ /// The IFC project name, or null to derive from model or default.
+ public string? ProjectName { get; set; }
+
+ /// The IFC building name.
+ public string BuildingName { get; set; } = "Tekla Building";
+
+ /// The IFC building storey name.
+ public string StoreyName { get; set; } = "Level 1";
+
+ /// The name of the producing application. Default is "TdbIO".
+ public string Application { get; set; } = "TdbIO";
+
+ /// The organization name. Default is "IOExtend".
+ public string Organization { get; set; } = "IOExtend";
+
+ /// The author name.
+ public string Author { get; set; } = "";
+
+ /// Whether to export Tekla user-defined and numeric properties as IFC property sets. Default is true.
+ public bool ExportProperties { get; set; } = true;
+
+ /// Whether to group parts under their assemblies (IFCELEMENTASSEMBLY). Default is true.
+ public bool ExportAssemblies { get; set; } = true;
+
+ /// Whether to export bolt groups as IFCMECHANICALFASTENER. Default is true.
+ public bool ExportBolts { get; set; } = true;
+
+ /// Whether to export welds as IFCFASTENER. Default is true.
+ public bool ExportWelds { get; set; } = true;
+
+ /// Whether to export part geometry as IFC faceted BREPs. Default is true.
+ public bool ExportGeometry { get; set; } = true;
+
+ /// Whether to convert Tekla model millimeters to IFC standard metres (0.001 scale factor). Default is true.
+ public bool ConvertMmToMetres { get; set; } = true;
+}
diff --git a/src/TdbIO/TeklaModel.cs b/src/TdbIO/TeklaModel.cs
index d75d5ea..9f2405c 100644
--- a/src/TdbIO/TeklaModel.cs
+++ b/src/TdbIO/TeklaModel.cs
@@ -1,3 +1,5 @@
+using System.Globalization;
+
namespace TdbIO;
/// Represents an in-memory, read-only object model decoded from a Tekla Structures model database (.db1).
@@ -101,6 +103,97 @@ internal TeklaModel(
/// Writes the decoded model as JSON using a .
/// The UTF-8 JSON writer.
public void WriteJson(System.Text.Json.Utf8JsonWriter writer) => Internal.ModelJsonWriter.Write(this, writer);
+
+ /// Serializes the decoded model to an IFC STEP physical file string.
+ /// Options controlling IFC export, or null for defaults.
+ /// An IFC STEP string representation of the model.
+ public string ToIfc(TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.ToString(this, options);
+
+ /// Writes the decoded model as an IFC STEP physical file to a stream.
+ /// The output stream.
+ /// Options controlling IFC export, or null for defaults.
+ public void WriteIfc(Stream stream, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.Write(this, stream, options);
+
+ /// Writes the decoded model as an IFC STEP physical file to a file path.
+ /// The destination file path.
+ /// Options controlling IFC export, or null for defaults.
+ public void WriteIfc(string path, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.WriteFile(this, path, options);
+
+ /// Validates that all geometric coordinates, lengths and numeric attributes are finite floating-point numbers.
+ /// Thrown when any coordinate, dimension or numeric attribute is NaN or Infinity.
+ public void ValidateFiniteNumbers()
+ {
+ static void Check(string propertyName, double value, long offset = 0)
+ {
+ if (!double.IsFinite(value))
+ throw Internal.FormatError.At(string.Create(CultureInfo.InvariantCulture, $"Non-finite number {value} in '{propertyName}'"), offset);
+ }
+
+ static void CheckPoint(ModelPoint pt)
+ {
+ long ptOff = pt.Offset;
+ Check("x", pt.X, ptOff > 0 ? ptOff + 8 : 0);
+ Check("y", pt.Y, ptOff > 0 ? ptOff + 16 : 0);
+ Check("z", pt.Z, ptOff > 0 ? ptOff + 24 : 0);
+ }
+
+ static void CheckAttributes(ModelObject obj)
+ {
+ foreach (var (k, v) in obj.NumericAttributes)
+ {
+ long off = obj.NumericAttributeOffsets?.GetValueOrDefault(k) ?? 0;
+ Check(k, v, off);
+ }
+ }
+
+ foreach (var p in Parts)
+ {
+ Check("length", p.Length, p.LengthOffset);
+ if (p.StartPoint.HasValue) CheckPoint(p.StartPoint.Value);
+ if (p.EndPoint.HasValue) CheckPoint(p.EndPoint.Value);
+ if (p.CoordinateSystem.HasValue)
+ {
+ var cs = p.CoordinateSystem.Value;
+ long csOff = cs.Offset;
+ Check("x", cs.X, csOff > 0 ? csOff + 8 : 0);
+ Check("y", cs.Y, csOff > 0 ? csOff + 16 : 0);
+ Check("z", cs.Z, csOff > 0 ? csOff + 24 : 0);
+ Check("length", cs.Length, csOff > 0 ? csOff + 32 : 0);
+ }
+ CheckAttributes(p);
+ }
+
+ foreach (var a in Assemblies)
+ {
+ CheckAttributes(a);
+ }
+
+ foreach (var b in Bolts)
+ {
+ if (b.FirstPoint.HasValue) CheckPoint(b.FirstPoint.Value);
+ if (b.SecondPoint.HasValue) CheckPoint(b.SecondPoint.Value);
+ foreach (var h in b.Holes)
+ {
+ long hOff = h.Offset;
+ Check("pointZ", h.PointZ, hOff > 0 ? hOff + 16 : 0);
+ Check("length", h.Length, hOff > 0 ? hOff + 24 : 0);
+ Check("shorteningLength", h.ShorteningLength, hOff > 0 ? hOff + 40 : 0);
+ }
+ foreach (var pos in b.Positions)
+ {
+ long posOff = pos.Offset;
+ Check("x", pos.X, posOff > 0 ? posOff + 8 : 0);
+ Check("y", pos.Y, posOff > 0 ? posOff + 16 : 0);
+ Check("z", pos.Z, posOff > 0 ? posOff + 24 : 0);
+ }
+ CheckAttributes(b);
+ }
+
+ foreach (var w in Welds)
+ {
+ CheckAttributes(w);
+ }
+ }
}
/// Base class for all entities in a Tekla Structures model.
@@ -137,6 +230,11 @@ public ModelObject(
/// The unique RFC 4122 GUID of the object.
public Guid Guid { get; }
+ /// The 22-character buildingSMART IFC GlobalId corresponding to , or derived from .
+ public string IfcGuid => Guid != Guid.Empty
+ ? Internal.Export.IfcGuid.ToIfcGuid(Guid)
+ : Internal.Export.IfcGuid.FromElementId(Id, GetType().Name);
+
/// The object type code (e.g. 1 for part, 2 for assembly, 3 for connection, 9 for bolt, 13 for weld).
public int Type { get; }
@@ -473,3 +571,13 @@ public readonly record struct ModelBoltHole(
///
public override string ToString() => $"Hole #{No} in Part #{PartId} Grip={Length:F1}";
}
+
+/// Utilities for buildingSMART IFC GlobalId generation and conversion.
+public static class TeklaIfcGuid
+{
+ /// Converts a .NET Guid to a 22-character buildingSMART IFC GlobalId.
+ public static string ToIfcGuid(Guid guid) => Internal.Export.IfcGuid.ToIfcGuid(guid);
+
+ /// Generates a deterministic 22-character buildingSMART IFC GlobalId from an element identifier.
+ public static string FromElementId(int elemId, string ns = "Tekla") => Internal.Export.IfcGuid.FromElementId(elemId, ns);
+}
diff --git a/tests/TdbIO.Scene.Tests/TdbIO.Scene.Tests.csproj b/tests/TdbIO.Scene.Tests/TdbIO.Scene.Tests.csproj
new file mode 100644
index 0000000..07c67a0
--- /dev/null
+++ b/tests/TdbIO.Scene.Tests/TdbIO.Scene.Tests.csproj
@@ -0,0 +1,28 @@
+
+
+
+ net8.0;net10.0
+ false
+ true
+ TdbIO.Scene.Tests
+
+
+
+
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs
new file mode 100644
index 0000000..1188570
--- /dev/null
+++ b/tests/TdbIO.Scene.Tests/TdbSceneReaderTests.cs
@@ -0,0 +1,312 @@
+using System.Text;
+using System.Text.Json;
+using IOScene;
+using IOViewer.Exporters;
+using TdbIO.CommandLine;
+using Xunit;
+
+namespace TdbIO.Scene.Tests;
+
+public sealed class TdbSceneReaderTests
+{
+ [Fact]
+ public void Read_ConvertsTeklaModelToValidSceneDocument()
+ {
+ var model = CreateSyntheticModel();
+ var result = TdbSceneReader.Read(model, new TdbSceneOptions { ModelKey = "test_model.db1" });
+
+ // Contract validation: MUST have 0 errors and 0 warnings
+ var diagnostics = result.Document.Validate();
+ Assert.Empty(diagnostics);
+
+ // Verify Model metadata
+ var sceneModel = Assert.Single(result.Document.Models);
+ Assert.Equal("test_model.db1", sceneModel.Key);
+ Assert.Equal("test_model.db1", sceneModel.Name);
+ Assert.Equal("db1", sceneModel.SourceFormat);
+ Assert.Equal("mm", sceneModel.SourceLengthUnit);
+ Assert.Equal("Tekla Structures", sceneModel.Application);
+ Assert.StartsWith("TdbIO.Scene", sceneModel.Producer);
+ Assert.Equal(0.001, result.MetresPerUnit);
+
+ // Verify Element counts
+ Assert.Equal(5, result.ElementCount); // 1 assembly + 2 parts + 1 bolt + 1 weld
+ Assert.True(result.ElementsWithGeometry >= 2);
+
+ // Verify Root model element
+ var rootElem = Assert.Single(result.Document.Elements, e => e.Kind == SceneNodeKind.Model);
+ Assert.Equal(1L, rootElem.Id);
+ Assert.Null(rootElem.ParentId);
+
+ // Verify Assembly element
+ var asmElem = Assert.Single(result.Document.Elements, e => e.Kind == SceneNodeKind.Group);
+ Assert.Equal(1L, asmElem.ParentId);
+ Assert.Equal("Assembly", asmElem.Category);
+ Assert.Contains("ROOF_BEAM_ASM", asmElem.Name);
+ Assert.NotEmpty(asmElem.PropertySetIds);
+
+ // Verify Parts elements
+ var partElems = result.Document.Elements.Where(e => e.Category == "Part").ToList();
+ Assert.Equal(2, partElems.Count);
+
+ var beamElem = Assert.Single(partElems, p => p.TypeName == "HEA300");
+ Assert.Equal(asmElem.Id, beamElem.ParentId); // Child of assembly
+ Assert.NotEmpty(beamElem.PropertySetIds);
+
+ var colElem = Assert.Single(partElems, p => p.TypeName == "HEB300");
+ Assert.Equal(1L, colElem.ParentId); // Standalone part, child of root model
+
+ // Verify PropertySets
+ var partPset = Assert.Single(result.Document.PropertySets, p => p.Key == "tekla:part" && p.Properties.Any(prop => prop.Name == "Profile" && prop.Value.Text == "HEA300"));
+ var lengthProp = Assert.Single(partPset.Properties, p => p.Name == "Length");
+ Assert.Equal(SceneValueKind.Number, lengthProp.Value.Kind);
+ Assert.Equal(6.0, lengthProp.Value.Number); // 6000 mm -> 6.0 m
+ Assert.Equal("m", lengthProp.Value.Unit);
+
+ // Verify Geometries & Instances
+ Assert.NotEmpty(result.Document.Geometries);
+ Assert.NotEmpty(result.Document.Instances);
+
+ foreach (var geom in result.Document.Geometries)
+ {
+ Assert.Equal(SceneTopology.Triangles, geom.Topology);
+ Assert.Equal(geom.Vertices.Count, geom.Normals?.Count);
+ Assert.True(geom.Indices.Count % 3 == 0);
+ }
+
+ // Verify Materials & Colors
+ Assert.NotEmpty(result.Document.Materials);
+ var instance = Assert.Single(result.Document.Instances, i => i.ElementId == beamElem.Id);
+ Assert.NotNull(instance.MaterialId);
+ Assert.NotNull(instance.Color);
+ }
+
+ [Fact]
+ public void SceneJson_Roundtrip_SucceedsAndValidates()
+ {
+ var model = CreateSyntheticModel();
+ var result = TdbSceneReader.Read(model, new TdbSceneOptions { ModelKey = "building.db1" });
+
+ using var ms = new MemoryStream();
+ SceneJson.Write(result.Document, ms);
+ ms.Position = 0;
+
+ var roundtripDoc = SceneJson.Read(ms);
+ Assert.NotNull(roundtripDoc);
+ Assert.Equal("building.db1", roundtripDoc.Title);
+ Assert.Empty(roundtripDoc.Validate());
+ }
+
+ [Fact]
+ public void HtmlViewerExporter_ExportsInteractiveViewer()
+ {
+ var model = CreateSyntheticModel();
+ var result = TdbSceneReader.Read(model, new TdbSceneOptions { ModelKey = "building.db1" });
+
+ string html = HtmlViewerExporter.ExportToString(result.Document);
+ Assert.False(string.IsNullOrWhiteSpace(html));
+ Assert.Contains("", html);
+ Assert.Contains("IOViewer", html);
+ Assert.Contains("building.db1", html);
+
+ string tempPath = Path.Combine(Path.GetTempPath(), $"viewer_{Guid.NewGuid():N}.html");
+ try
+ {
+ HtmlViewerExporter.Save(result.Document, tempPath);
+ Assert.True(File.Exists(tempPath));
+ string fileContent = File.ReadAllText(tempPath);
+ Assert.Contains("", fileContent);
+ }
+ finally
+ {
+ if (File.Exists(tempPath)) File.Delete(tempPath);
+ }
+ }
+
+ [Fact]
+ public void Read_RejectsNonFiniteProfile()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "BEAM",
+ profile: "PLNaN*200",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null);
+
+ var doc = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([]));
+ var model = new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: [beam], bolts: [], welds: [], objects: [beam]);
+
+ Assert.Throws(() => TdbSceneReader.Read(model));
+ }
+
+ [Fact]
+ public void Read_AcceptsFiniteCustomProfileWithSubstrings()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "BEAM",
+ profile: "CUSTOM_NANO200",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null);
+
+ var doc = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([]));
+ var model = new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: [beam], bolts: [], welds: [], objects: [beam]);
+
+ var result = TdbSceneReader.Read(model);
+ Assert.NotNull(result);
+ Assert.Empty(result.Document.Validate());
+ }
+
+ [Fact]
+ public void Cli_Export_CommandsWorkCorrectly()
+ {
+ // Test usage errors and options
+ var err = new StringWriter();
+ var @out = new StringWriter();
+
+ // Mutually exclusive flags
+ int code = Cli.Run(["export", "dummy.db1", "--ifc", "--html"], @out, err);
+ Assert.Equal(Cli.ExitUsage, code);
+ Assert.Contains("mutually exclusive", err.ToString());
+ }
+
+ private static TeklaModel CreateSyntheticModel()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var p2 = new ModelPoint(3, 0, 0, 3000);
+
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ name: "STEEL_BEAM",
+ profile: "HEA300",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "PAINT",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null,
+ stringAttributes: new Dictionary { ["COMMENT"] = "Roof beam" },
+ numericAttributes: new Dictionary { ["WEIGHT"] = 530.4 });
+
+ var column = new ModelPart(
+ id: 102,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "COLUMN",
+ profile: "HEB300",
+ material: "S355J2",
+ prefix: "C",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 4,
+ finish: "",
+ startPoint: p0,
+ endPoint: p2,
+ length: 3000,
+ coordinateSystem: null);
+
+ var assembly = new ModelAssembly(
+ id: 201,
+ guid: Guid.NewGuid(),
+ type: 2,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ name: "ROOF_BEAM_ASM",
+ prefix: "A",
+ startNumber: 1,
+ positionNumber: 1,
+ assemblyType: 0,
+ @class: 3);
+
+ beam.Assembly = assembly;
+ assembly.MainPart = beam;
+ assembly.Parts = [beam];
+
+ var bolt = new ModelBolt(
+ id: 301,
+ guid: Guid.NewGuid(),
+ type: 9,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ firstPoint: p0,
+ secondPoint: p1,
+ holes: [new ModelBoltHole(1, 101, beam, 0, 20, 0, 0, 0)],
+ positions: [new ModelPoint(5, 100, 50, 0)]);
+ bolt.Assembly = assembly;
+
+ var weld = new ModelWeld(
+ id: 401,
+ guid: Guid.NewGuid(),
+ type: 13,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ commonAttrId: 501);
+ weld.Assembly = assembly;
+
+ assembly.Bolts = [bolt];
+ assembly.Welds = [weld];
+
+ var document = Db1Document.Create(TdbIO.Tests.Synthetic.Db1Payload([]));
+
+ return new TeklaModel(
+ document,
+ Guid.NewGuid(),
+ assemblies: [assembly],
+ parts: [beam, column],
+ bolts: [bolt],
+ welds: [weld],
+ objects: [beam, column, assembly, bolt, weld]);
+ }
+}
diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs
index c9935dc..94c39a2 100644
--- a/tests/TdbIO.Tests/CliTests.cs
+++ b/tests/TdbIO.Tests/CliTests.cs
@@ -1,4 +1,5 @@
using System.Buffers.Binary;
+using System.Text;
using System.Text.Json;
using TdbIO.CommandLine;
using Xunit;
@@ -413,6 +414,312 @@ public void ExportOnModelWithNonFiniteNumberReturnsExitInput()
Assert.Equal(1000.0, json.RootElement.GetProperty("parts")[0].GetProperty("length").GetDouble());
}
+ [Fact]
+ public void Export_ToIfcHtmlAndSceneJson_Succeeds()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1); // Part
+
+ var partBytes = new byte[PartRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), 1000.0);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+ byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2));
+
+ string okFile = File("export_test.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, partSec)));
+
+ // 1. Export to IFC file
+ string ifcOut = Path.Combine(_folder, "model.ifc");
+ var (ifcExit, _, ifcErr) = Run("export", okFile, ifcOut);
+ Assert.Equal(Cli.ExitOk, ifcExit);
+ Assert.Empty(ifcErr);
+ Assert.True(System.IO.File.Exists(ifcOut));
+ Assert.Contains("ISO-10303-21;", System.IO.File.ReadAllText(ifcOut));
+
+ // 2. Export to HTML viewer file
+ string htmlOut = Path.Combine(_folder, "model.html");
+ var (htmlExit, _, htmlErr) = Run("export", okFile, htmlOut);
+ Assert.Equal(Cli.ExitOk, htmlExit);
+ Assert.Empty(htmlErr);
+ Assert.True(System.IO.File.Exists(htmlOut));
+ Assert.Contains("", System.IO.File.ReadAllText(htmlOut));
+
+ // 3. Export to Scene JSON file
+ string sceneJsonOut = Path.Combine(_folder, "model.scene.json");
+ var (sceneExit, _, sceneErr) = Run("export", okFile, sceneJsonOut, "--scene-json");
+ Assert.Equal(Cli.ExitOk, sceneExit);
+ Assert.Empty(sceneErr);
+ Assert.True(System.IO.File.Exists(sceneJsonOut));
+ Assert.Contains("\"Kind\"", System.IO.File.ReadAllText(sceneJsonOut));
+
+ // 4. Export IFC to stdout
+ var (stdoutIfcExit, stdoutIfc, stdoutIfcErr) = Run("export", okFile, "--ifc");
+ Assert.Equal(Cli.ExitOk, stdoutIfcExit);
+ Assert.Empty(stdoutIfcErr);
+ Assert.StartsWith("ISO-10303-21;", stdoutIfc);
+ }
+
+ [Fact]
+ public void Export_RejectsOutputPathIdenticalToInputFile()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+
+ byte[] originalContent = Gzip(Db1TablesPayload(unkeyedSec, objSec));
+ string inputFile = File("identity_test.db1", originalContent);
+
+ // Identical path
+ var (exit1, _, err1) = Run("export", inputFile, inputFile);
+ Assert.Equal(Cli.ExitUsage, exit1);
+ Assert.Contains("The output file path must not be the same as the input file.", err1);
+ Assert.Equal(originalContent, System.IO.File.ReadAllBytes(inputFile));
+
+ // Redundant relative segments resolving to the same file
+ string redundantPath = Path.Combine(Path.GetDirectoryName(inputFile)!, ".", Path.GetFileName(inputFile));
+ var (exit2, _, err2) = Run("export", inputFile, redundantPath);
+ Assert.Equal(Cli.ExitUsage, exit2);
+ Assert.Contains("The output file path must not be the same as the input file.", err2);
+ Assert.Equal(originalContent, System.IO.File.ReadAllBytes(inputFile));
+ }
+
+ [Fact]
+ public void Export_PreservesPreviousDestinationWhenConversionFails()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ var partBytes = new byte[PartRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), double.NaN); // NaN in length
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+ byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2));
+
+ string nanFile = File("nan_length.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, partSec)));
+ string destFile = Path.Combine(_folder, "existing_report.txt");
+ const string sentinel = "EXISTING_REPORT";
+ System.IO.File.WriteAllText(destFile, sentinel);
+
+ var (exit, _, err) = Run("export", nanFile, destFile);
+ Assert.Equal(Cli.ExitInput, exit);
+ Assert.Contains("Non-finite number", err);
+ Assert.Equal(sentinel, System.IO.File.ReadAllText(destFile));
+ }
+
+ [Fact]
+ public void Export_RejectsNonFiniteModelDataAcrossRenderers()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ var pointBytes = new byte[PointRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(pointBytes.AsSpan(0), 201);
+ BinaryPrimitives.WriteDoubleLittleEndian(pointBytes.AsSpan(8), double.NaN); // NaN in point X
+
+ var partBytes = new byte[PartRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(16), 201); // EndPointId = 201
+ BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), 1000.0);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+ byte[] ptSec = Db1Section(PointRow.TableKey, PointRow.ExpectedRowSize, [1], (0x04, pointBytes, 1, 2));
+ byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2));
+
+ string nanCoordFile = File("nan_coord.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, ptSec, partSec)));
+
+ // 1. Scene JSON export rejected
+ var (sceneExit, _, sceneErr) = Run("export", nanCoordFile, "--scene-json");
+ Assert.Equal(Cli.ExitInput, sceneExit);
+ Assert.Contains("Non-finite number", sceneErr);
+ Assert.Contains("offset", sceneErr);
+
+ // 2. IFC export rejected
+ var (ifcExit, _, ifcErr) = Run("export", nanCoordFile, "--ifc");
+ Assert.Equal(Cli.ExitInput, ifcExit);
+ Assert.Contains("Non-finite number", ifcErr);
+ Assert.Contains("offset", ifcErr);
+
+ // 3. HTML export rejected and output file not created
+ string htmlPath = Path.Combine(_folder, "should_not_exist.html");
+ var (htmlExit, _, htmlErr) = Run("export", nanCoordFile, htmlPath);
+ Assert.Equal(Cli.ExitInput, htmlExit);
+ Assert.Contains("Non-finite number", htmlErr);
+ Assert.False(System.IO.File.Exists(htmlPath));
+ }
+
+ [Fact]
+ public void Export_RejectsOutputPathIdenticalViaDirectoryJunction()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+
+ string targetDir = Path.Combine(_folder, "alias-target");
+ string linkDir = Path.Combine(_folder, "alias-link");
+ Directory.CreateDirectory(targetDir);
+
+ using var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
+ {
+ FileName = "cmd.exe",
+ Arguments = $"/c mklink /J \"{linkDir}\" \"{targetDir}\"",
+ CreateNoWindow = true,
+ UseShellExecute = false
+ });
+ proc?.WaitForExit();
+ if (!Directory.Exists(linkDir)) return;
+
+ try
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+
+ byte[] originalContent = Gzip(Db1TablesPayload(unkeyedSec, objSec));
+ string targetFile = Path.Combine(targetDir, "model.db1");
+ System.IO.File.WriteAllBytes(targetFile, originalContent);
+ string linkFile = Path.Combine(linkDir, "model.db1");
+
+ var (exit, _, err) = Run("export", linkFile, targetFile);
+ Assert.Equal(Cli.ExitUsage, exit);
+ Assert.Contains("The output file path must not be the same as the input file.", err);
+ Assert.Equal(originalContent, System.IO.File.ReadAllBytes(targetFile));
+ }
+ finally
+ {
+ if (Directory.Exists(linkDir))
+ {
+ Directory.Delete(linkDir, false);
+ }
+ }
+ }
+
+ [Fact]
+ public void Export_RejectsNonFiniteProfileAcrossRenderers()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ var pointBytes1 = new byte[PointRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(pointBytes1.AsSpan(0), 201);
+ var pointBytes2 = new byte[PointRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(pointBytes2.AsSpan(0), 202);
+ BinaryPrimitives.WriteDoubleLittleEndian(pointBytes2.AsSpan(8), 1000.0);
+
+ var partAttrBytes = new byte[PartAttrRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partAttrBytes.AsSpan(0), 501);
+ Encoding.ASCII.GetBytes("PLNaN*200").CopyTo(partAttrBytes.AsSpan(116));
+
+ var partBytes = new byte[PartRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(4), 501); // PartAttrId = 501
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(12), 201); // StartPointId = 201
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(16), 202); // EndPointId = 202
+ BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), 1000.0);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+ byte[] ptSec = Db1Section(PointRow.TableKey, PointRow.ExpectedRowSize, [1, 1],
+ (0x04, pointBytes1, 1, 2),
+ (0x04, pointBytes2, 2, 3));
+ byte[] paSec = Db1Section(PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize, [1], (0x04, partAttrBytes, 1, 2));
+ byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2));
+
+ string nanProfFile = File("nan_prof.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, ptSec, paSec, partSec)));
+
+ // 1. IFC export rejected
+ var (ifcExit, _, ifcErr) = Run("export", nanProfFile, "--ifc");
+ Assert.Equal(Cli.ExitInput, ifcExit);
+ Assert.Contains("Non-finite", ifcErr);
+ Assert.Contains("PLNaN*200", ifcErr);
+
+ // 2. Scene JSON export rejected
+ var (sceneExit, _, sceneErr) = Run("export", nanProfFile, "--scene-json");
+ Assert.Equal(Cli.ExitInput, sceneExit);
+ Assert.Contains("Non-finite", sceneErr);
+ Assert.Contains("PLNaN*200", sceneErr);
+
+ // 3. HTML export rejected and output file not created
+ string htmlPath = Path.Combine(_folder, "should_not_exist_prof.html");
+ var (htmlExit, _, htmlErr) = Run("export", nanProfFile, htmlPath);
+ Assert.Equal(Cli.ExitInput, htmlExit);
+ Assert.Contains("Non-finite", htmlErr);
+ Assert.False(System.IO.File.Exists(htmlPath));
+ }
+
+ [Fact]
+ public void Export_AcceptsFiniteCustomProfileWithSubstringsAcrossAllRenderers()
+ {
+ var objBytes = new byte[ObjectRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1);
+
+ var pointBytes1 = new byte[PointRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(pointBytes1.AsSpan(0), 201);
+ var pointBytes2 = new byte[PointRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(pointBytes2.AsSpan(0), 202);
+ BinaryPrimitives.WriteDoubleLittleEndian(pointBytes2.AsSpan(8), 6000.0);
+
+ var partAttrBytes = new byte[PartAttrRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partAttrBytes.AsSpan(0), 501);
+ Encoding.ASCII.GetBytes("CUSTOM_NANO200").CopyTo(partAttrBytes.AsSpan(116));
+
+ var partBytes = new byte[PartRow.ExpectedRowSize];
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101);
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(4), 501);
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(12), 201);
+ BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(16), 202);
+ BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), 6000.0);
+
+ byte[] unkeyedSec = Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2));
+ byte[] objSec = Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2));
+ byte[] ptSec = Db1Section(PointRow.TableKey, PointRow.ExpectedRowSize, [1, 1],
+ (0x04, pointBytes1, 1, 2),
+ (0x04, pointBytes2, 2, 3));
+ byte[] paSec = Db1Section(PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize, [1], (0x04, partAttrBytes, 1, 2));
+ byte[] partSec = Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2));
+
+ string nanoFile = File("custom_nano.db1", Gzip(Db1TablesPayload(unkeyedSec, objSec, ptSec, paSec, partSec)));
+
+ // 1. Plain object JSON export succeeds
+ var (jsonExit, jsonOut, jsonErr) = Run("export", nanoFile);
+ Assert.Equal(Cli.ExitOk, jsonExit);
+ Assert.Empty(jsonErr);
+ Assert.Contains("CUSTOM_NANO200", jsonOut);
+
+ // 2. IFC export succeeds
+ var (ifcExit, ifcOut, ifcErr) = Run("export", nanoFile, "--ifc");
+ Assert.Equal(Cli.ExitOk, ifcExit);
+ Assert.Empty(ifcErr);
+ Assert.Contains("CUSTOM_NANO200", ifcOut);
+
+ // 3. Scene JSON export succeeds
+ var (sceneExit, sceneOut, sceneErr) = Run("export", nanoFile, "--scene-json");
+ Assert.Equal(Cli.ExitOk, sceneExit);
+ Assert.Empty(sceneErr);
+ Assert.Contains("CUSTOM_NANO200", sceneOut);
+
+ // 4. HTML viewer export succeeds
+ string htmlPath = Path.Combine(_folder, "custom_nano.html");
+ var (htmlExit, _, htmlErr) = Run("export", nanoFile, htmlPath);
+ Assert.Equal(Cli.ExitOk, htmlExit);
+ Assert.Empty(htmlErr);
+ Assert.True(System.IO.File.Exists(htmlPath));
+ Assert.Contains("CUSTOM_NANO200", System.IO.File.ReadAllText(htmlPath));
+ }
+
private static void AssertInputError(params string[] args)
{
var (exit, stdout, stderr) = Run(args);
diff --git a/tests/TdbIO.Tests/GzipTests.cs b/tests/TdbIO.Tests/GzipTests.cs
index ff59923..e9e1b74 100644
--- a/tests/TdbIO.Tests/GzipTests.cs
+++ b/tests/TdbIO.Tests/GzipTests.cs
@@ -152,9 +152,9 @@ public void CorruptDeflateDataIsRejected()
public void LargeForgedIsizeWithCorruptDataDoesNotAllocateLargeBuffer()
{
byte[] file = Synthetic.Concat([0x1F, 0x8B, 0x08, 0x00, 0, 0, 0, 0, 0, 0], [0xFF, 0xFF, 0xFF], Synthetic.Le32(0u), Synthetic.Le32(64u * 1024 * 1024));
- long before = GC.GetTotalAllocatedBytes(precise: true);
+ long before = GC.GetAllocatedBytesForCurrentThread();
Rejects(file);
- long allocated = GC.GetTotalAllocatedBytes(precise: true) - before;
+ long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.True(allocated < 4 * 1024 * 1024, $"Allocated {allocated} bytes, expected < 4 MiB");
}
diff --git a/tests/TdbIO.Tests/IfcExportTests.cs b/tests/TdbIO.Tests/IfcExportTests.cs
new file mode 100644
index 0000000..ed54bbd
--- /dev/null
+++ b/tests/TdbIO.Tests/IfcExportTests.cs
@@ -0,0 +1,529 @@
+using System.Globalization;
+using System.Text;
+using TdbIO.Internal.Export;
+using Xunit;
+
+namespace TdbIO.Tests;
+
+public sealed class IfcExportTests
+{
+ [Fact]
+ public void StepWriter_EscapesUnicodeAndSpecialChars()
+ {
+ Assert.Equal(@"\X2\04220435043A043B0430\X0\", StepWriter.Escape("Текла"));
+ Assert.Equal("It''s a test", StepWriter.Escape("It's a test"));
+ Assert.Equal(@"C:\\Path\\File", StepWriter.Escape(@"C:\Path\File"));
+ }
+
+ [Fact]
+ public void StepWriter_FormatsRealsCorrectly()
+ {
+ Assert.Equal("0.", StepWriter.Real(0));
+ Assert.Equal("12.5", StepWriter.Real(12.5));
+ Assert.Equal("-100.", StepWriter.Real(-100));
+ }
+
+ [Fact]
+ public void StepWriter_RejectsNonFiniteReals()
+ {
+ Assert.Throws(() => StepWriter.Real(double.NaN));
+ Assert.Throws(() => StepWriter.Real(double.PositiveInfinity));
+ Assert.Throws(() => StepWriter.RealExact(double.NaN));
+ Assert.Throws(() => StepWriter.RealExact(double.NegativeInfinity));
+ }
+
+ [Fact]
+ public void TeklaModel_ToIfc_RejectsNonFiniteProfile()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "BEAM",
+ profile: "PLNaN*200",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: [beam], bolts: [], welds: [], objects: [beam]);
+
+ Assert.Throws(() => model.ToIfc());
+ }
+
+ [Fact]
+ public void TeklaModel_ToIfc_AcceptsFiniteCustomProfileWithSubstrings()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "BEAM",
+ profile: "CUSTOM_NANO200",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = new TeklaModel(doc, Guid.NewGuid(), assemblies: [], parts: [beam], bolts: [], welds: [], objects: [beam]);
+
+ string ifc = model.ToIfc();
+ Assert.Contains("CUSTOM_NANO200", ifc);
+ }
+
+ [Fact]
+ public void IfcGuid_ProducesStandard22CharGlobalId()
+ {
+ var guid = Guid.NewGuid();
+ string ifcGuid = IfcGuid.ToIfcGuid(guid);
+ Assert.Equal(22, ifcGuid.Length);
+
+ // BuildingSMART IFC character set
+ foreach (char c in ifcGuid)
+ {
+ Assert.True(
+ char.IsAsciiLetterOrDigit(c) || c == '_' || c == '$',
+ $"Character '{c}' is not valid in IFC GUID");
+ }
+ }
+
+ [Fact]
+ public void IfcGuid_DeterministicFromElementId()
+ {
+ string guid1 = IfcGuid.FromElementId(42, "Part");
+ string guid2 = IfcGuid.FromElementId(42, "Part");
+ string guidOther = IfcGuid.FromElementId(43, "Part");
+
+ Assert.Equal(22, guid1.Length);
+ Assert.Equal(guid1, guid2);
+ Assert.NotEqual(guid1, guidOther);
+ }
+
+ [Fact]
+ public void TeklaModel_ExportsValidIfc2x3()
+ {
+ var model = CreateSyntheticModel();
+ string ifc = model.ToIfc();
+
+ Assert.StartsWith("ISO-10303-21;", ifc);
+ Assert.Contains("FILE_SCHEMA(('IFC2X3'));", ifc);
+ Assert.Contains("IFCPROJECT", ifc);
+ Assert.Contains("IFCSITE", ifc);
+ Assert.Contains("IFCBUILDING", ifc);
+ Assert.Contains("IFCBUILDINGSTOREY", ifc);
+ Assert.Contains("IFCELEMENTASSEMBLY", ifc);
+ Assert.Contains("IFCBEAM", ifc);
+ Assert.Contains("IFCCOLUMN", ifc);
+ Assert.Contains("IFCPLATE", ifc);
+ Assert.Contains("IFCMECHANICALFASTENER", ifc);
+ Assert.Contains("IFCFASTENER", ifc);
+ Assert.Contains("IFCFACETEDBREP", ifc);
+ Assert.Contains("IFCPROPERTYSET", ifc);
+ Assert.Contains("IFCMATERIAL", ifc);
+ Assert.Contains("IFCRELAGGREGATES", ifc);
+ Assert.Contains("IFCRELCONTAINEDINSPATIALSTRUCTURE", ifc);
+ Assert.Contains("END-ISO-10303-21;", ifc);
+ }
+
+ [Fact]
+ public void TeklaModel_ExportsValidIfc4()
+ {
+ var model = CreateSyntheticModel();
+ string ifc = model.ToIfc(new TeklaIfcExportOptions { SchemaVersion = "IFC4" });
+
+ Assert.Contains("FILE_SCHEMA(('IFC4'));", ifc);
+ Assert.Contains("IFCBEAM", ifc);
+ Assert.Contains(".BEAM.", ifc);
+ Assert.Contains("END-ISO-10303-21;", ifc);
+ }
+
+ [Fact]
+ public void TeklaModel_WriteIfc_ToFileAndStream()
+ {
+ var model = CreateSyntheticModel();
+
+ using var ms = new MemoryStream();
+ model.WriteIfc(ms);
+ string fromStream = Encoding.UTF8.GetString(ms.ToArray());
+ Assert.StartsWith("ISO-10303-21;", fromStream);
+
+ string tempPath = Path.Combine(Path.GetTempPath(), $"test_{Guid.NewGuid():N}.ifc");
+ try
+ {
+ model.WriteIfc(tempPath);
+ Assert.True(File.Exists(tempPath));
+ string fromFile = File.ReadAllText(tempPath);
+ Assert.StartsWith("ISO-10303-21;", fromFile);
+ }
+ finally
+ {
+ if (File.Exists(tempPath)) File.Delete(tempPath);
+ }
+ }
+
+ private static TeklaModel CreateSyntheticModel()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 6000, 0, 0);
+ var p2 = new ModelPoint(3, 0, 0, 3000);
+
+ var beam = new ModelPart(
+ id: 101,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ name: "STEEL_BEAM",
+ profile: "HEA300",
+ material: "S355J2",
+ prefix: "B",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 3,
+ finish: "PAINT",
+ startPoint: p0,
+ endPoint: p1,
+ length: 6000,
+ coordinateSystem: null,
+ stringAttributes: new Dictionary { ["COMMENT"] = "Main roof girder" },
+ numericAttributes: new Dictionary { ["WEIGHT"] = 530.4 });
+
+ var column = new ModelPart(
+ id: 102,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ assemblyId: null,
+ name: "COLUMN",
+ profile: "HEB300",
+ material: "S355J2",
+ prefix: "C",
+ startNumber: 1,
+ positionNumber: 1,
+ @class: 4,
+ finish: "",
+ startPoint: p0,
+ endPoint: p2,
+ length: 3000,
+ coordinateSystem: null);
+
+ var plate = new ModelPart(
+ id: 103,
+ guid: Guid.NewGuid(),
+ type: 1,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ name: "END_PLATE",
+ profile: "PL10*200",
+ material: "S235JR",
+ prefix: "p",
+ startNumber: 1,
+ positionNumber: 5,
+ @class: 2,
+ finish: "",
+ startPoint: p0,
+ endPoint: new ModelPoint(4, 200, 0, 0),
+ length: 200,
+ coordinateSystem: null);
+
+ var assembly = new ModelAssembly(
+ id: 201,
+ guid: Guid.NewGuid(),
+ type: 2,
+ subtype: 0,
+ phase: 1,
+ parentId: null,
+ name: "ROOF_BEAM_ASM",
+ prefix: "A",
+ startNumber: 1,
+ positionNumber: 1,
+ assemblyType: 0,
+ @class: 3);
+
+ beam.Assembly = assembly;
+ plate.Assembly = assembly;
+ assembly.MainPart = beam;
+ assembly.Parts = [beam, plate];
+ assembly.Secondaries = [plate];
+
+ var bolt = new ModelBolt(
+ id: 301,
+ guid: Guid.NewGuid(),
+ type: 9,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ firstPoint: p0,
+ secondPoint: p1,
+ holes: [new ModelBoltHole(1, 101, beam, 0, 20, 0, 0, 0)],
+ positions: [new ModelPoint(5, 100, 50, 0)]);
+ bolt.Assembly = assembly;
+
+ var weld = new ModelWeld(
+ id: 401,
+ guid: Guid.NewGuid(),
+ type: 13,
+ subtype: 0,
+ phase: 1,
+ parentId: 201,
+ assemblyId: 201,
+ commonAttrId: 501);
+ weld.Assembly = assembly;
+
+ assembly.Bolts = [bolt];
+ assembly.Welds = [weld];
+
+ var document = Db1Document.Create(Synthetic.Db1Payload([]));
+
+ return new TeklaModel(
+ document,
+ Guid.NewGuid(),
+ assemblies: [assembly],
+ parts: [beam, column, plate],
+ bolts: [bolt],
+ welds: [weld],
+ objects: [beam, column, plate, assembly, bolt, weld]);
+ }
+
+ [Fact]
+ public void StepWriter_RealExact_PreservesSmallPrecision_AndValidStepSyntax()
+ {
+ double small = 1e-8;
+ string formatted = StepWriter.RealExact(small);
+ Assert.Equal("1.E-08", formatted);
+
+ // Valid ISO 10303-21 STEP real syntax: must contain a decimal point in the mantissa
+ int expIndex = formatted.IndexOfAny(['E', 'e']);
+ Assert.True(expIndex > 0);
+ Assert.Contains('.', formatted[..expIndex]);
+
+ // Round-trip parse back to double
+ double parsed = double.Parse(formatted, CultureInfo.InvariantCulture);
+ Assert.Equal(small, parsed);
+ }
+
+ [Fact]
+ public void Ifc_SchemaConformance_Ifc2x3()
+ {
+ var model = CreateSyntheticModel();
+ string ifc = model.ToIfc(new TeklaIfcExportOptions { SchemaVersion = "IFC2X3" });
+ var entities = ParseIfcEntities(ifc);
+
+ var buildings = entities.Values.Where(e => e.Type == "IFCBUILDING").ToList();
+ Assert.NotEmpty(buildings);
+ Assert.All(buildings, b => Assert.Equal(12, b.Args.Count));
+
+ var assemblies = entities.Values.Where(e => e.Type == "IFCELEMENTASSEMBLY").ToList();
+ Assert.NotEmpty(assemblies);
+ Assert.All(assemblies, a => Assert.Equal(10, a.Args.Count));
+
+ var materials = entities.Values.Where(e => e.Type == "IFCMATERIAL").ToList();
+ Assert.NotEmpty(materials);
+ Assert.All(materials, m => Assert.Single(m.Args));
+
+ var bolts = entities.Values.Where(e => e.Type == "IFCMECHANICALFASTENER").ToList();
+ Assert.NotEmpty(bolts);
+ Assert.All(bolts, b => Assert.Equal(10, b.Args.Count));
+
+ var welds = entities.Values.Where(e => e.Type == "IFCFASTENER").ToList();
+ Assert.NotEmpty(welds);
+ Assert.All(welds, w => Assert.Equal(8, w.Args.Count));
+ }
+
+ [Fact]
+ public void Ifc_SchemaConformance_Ifc4()
+ {
+ var model = CreateSyntheticModel();
+ string ifc = model.ToIfc(new TeklaIfcExportOptions { SchemaVersion = "IFC4" });
+ var entities = ParseIfcEntities(ifc);
+
+ var buildings = entities.Values.Where(e => e.Type == "IFCBUILDING").ToList();
+ Assert.NotEmpty(buildings);
+ Assert.All(buildings, b => Assert.Equal(12, b.Args.Count));
+
+ var assemblies = entities.Values.Where(e => e.Type == "IFCELEMENTASSEMBLY").ToList();
+ Assert.NotEmpty(assemblies);
+ Assert.All(assemblies, a => Assert.Equal(10, a.Args.Count));
+
+ var materials = entities.Values.Where(e => e.Type == "IFCMATERIAL").ToList();
+ Assert.NotEmpty(materials);
+ Assert.All(materials, m => Assert.Equal(3, m.Args.Count));
+
+ var bolts = entities.Values.Where(e => e.Type == "IFCMECHANICALFASTENER").ToList();
+ Assert.NotEmpty(bolts);
+ Assert.All(bolts, b =>
+ {
+ Assert.Equal(11, b.Args.Count);
+ Assert.Equal(".BOLT.", b.Args[10]);
+ });
+
+ var welds = entities.Values.Where(e => e.Type == "IFCFASTENER").ToList();
+ Assert.NotEmpty(welds);
+ Assert.All(welds, w =>
+ {
+ Assert.Equal(9, w.Args.Count);
+ Assert.Equal(".WELD.", w.Args[8]);
+ });
+
+ var plates = entities.Values.Where(e => e.Type == "IFCPLATE").ToList();
+ Assert.NotEmpty(plates);
+ Assert.All(plates, p =>
+ {
+ Assert.Equal(9, p.Args.Count);
+ Assert.NotEqual(".PLATE.", p.Args[8]);
+ Assert.Equal(".NOTDEFINED.", p.Args[8]);
+ });
+ }
+
+ [Fact]
+ public void Ifc_ExportGeometryFalse_OmitsProductDefinitionShape()
+ {
+ var model = CreateSyntheticModel();
+ string ifc = model.ToIfc(new TeklaIfcExportOptions { ExportGeometry = false });
+ var entities = ParseIfcEntities(ifc);
+
+ Assert.DoesNotContain(entities.Values, e => e.Type == "IFCPRODUCTDEFINITIONSHAPE");
+
+ var beams = entities.Values.Where(e => e.Type == "IFCBEAM").ToList();
+ Assert.NotEmpty(beams);
+ Assert.All(beams, b => Assert.Equal("$", b.Args[6]));
+
+ var columns = entities.Values.Where(e => e.Type == "IFCCOLUMN").ToList();
+ Assert.NotEmpty(columns);
+ Assert.All(columns, c => Assert.Equal("$", c.Args[6]));
+ }
+
+ [Fact]
+ public void Ifc_Units_ConvertMmToMetres_ScalesLengthAndDeclaresUnit()
+ {
+ var model = CreateSyntheticModel();
+
+ // 1. ConvertMmToMetres = true (default)
+ string ifcM = model.ToIfc(new TeklaIfcExportOptions { ConvertMmToMetres = true });
+ Assert.Contains("IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);", ifcM);
+ Assert.Contains("IFCLENGTHMEASURE(6.)", ifcM);
+ Assert.DoesNotContain("IFCLENGTHMEASURE(6000.)", ifcM);
+
+ // 2. ConvertMmToMetres = false
+ string ifcMm = model.ToIfc(new TeklaIfcExportOptions { ConvertMmToMetres = false });
+ Assert.Contains("IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);", ifcMm);
+ Assert.Contains("IFCLENGTHMEASURE(6000.)", ifcMm);
+ }
+
+ [Fact]
+ public void Ifc_GuidEmpty_Matches_IOScene_IfcGuid()
+ {
+ var p0 = new ModelPoint(1, 0, 0, 0);
+ var p1 = new ModelPoint(2, 1000, 0, 0);
+ var part = new ModelPart(1, Guid.Empty, 1, 0, 1, null, null, "PART", "PL10", "S235", "", 1, 1, 1, "", p0, p1, 1000, null);
+ var asm = new ModelAssembly(2, Guid.Empty, 2, 0, 1, null, "ASM", "A", 1, 1, 0, 1);
+ var bolt = new ModelBolt(3, Guid.Empty, 9, 0, 1, null, null, p0, p1, [], []);
+ var weld = new ModelWeld(4, Guid.Empty, 13, 0, 1, null, null, 1);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = new TeklaModel(doc, Guid.Empty, [asm], [part], [bolt], [weld], [part, asm, bolt, weld]);
+
+ string ifc = model.ToIfc();
+ var entities = ParseIfcEntities(ifc);
+
+ var ifcPart = Assert.Single(entities.Values, e => e.Type == "IFCPLATE" || e.Type == "IFCMEMBER");
+ Assert.Equal($"'{part.IfcGuid}'", ifcPart.Args[0]);
+
+ var ifcAsm = Assert.Single(entities.Values, e => e.Type == "IFCELEMENTASSEMBLY");
+ Assert.Equal($"'{asm.IfcGuid}'", ifcAsm.Args[0]);
+
+ var ifcBolt = Assert.Single(entities.Values, e => e.Type == "IFCMECHANICALFASTENER");
+ Assert.Equal($"'{bolt.IfcGuid}'", ifcBolt.Args[0]);
+
+ var ifcWeld = Assert.Single(entities.Values, e => e.Type == "IFCFASTENER");
+ Assert.Equal($"'{weld.IfcGuid}'", ifcWeld.Args[0]);
+ }
+
+ private static List ParseStepArgs(string argsText)
+ {
+ var list = new List();
+ int depth = 0;
+ bool inQuote = false;
+ int start = 0;
+ for (int i = 0; i < argsText.Length; i++)
+ {
+ char c = argsText[i];
+ if (c == '\'')
+ {
+ if (inQuote && i + 1 < argsText.Length && argsText[i + 1] == '\'')
+ {
+ i++; // skip escaped quote ''
+ }
+ else
+ {
+ inQuote = !inQuote;
+ }
+ }
+ else if (!inQuote)
+ {
+ if (c == '(') depth++;
+ else if (c == ')') depth--;
+ else if (c == ',' && depth == 0)
+ {
+ list.Add(argsText[start..i].Trim());
+ start = i + 1;
+ }
+ }
+ }
+ list.Add(argsText[start..].Trim());
+ return list;
+ }
+
+ private static Dictionary Args)> ParseIfcEntities(string ifc)
+ {
+ var dict = new Dictionary Args)>();
+ foreach (var line in ifc.Split(["\r\n", "\n"], StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (!line.StartsWith('#')) continue;
+ int eq = line.IndexOf('=');
+ if (eq < 0) continue;
+ int id = int.Parse(line[1..eq].Trim(), CultureInfo.InvariantCulture);
+ int openParen = line.IndexOf('(', eq);
+ int closeParen = line.LastIndexOf(')');
+ if (openParen < 0 || closeParen <= openParen) continue;
+ string type = line[(eq + 1)..openParen].Trim();
+ string argsText = line[(openParen + 1)..closeParen];
+ var args = ParseStepArgs(argsText);
+ dict[id] = (type, args);
+ }
+ return dict;
+ }
+}
diff --git a/tests/TdbIO.Tests/TdbIO.Tests.csproj b/tests/TdbIO.Tests/TdbIO.Tests.csproj
index b433e18..9e4a1bd 100644
--- a/tests/TdbIO.Tests/TdbIO.Tests.csproj
+++ b/tests/TdbIO.Tests/TdbIO.Tests.csproj
@@ -14,10 +14,12 @@
runtime; build; native; contentfiles; analyzers; buildtransitive
all
+
+