Document
Document is OCCTSwift’s XCAF/OCAF document type, wrapping OCCT’s TDocStd_Document and the XDE layer (XCAFDoc_DocumentTool, STEPCAFControl_Reader/Writer). It preserves the full assembly hierarchy, names, colors, PBR materials, GD&T annotations, layer assignments, and OCAF attribute trees from STEP files — and lets you build or edit those structures programmatically. Obtain one via Document.load(from:) (STEP import), Document.create() (blank), or Document.loadOCAF(from:) (native OCAF/binary format).
Document is very large — documented across many pages. This is the core (load/save, assembly structure, AssemblyNode, colors/materials, GD&T, core OCAF attributes); see the other Document — … pages for persistence/IO, XCAF tools, the OCAF attribute zoo, and the many low-level OCCT geometry/math wrappers exposed here.
Topics
- Loading · Assembly Structure · Convenience Methods · Writing · AssemblyNode · GD&T / Dimensions and Tolerances · TNaming: Topological Naming · Errors · Length Unit · Layers · Materials · TDF Label Properties · TDF Reference · TDF CopyLabel · Document Main Label · Document Transactions · Document Undo/Redo · Document Modified Labels · TDataStd Scalar Attributes · TDataStd Integer Array · TDataStd Real Array · TDataStd TreeNode · TDataStd NamedData · TDataXtd Shape Attribute · TDataXtd Position Attribute · TDataXtd Geometry Attribute · TDataXtd Triangulation Attribute · TDataXtd Point/Axis/Plane Attributes
Loading
Document.load(from:progress:)
Load a STEP file with full XDE support (assembly structure, names, colors, materials).
public static func load(from url: URL, progress: ImportProgress? = nil) throws -> Document
- Parameters:
url— URL to the STEP file;progress— optional progress/cancellation channel. - Returns:
Documentcontaining the assembly structure. - Throws:
DocumentError.loadFailedif loading fails;ImportError.cancelledif cancelled cooperatively. - OCCT:
STEPCAFControl_Readerwith color, name, layer, props, and material modes enabled;XCAFDoc_DocumentTool::ShapeTool/ColorTool/VisMaterialTool. - Example:
guard let url = Bundle.main.url(forResource: "assembly", withExtension: "step") else { return } let doc = try Document.load(from: url) for node in doc.rootNodes { print(node.name ?? "<unnamed>", node.children.count) }
Document.loadSTEP(from:progress:)
Alias for load(from:progress:) with explicit STEP naming.
public static func loadSTEP(from url: URL, progress: ImportProgress? = nil) throws -> Document
- OCCT:
STEPCAFControl_Reader(same asload(from:progress:)).
Document.create()
Create a new empty XCAF document.
public static func create() -> Document?
- Returns: A blank
Documentwith empty shape, color, and material tools, ornilon failure. - OCCT:
TDocStd_Application::NewDocument("MDTV-XCAF", …)+XCAFDoc_DocumentTool. - Example:
guard let doc = Document.create() else { return } let labelId = doc.addShape(Shape.box(width: 10, height: 10, depth: 10)!)
Assembly Structure
rootNodes
Get the root nodes (top-level/free shapes) in the document.
public var rootNodes: [AssemblyNode] { get }
- Returns: Array of top-level
AssemblyNodevalues. Assemblies have children; parts have ashape. - OCCT:
XCAFDoc_ShapeToolfree-shape enumeration viaOCCTDocumentGetRootCount/OCCTDocumentGetRootLabelId. - Example:
func printTree(_ node: AssemblyNode, indent: Int = 0) { print(String(repeating: " ", count: indent) + (node.name ?? "<unnamed>")) for child in node.children { printTree(child, indent: indent + 1) } } doc.rootNodes.forEach { printTree($0) }
node(at:)
Look up an AssemblyNode by its XCAF labelId.
public func node(at labelId: Int64) -> AssemblyNode?
labelId values are stable within a single Document instance; round-trip via AssemblyNode.labelId.
- Parameters:
labelId— the identifier previously obtained fromrootNodestraversal or ashapeLabelId(at:)call. - Returns: The matching node, or
nilif thelabelIddoes not refer to a label in this document. - OCCT:
TDF_Labellook-up in the document’s label registry (OCCTDocumentLabelIsNull). - Example:
let id = doc.rootNodes.first?.labelId ?? -1 if let node = doc.node(at: id) { print(node.name ?? "") }
Convenience Methods
allShapes()
Get all shapes from the document as a flat list (depth-first traversal).
public func allShapes() -> [Shape]
- Returns: Every
Shapefound by recursingrootNodes. Pure assemblies that have no direct geometry contribute no shapes. - Example:
let shapes = doc.allShapes() print("Total parts:", shapes.count)
shapesWithColors()
Get all shapes with their associated colors.
public func shapesWithColors() -> [(shape: Shape, color: Color?)]
- Returns: Array of
(shape, color?)pairs;colorisnilfor uncolored nodes. - Example:
for (shape, color) in doc.shapesWithColors() { if let c = color { print("color:", c.red, c.green, c.blue) } }
shapesWithMaterials()
Get all shapes with their associated PBR materials.
public func shapesWithMaterials() -> [(shape: Shape, material: Material?)]
- Returns: Array of
(shape, material?)pairs;materialisnilfor nodes without a PBR material.
Writing
write(to:)
Write the document to a STEP file, preserving assembly structure, colors, and materials.
public func write(to url: URL) throws
- Parameters:
url— output file URL. - Throws:
DocumentError.writeFailedif writing fails. - OCCT:
STEPCAFControl_Writerwith color, name, layer, props, and material modes. - Example:
let out = URL(fileURLWithPath: "/tmp/export.step") try doc.write(to: out)
writeSTEP(to:progress:)
Write the document to a STEP file with optional progress and cancellation.
public func writeSTEP(to url: URL, progress: ImportProgress?) throws
- Parameters:
url— output URL;progress— optional progress/cancellation channel. - Throws:
ImportError.cancelledif cancelled;ImportError.importFailedon other failure. - OCCT:
STEPCAFControl_Writer(viaOCCTDocumentWriteSTEPProgress).
AssemblyNode
AssemblyNode represents a node in an XDE assembly tree — a part or sub-assembly in a STEP file with name, transform, color, PBR material, child nodes, and shape geometry.
public final class AssemblyNode: @unchecked Sendable
AssemblyNode holds an unowned reference to its parent Document and is invalidated when the document is released.
labelId
The XCAF label identifier for this node.
public let labelId: Int64
Stable within a single Document instance; pass it back to Document.node(at:) to recover the node.
name
The name of this node (from CAD software).
public var name: String? { get }
- Returns: The label name string, or
nilif unnamed. - OCCT:
TDataStd_Nameattribute on the label (viaOCCTDocumentGetLabelName).
isAssembly
Whether this node is an assembly (has children).
public var isAssembly: Bool { get }
- OCCT:
XCAFDoc_ShapeTool::IsAssembly(viaOCCTDocumentIsAssembly).
isReference
Whether this node is a reference (instance of another shape).
public var isReference: Bool { get }
- OCCT:
XCAFDoc_ShapeTool::IsReference(viaOCCTDocumentIsReference).
transform
Transform matrix (position/rotation relative to parent), as a column-major simd_float4x4.
public var transform: simd_float4x4 { get }
- OCCT:
XCAFDoc_Locationattribute (viaOCCTDocumentGetLocation).
color
Color assigned to this node (if any). Checks surface color first, then generic.
public var color: Color? { get }
- Returns:
Color(RGBA in 0–1 range), ornilif no color is assigned. - OCCT:
XCAFDoc_ColorTool::GetColorwithXCAFDoc_ColorSurfthenXCAFDoc_ColorGen.
setColor(_:)
Set the surface color on this node.
public func setColor(_ color: Color)
- Parameters:
color— the color to assign. - OCCT:
XCAFDoc_ColorTool::SetColorwithXCAFDoc_ColorSurf(viaOCCTDocumentSetLabelColor). - Example:
node.setColor(Color(red: 1, green: 0, blue: 0, alpha: 1))
setColor(_:type:)
Set the color on this node with a specific color type.
public func setColor(_ color: Color, type: OCCTColorType)
- Parameters:
color— the color to assign;type—OCCTColorTypeGeneric(0),OCCTColorTypeSurface(1), orOCCTColorTypeCurve(2). - OCCT:
XCAFDoc_ColorTool::SetColor(viaOCCTDocumentSetLabelColor).
setMaterial(_:)
Set the PBR material on this node.
public func setMaterial(_ material: Material)
- Parameters:
material—Materialstruct with base color, metallic, roughness, emissive, and transparency. - OCCT:
XCAFDoc_VisMaterialTool::SetShapeMaterial(viaOCCTDocumentSetLabelMaterial).
material
PBR material assigned to this node (if any).
public var material: Material? { get }
- Returns:
Materialwith PBR properties, ornilif none is assigned. - OCCT:
XCAFDoc_VisMaterialTool::GetShapeMaterial(viaOCCTDocumentGetLabelMaterial).
children
Child nodes for assemblies.
public var children: [AssemblyNode] { get }
- Returns: Array of direct child
AssemblyNodevalues; empty for leaf parts. - OCCT:
TDF_Labelchild iteration (viaOCCTDocumentGetChildCount/OCCTDocumentGetChildLabelId).
shape
The shape geometry with transform applied.
public var shape: Shape? { get }
- Returns:
Shapewith the node’sTopLoc_Locationbaked in, ornilfor pure assemblies with no direct geometry. - OCCT:
XCAFDoc_ShapeTool::GetShape+TopLoc_Location(viaOCCTDocumentGetShapeWithLocation).
shapeWithoutTransform
The shape geometry without transform (original definition).
public var shapeWithoutTransform: Shape? { get }
- Returns: The un-located shape, or
nilif none is attached. - OCCT:
XCAFDoc_ShapeTool::GetShapewithout location (viaOCCTDocumentGetShape).
referredNode
For references, get the referred (prototype) node.
public var referredNode: AssemblyNode? { get }
- Returns: The prototype node this reference points to, or
nilifisReferenceisfalse. - OCCT:
XCAFDoc_ShapeTool::GetReferredShape(viaOCCTDocumentGetReferredLabelId).
GD&T / Dimensions and Tolerances
Supporting types for GD&T data read from STEP files.
DimensionInfo
Dimension information from STEP GD&T data.
public struct DimensionInfo: Sendable {
public let type: Int32 // XCAFDimTolObjects_DimensionType
public let value: Double // primary dimension value
public let lowerTolerance: Double
public let upperTolerance: Double
}
| Field | Meaning |
|---|---|
type | Dimension kind, as an XCAFDimTolObjects_DimensionType raw value. |
value | Primary (nominal) dimension value. |
lowerTolerance | Lower tolerance bound below value. |
upperTolerance | Upper tolerance bound above value. |
(Per-field anchors below, for cross-reference; the table above has the actual meaning of each.)
upperTolerance
GeomToleranceInfo
Geometric tolerance information from STEP GD&T data.
public struct GeomToleranceInfo: Sendable {
public let type: Int32 // XCAFDimTolObjects_GeomToleranceType
public let value: Double
}
DatumInfo
Datum reference information from STEP GD&T data.
public struct DatumInfo: Sendable {
public let name: String // e.g. "A", "B", "C"
}
dimensionCount
Number of dimensions defined in this document.
public var dimensionCount: Int { get }
- OCCT:
XCAFDoc_DimTolTool::GetDimensionLabels(viaOCCTDocumentGetDimensionCount).
geomToleranceCount
Number of geometric tolerances defined in this document.
public var geomToleranceCount: Int { get }
- OCCT:
XCAFDoc_DimTolTool(viaOCCTDocumentGetGeomToleranceCount).
datumCount
Number of datums defined in this document.
public var datumCount: Int { get }
- OCCT:
XCAFDoc_DimTolTool(viaOCCTDocumentGetDatumCount).
dimension(at:)
Get dimension info at the given index.
public func dimension(at index: Int) -> DimensionInfo?
- Parameters:
index— zero-based dimension index. - Returns:
DimensionInfo, ornilif index is out of range. - OCCT:
XCAFDimTolObjects_DimensionObject(viaOCCTDocumentGetDimensionInfo).
geomTolerance(at:)
Get geometric tolerance info at the given index.
public func geomTolerance(at index: Int) -> GeomToleranceInfo?
- Returns:
GeomToleranceInfo, ornilif index is out of range. - OCCT:
XCAFDimTolObjects_GeomToleranceObject(viaOCCTDocumentGetGeomToleranceInfo).
datum(at:)
Get datum info at the given index.
public func datum(at index: Int) -> DatumInfo?
- Returns:
DatumInfo, ornilif index is out of range. - OCCT:
XCAFDimTolObjects_DatumObject(viaOCCTDocumentGetDatumInfo).
dimensions
All dimensions in this document.
public var dimensions: [DimensionInfo] { get }
geomTolerances
All geometric tolerances in this document.
public var geomTolerances: [GeomToleranceInfo] { get }
datums
All datums in this document.
public var datums: [DatumInfo] { get }
- Example:
let doc = try Document.load(from: gdt_step_url) print("Dimensions:", doc.dimensions.count) print("Tolerances:", doc.geomTolerances.count) for datum in doc.datums { print("Datum:", datum.name) }
TNaming: Topological Naming
Types and methods for persistent topological naming (TNaming_NamedShape, TNaming_Builder).
NamingEvolution
Evolution type for topological naming history.
public enum NamingEvolution: Int32, Sendable {
case primitive = 0 // Created from scratch (no predecessor)
case generated = 1 // Generated from another shape
case modify = 2 // Modified (e.g. filleted edge)
case delete = 3 // Deleted
case selected = 4 // Named selection for persistent identification
}
Mirrors OCCT’s TNaming_Evolution (TNaming_PRIMITIVE, TNaming_GENERATED, TNaming_MODIFY, TNaming_DELETE, TNaming_SELECTED) by name, but not by raw value past .delete: the OCCT enum has a sixth case, TNaming_REPLACE, between DELETE (3) and SELECTED (5), that this Swift enum has no case for at all, so .selected is raw value 4 here versus 5 in OCCT. TNaming_REPLACE is not currently exposed through this API.
| Case | Meaning |
|---|---|
primitive | New entity created from scratch: the old shape of the pair is null, the new shape is the created entity. |
generated | Entity created from another entity: old shape is the generator, new shape is the created entity. |
modify | Split or merged entity: old shape is the entity before the operation, new shape is the entity after (e.g. a filleted edge). |
delete | Deletion: old shape is the deleted entity, new shape is null. |
selected | Named topological entity for persistent identification: new shape is the named entity; old shape is unused. |
NamingEvolution.selected
Named selection for persistent identification.
NamingHistoryEntry
A single entry in the naming history of a label.
public struct NamingHistoryEntry: Sendable {
public let evolution: NamingEvolution
public let hasOldShape: Bool
public let hasNewShape: Bool
public let isModification: Bool
}
| Field | Meaning |
|---|---|
evolution | The kind of naming event this entry records (see NamingEvolution). |
hasOldShape | true if this entry carries an old (input) shape. |
hasNewShape | true if this entry carries a new (result) shape. |
isModification | true if this entry represents a modification (evolution == .modify) rather than creation, deletion, or selection. |
(Per-field anchors below, for cross-reference; the table above has the actual meaning of each.)
isModification
createLabel(parent:)
Create a new TDF label for naming history tracking.
public func createLabel(parent: AssemblyNode? = nil) -> AssemblyNode?
- Parameters:
parent— parent node; passnilto create under the document main label. - Returns:
AssemblyNoderepresenting the new label, ornilon failure. - OCCT:
TDF_Label::NewChild(viaOCCTDocumentCreateLabel).
recordNaming(on:evolution:oldShape:newShape:)
Record a naming evolution on a label.
@discardableResult
public func recordNaming(on node: AssemblyNode, evolution: NamingEvolution,
oldShape: Shape? = nil, newShape: Shape? = nil) -> Bool
- Parameters:
node— the label to record on.evolution— type of topological evolution.oldShape— predecessor shape (nilfor.primitive).newShape— result shape (nilfor.delete).
- Returns:
trueif recording succeeded. - OCCT:
TNaming_Builder::Generated/Modify/Delete/Select(viaOCCTDocumentNamingRecord).
currentShape(on:)
Get the current (most recent) shape on a label.
public func currentShape(on node: AssemblyNode) -> Shape?
- OCCT:
TNaming_Tool::CurrentShape+TNaming_NamedShape(viaOCCTDocumentNamingGetCurrentShape).
storedShape(on:)
Get the stored shape on a label.
public func storedShape(on node: AssemblyNode) -> Shape?
- OCCT:
TNaming_Tool::GetShape(viaOCCTDocumentNamingGetShape).
namingEvolution(on:)
Get the naming evolution type on a label.
public func namingEvolution(on node: AssemblyNode) -> NamingEvolution?
- Returns: The
NamingEvolutioncase, ornilif no naming attribute exists. - OCCT:
TNaming_NamedShape::Evolution(viaOCCTDocumentNamingGetEvolution).
namingHistory(on:)
Get the full naming history on a label.
public func namingHistory(on node: AssemblyNode) -> [NamingHistoryEntry]
- Returns: Array of
NamingHistoryEntryvalues ordered from oldest to newest. - OCCT:
TNaming_IteratoroverTNaming_NamedShape(viaOCCTDocumentNamingHistoryCount/OCCTDocumentNamingGetHistoryEntry).
oldShape(on:at:)
Get the old (input) shape from a history entry.
public func oldShape(on node: AssemblyNode, at index: Int) -> Shape?
- Parameters:
index— zero-based history index. - OCCT:
TNaming_Iterator(viaOCCTDocumentNamingGetOldShape).
newShape(on:at:)
Get the new (result) shape from a history entry.
public func newShape(on node: AssemblyNode, at index: Int) -> Shape?
- OCCT:
TNaming_Iterator(viaOCCTDocumentNamingGetNewShape).
tracedForward(from:scope:)
Trace forward: find shapes generated/modified from the given shape.
public func tracedForward(from shape: Shape, scope: AssemblyNode) -> [Shape]
- Parameters:
shape— the source shape;scope— label providing document scope. - Returns: Shapes that were generated or modified from
shape(up to 64). - OCCT:
TNaming_Tool::GeneratedShape/ forward-tracing (viaOCCTDocumentNamingTraceForward).
tracedBackward(from:scope:)
Trace backward: find shapes that generated/preceded the given shape.
public func tracedBackward(from shape: Shape, scope: AssemblyNode) -> [Shape]
- Parameters:
shape— the shape to trace back from;scope— label scope. - Returns: Predecessor shapes (up to 64).
- OCCT:
TNaming_Toolbackward-tracing (viaOCCTDocumentNamingTraceBackward).
selectShape(_:context:on:)
Create a persistent named selection.
@discardableResult
public func selectShape(_ selection: Shape, context: Shape, on node: AssemblyNode) -> Bool
- Parameters:
selection— sub-shape to select;context— containing shape;node— label to store on. - OCCT:
TNaming_Builder::Select(viaOCCTDocumentNamingSelect).
resolveShape(on:)
Resolve a previously selected shape after modifications.
public func resolveShape(on node: AssemblyNode) -> Shape?
- Returns: The resolved shape, or
nilif resolution fails. - OCCT:
TNaming_Selector::Solve(viaOCCTDocumentNamingResolve).
Errors
DocumentError
Errors that can occur when working with XDE documents.
public enum DocumentError: Error, LocalizedError {
case loadFailed(url: URL)
case writeFailed(url: URL)
public var errorDescription: String? { get }
}
errorDescription produces a human-readable message such as "Failed to load STEP file: assembly.step".
| Case / property | Meaning |
|---|---|
loadFailed(url:) | A STEP file at url failed to load (Document.load(from:progress:) / loadSTEP(from:progress:)). |
writeFailed(url:) | A STEP file at url failed to write (Document.write(to:) / writeSTEP(to:progress:)). |
errorDescription | LocalizedError conformance: a human-readable message naming the file (by last path component) and the failed operation. |
(Per-case anchors below, for cross-reference; the table above has the actual meaning of each.)
errorDescription
Length Unit
LengthUnit
Length unit information from a document.
public struct LengthUnit: Sendable {
public let scale: Double // e.g. 1.0 for mm, 25.4 for inch, 1000.0 for m
public let name: String // e.g. "mm", "inch", "m"
}
lengthUnit
Get the length unit of this document.
public var lengthUnit: LengthUnit? { get }
Common scale values: 1.0 = mm, 10.0 = cm, 1000.0 = m, 25.4 = inch.
- Returns:
LengthUnitwith scale and name, ornilif not set. - OCCT:
STEPCAFControl_Readerunit info (viaOCCTDocumentGetLengthUnit). - Example:
if let unit = doc.lengthUnit { print("Unit:", unit.name, "scale:", unit.scale) }
Layers
layerCount
Number of layers in this document.
public var layerCount: Int { get }
- OCCT:
XCAFDoc_LayerTool(viaOCCTDocumentGetLayerCount).
layerName(at:)
Get the name of a layer by index.
public func layerName(at index: Int) -> String?
- Parameters:
index— zero-based layer index. - Returns: Layer name, or
nilif out of range. - OCCT:
XCAFDoc_LayerTool(viaOCCTDocumentGetLayerName).
layerNames
All layer names in this document.
public var layerNames: [String] { get }
- Example:
print("Layers:", doc.layerNames.joined(separator: ", "))
Materials
MaterialInfo
Material information from a document.
public struct MaterialInfo: Sendable {
public let name: String
public let description: String
public let density: Double
}
| Field | Meaning |
|---|---|
name | Material name. |
description | Material description. |
density | Material density, as recorded by XCAFDoc_Material::GetDensity(); units are whatever the source CAD/STEP data used and are not converted or interpreted by OCCTSwift. |
MaterialInfo.density
Material density, as recorded by XCAFDoc_Material::GetDensity() (units follow the source data, not converted here).
materialCount
Number of materials in this document.
public var materialCount: Int { get }
- OCCT:
XCAFDoc_MaterialTool::GetMaterialLabels(viaOCCTDocumentGetMaterialCount).
materialInfo(at:)
Get material info by index.
public func materialInfo(at index: Int) -> MaterialInfo?
- Parameters:
index— zero-based material index. - Returns:
MaterialInfo, ornilif out of range. - OCCT:
XCAFDoc_MaterialTool::GetMaterial(viaOCCTDocumentGetMaterialInfo).
materials
All materials in this document.
public var materials: [MaterialInfo] { get }
- Example:
for mat in doc.materials { print(mat.name, "density:", mat.density) }
TDF Label Properties
Extensions on AssemblyNode exposing low-level TDF_Label properties.
tag
The tag integer identifying this label among its siblings.
public var tag: Int32 { get }
- OCCT:
TDF_Label::Tag(viaOCCTDocumentLabelTag).
depth
The depth of this label in the tree (root = 0, main = 1, etc.).
public var depth: Int32 { get }
- OCCT:
TDF_Label::Depth(viaOCCTDocumentLabelDepth).
isNull
Whether this label is null.
public var isNull: Bool { get }
- OCCT:
TDF_Label::IsNull.
isRoot
Whether this label is the root label (0:).
public var isRoot: Bool { get }
- OCCT:
TDF_Label::IsRoot.
father
The parent (father) node of this label.
public var father: AssemblyNode? { get }
- Returns: The parent node, or
nilif this is the root. - OCCT:
TDF_Label::Father.
root
The root node of the data framework.
public var root: AssemblyNode? { get }
- OCCT:
TDF_Label::Root.
hasAttribute
Whether this label has any attributes.
public var hasAttribute: Bool { get }
- OCCT:
TDF_Label::HasAttribute.
attributeCount
The number of attributes on this label.
public var attributeCount: Int32 { get }
- OCCT:
TDF_Label::NbAttributes.
hasChild
Whether this label has any child labels.
public var hasChild: Bool { get }
- OCCT:
TDF_Label::HasChild.
childCount
The number of direct child labels.
public var childCount: Int32 { get }
- OCCT:
TDF_Label::NbChildren.
findChild(tag:create:)
Find or create a child label by tag.
public func findChild(tag: Int32, create: Bool = false) -> AssemblyNode?
- Parameters:
tag— tag to search for;create— iftrue, create the child if it doesn’t exist. - Returns: The child node, or
nilif not found andcreateisfalse. - OCCT:
TDF_Label::FindChild.
forgetAllAttributes(clearChildren:)
Remove all attributes from this label.
public func forgetAllAttributes(clearChildren: Bool = true)
- Parameters:
clearChildren— iftrue, also clears attributes on child labels. - OCCT:
TDF_Label::ForgetAllAttributes.
descendants(allLevels:)
Get all descendant labels.
public func descendants(allLevels: Bool = false) -> [AssemblyNode]
- Parameters:
allLevels— iftrue, recurse all descendants; iffalse, direct children only. - Returns: Array of descendant nodes (up to 1,024).
- OCCT:
TDF_LabelSequencerecursive traversal (viaOCCTDocumentGetDescendantLabels).
setName(_:)
Set the name (TDataStd_Name) on this label.
@discardableResult
public func setName(_ name: String) -> Bool
- Returns:
trueif the name was set successfully. - OCCT:
TDataStd_Name::Set(viaOCCTDocumentSetLabelName).
TDF Reference
setReference(to:)
Set a TDF_Reference from this label to another label.
@discardableResult
public func setReference(to target: AssemblyNode) -> Bool
- OCCT:
TDF_Reference::Set(viaOCCTDocumentLabelSetReference).
referencedLabel
Get the label referenced by a TDF_Reference attribute on this label.
public var referencedLabel: AssemblyNode? { get }
- Returns: The referenced node, or
nilif noTDF_Referenceattribute exists. - OCCT:
TDF_Reference::Get(viaOCCTDocumentLabelGetReference).
TDF CopyLabel
copyLabel(from:to:)
Copy a label and all its attributes to a destination label.
@discardableResult
public func copyLabel(from source: AssemblyNode, to destination: AssemblyNode) -> Bool
- Parameters:
source— label to copy from;destination— label to copy to. - Returns:
trueif the copy succeeded. - OCCT:
TDF_CopyLabel(viaOCCTDocumentCopyLabel).
Document Main Label
mainLabel
The main label (0:1) of the document — the root of the user data tree.
public var mainLabel: AssemblyNode? { get }
- OCCT:
TDocStd_Document::Main()(viaOCCTDocumentGetMainLabel). - Example:
if let main = doc.mainLabel { _ = main.setName("MyModel") }
Document Transactions
openTransaction()
Open a new transaction (command) on the document.
public func openTransaction()
All changes made after this call can be committed or aborted.
- OCCT:
TDocStd_Document::NewCommand(viaOCCTDocumentOpenTransaction).
commitTransaction()
Commit the current transaction.
@discardableResult
public func commitTransaction() -> Bool
- Returns:
trueif committed successfully. - OCCT:
TDocStd_Document::CommitCommand.
abortTransaction()
Abort the current transaction, undoing all changes since openTransaction().
public func abortTransaction()
- OCCT:
TDocStd_Document::AbortCommand.
hasOpenTransaction
Whether a transaction is currently open.
public var hasOpenTransaction: Bool { get }
- OCCT:
TDocStd_Document::HasOpenCommand. - Example:
doc.openTransaction() _ = doc.mainLabel?.setName("Rev1") _ = doc.commitTransaction()
Document Undo/Redo
setUndoLimit(_:)
Set the maximum number of undo steps.
public func setUndoLimit(_ limit: Int)
Must be called before any transactions. Pass 0 to disable undo.
- OCCT:
TDocStd_Document::SetUndoLimit.
undoLimit
The maximum number of undo steps.
public var undoLimit: Int { get }
- OCCT:
TDocStd_Document::GetUndoLimit.
undo()
Perform undo (reverses the last committed transaction).
@discardableResult
public func undo() -> Bool
- Returns:
trueif undo was performed. - OCCT:
TDocStd_Document::Undo.
redo()
Perform redo (reapplies the last undone transaction).
@discardableResult
public func redo() -> Bool
- Returns:
trueif redo was performed. - OCCT:
TDocStd_Document::Redo.
availableUndos
The number of available undo steps.
public var availableUndos: Int { get }
- OCCT:
TDocStd_Document::GetAvailableUndos.
availableRedos
The number of available redo steps.
public var availableRedos: Int { get }
- OCCT:
TDocStd_Document::GetAvailableRedos. - Example:
doc.setUndoLimit(10) doc.openTransaction() _ = doc.mainLabel?.setInteger(42) _ = doc.commitTransaction() print("Undos available:", doc.availableUndos) _ = doc.undo()
Document Modified Labels
setModified(_:)
Mark a label as modified.
public func setModified(_ node: AssemblyNode)
- OCCT:
TDocStd_Document::SetModified(viaOCCTDocumentSetModified).
clearModified()
Clear all modification marks.
public func clearModified()
- OCCT:
TDocStd_Document::PurgeModified(viaOCCTDocumentClearModified).
isModified(_:)
Check if a label is marked as modified.
public func isModified(_ node: AssemblyNode) -> Bool
- OCCT:
TDocStd_Document::IsModified(viaOCCTDocumentIsLabelModified).
TDataStd Scalar Attributes
Extensions on AssemblyNode for TDataStd scalar attribute types.
setInteger(_:)
Set an integer attribute (TDataStd_Integer) on this label.
@discardableResult
public func setInteger(_ value: Int32) -> Bool
- OCCT:
TDataStd_Integer::Set(viaOCCTDocumentSetIntegerAttr).
integer
Get the integer attribute from this label.
public var integer: Int32? { get }
- Returns: The stored value, or
nilif noTDataStd_Integerexists. - OCCT:
TDataStd_Integer::Get(viaOCCTDocumentGetIntegerAttr).
setReal(_:)
Set a real attribute (TDataStd_Real) on this label.
@discardableResult
public func setReal(_ value: Double) -> Bool
- OCCT:
TDataStd_Real::Set(viaOCCTDocumentSetRealAttr).
real
Get the real attribute from this label.
public var real: Double? { get }
- OCCT:
TDataStd_Real::Get(viaOCCTDocumentGetRealAttr).
setAsciiString(_:)
Set an ASCII string attribute (TDataStd_AsciiString) on this label.
@discardableResult
public func setAsciiString(_ value: String) -> Bool
- OCCT:
TDataStd_AsciiString::Set(viaOCCTDocumentSetAsciiStringAttr).
asciiString
Get the ASCII string attribute from this label.
public var asciiString: String? { get }
- OCCT:
TDataStd_AsciiString::Get(viaOCCTDocumentGetAsciiStringAttr).
setComment(_:)
Set a comment attribute (TDataStd_Comment) on this label.
@discardableResult
public func setComment(_ value: String) -> Bool
- OCCT:
TDataStd_Comment::Set(viaOCCTDocumentSetCommentAttr).
comment
Get the comment attribute from this label.
public var comment: String? { get }
- OCCT:
TDataStd_Comment::Get(viaOCCTDocumentGetCommentAttr). - Example:
guard let label = doc.createLabel() else { return } _ = label.setReal(3.14159) _ = label.setComment("pi approximation") print(label.real ?? 0, label.comment ?? "")
TDataStd Integer Array
initIntegerArray(lower:upper:)
Initialize an integer array attribute on this label.
@discardableResult
public func initIntegerArray(lower: Int32, upper: Int32) -> Bool
- Parameters:
lower,upper— inclusive bounds of the array. - OCCT:
TDataStd_IntegerArray::Init(viaOCCTDocumentInitIntegerArray).
setIntegerArrayValue(at:value:)
Set a value in the integer array attribute.
@discardableResult
public func setIntegerArrayValue(at index: Int32, value: Int32) -> Bool
- OCCT:
TDataStd_IntegerArray::SetValue(viaOCCTDocumentSetIntegerArrayValue).
integerArrayValue(at:)
Get a value from the integer array attribute.
public func integerArrayValue(at index: Int32) -> Int32?
- Returns: The value, or
nilif the attribute doesn’t exist orindexis out of bounds. - OCCT:
TDataStd_IntegerArray::Value(viaOCCTDocumentGetIntegerArrayValue).
integerArrayBounds
Get the bounds of the integer array attribute.
public var integerArrayBounds: (lower: Int32, upper: Int32)? { get }
- OCCT:
TDataStd_IntegerArray::Lower/Upper(viaOCCTDocumentGetIntegerArrayBounds). - Example:
guard let label = doc.createLabel() else { return } _ = label.initIntegerArray(lower: 0, upper: 2) _ = label.setIntegerArrayValue(at: 0, value: 10) _ = label.setIntegerArrayValue(at: 1, value: 20) _ = label.setIntegerArrayValue(at: 2, value: 30) print(label.integerArrayValue(at: 1) ?? -1) // 20
TDataStd Real Array
initRealArray(lower:upper:)
Initialize a real array attribute on this label.
@discardableResult
public func initRealArray(lower: Int32, upper: Int32) -> Bool
- OCCT:
TDataStd_RealArray::Init(viaOCCTDocumentInitRealArray).
setRealArrayValue(at:value:)
Set a value in the real array attribute.
@discardableResult
public func setRealArrayValue(at index: Int32, value: Double) -> Bool
- OCCT:
TDataStd_RealArray::SetValue(viaOCCTDocumentSetRealArrayValue).
realArrayValue(at:)
Get a value from the real array attribute.
public func realArrayValue(at index: Int32) -> Double?
- OCCT:
TDataStd_RealArray::Value(viaOCCTDocumentGetRealArrayValue).
realArrayBounds
Get the bounds of the real array attribute.
public var realArrayBounds: (lower: Int32, upper: Int32)? { get }
- OCCT:
TDataStd_RealArray::Lower/Upper(viaOCCTDocumentGetRealArrayBounds).
TDataStd TreeNode
setTreeNode()
Set a tree node attribute (TDataStd_TreeNode) on this label.
@discardableResult
public func setTreeNode() -> Bool
- OCCT:
TDataStd_TreeNode::Set(viaOCCTDocumentSetTreeNode).
appendTreeChild(_:)
Append a child to this tree node.
@discardableResult
public func appendTreeChild(_ child: AssemblyNode) -> Bool
- OCCT:
TDataStd_TreeNode::Append(viaOCCTDocumentAppendTreeChild).
treeNodeFather
The father (parent) of this tree node.
public var treeNodeFather: AssemblyNode? { get }
- OCCT:
TDataStd_TreeNode::Father(viaOCCTDocumentTreeNodeFather).
treeNodeFirstChild
The first child of this tree node.
public var treeNodeFirstChild: AssemblyNode? { get }
- OCCT:
TDataStd_TreeNode::First(viaOCCTDocumentTreeNodeFirst).
treeNodeNext
The next sibling of this tree node.
public var treeNodeNext: AssemblyNode? { get }
- OCCT:
TDataStd_TreeNode::Next(viaOCCTDocumentTreeNodeNext).
treeNodeHasFather
Whether this tree node has a father.
public var treeNodeHasFather: Bool { get }
- OCCT:
TDataStd_TreeNode::HasFather.
treeNodeDepth
The depth of this tree node (root = 0).
public var treeNodeDepth: Int32 { get }
- OCCT:
TDataStd_TreeNode::Depth.
treeNodeChildCount
The number of children of this tree node.
public var treeNodeChildCount: Int32 { get }
- OCCT:
TDataStd_TreeNode::NbChildren. - Example:
guard let parent = doc.createLabel(), let child1 = doc.createLabel(), let child2 = doc.createLabel() else { return } _ = parent.setTreeNode() _ = child1.setTreeNode() _ = child2.setTreeNode() _ = parent.appendTreeChild(child1) _ = parent.appendTreeChild(child2) print("Children:", parent.treeNodeChildCount) // 2
TDataStd NamedData
setNamedInteger(_:value:)
Set a named integer value on this label.
@discardableResult
public func setNamedInteger(_ name: String, value: Int32) -> Bool
- OCCT:
TDataStd_NamedData::SetInteger(viaOCCTDocumentNamedDataSetInteger).
namedInteger(_:)
Get a named integer value from this label.
public func namedInteger(_ name: String) -> Int32?
- OCCT:
TDataStd_NamedData::GetInteger(viaOCCTDocumentNamedDataGetInteger).
hasNamedInteger(_:)
Check if a named integer exists on this label.
public func hasNamedInteger(_ name: String) -> Bool
- OCCT:
TDataStd_NamedData::HasInteger.
setNamedReal(_:value:)
Set a named real value on this label.
@discardableResult
public func setNamedReal(_ name: String, value: Double) -> Bool
- OCCT:
TDataStd_NamedData::SetReal(viaOCCTDocumentNamedDataSetReal).
namedReal(_:)
Get a named real value from this label.
public func namedReal(_ name: String) -> Double?
- OCCT:
TDataStd_NamedData::GetReal.
hasNamedReal(_:)
Check if a named real exists on this label.
public func hasNamedReal(_ name: String) -> Bool
setNamedString(_:value:)
Set a named string value on this label.
@discardableResult
public func setNamedString(_ name: String, value: String) -> Bool
- OCCT:
TDataStd_NamedData::SetString(viaOCCTDocumentNamedDataSetString).
namedString(_:)
Get a named string value from this label.
public func namedString(_ name: String) -> String?
- OCCT:
TDataStd_NamedData::GetString.
hasNamedString(_:)
Check if a named string exists on this label.
public func hasNamedString(_ name: String) -> Bool
- Example:
guard let label = doc.createLabel() else { return } _ = label.setNamedReal("mass_kg", value: 2.75) _ = label.setNamedString("material", value: "Aluminium 6061") print(label.namedReal("mass_kg") ?? 0) // 2.75 print(label.namedString("material") ?? "") // Aluminium 6061
TDataXtd Shape Attribute
GeometryType
Geometry type for TDataXtd_Geometry attributes.
public enum GeometryType: Int32 {
case anyGeom = 0
case point = 1
case line = 2
case circle = 3
case ellipse = 4
case spline = 5
case plane = 6
case cylinder = 7
}
Mirrors TDataXtd_GeometryEnum (ANY_GEOM, POINT, LINE, CIRCLE, ELLIPSE, SPLINE, PLANE, CYLINDER). OCCT’s own header carries one blanket comment for the whole enum (“the types of geometric shapes available”) rather than a per-case one.
| Case | Meaning |
|---|---|
anyGeom | No specific geometry type constraint. |
point | A point geometry. |
line | A line geometry. |
circle | A circle geometry. |
ellipse | An ellipse geometry. |
spline | A B-spline curve geometry. |
plane | A plane geometry. |
cylinder | A cylinder geometry. |
GeometryType.cylinder
ExecutionStatus
Execution status for TFunction graph nodes.
public enum ExecutionStatus: Int32 {
case wrongDefinition = 0
case notExecuted = 1
case executing = 2
case succeeded = 3
case failed = 4
}
Mirrors TFunction_ExecutionStatus (TFunction_ES_WrongDefinition, TFunction_ES_NotExecuted, TFunction_ES_Executing, TFunction_ES_Succeeded, TFunction_ES_Failed) case for case.
| Case | Meaning |
|---|---|
wrongDefinition | The function’s arguments/definition are invalid; it cannot run. |
notExecuted | Not yet run in this execution pass. |
executing | Currently running (set while TFunction_Driver::Execute is in progress). |
succeeded | Completed without error. |
failed | Ran but reported an error. |
ExecutionStatus.failed
Ran but reported an error.
setShapeAttribute(_:)
Set a shape attribute on this label (stores the shape via TNaming).
@discardableResult
public func setShapeAttribute(_ shape: Shape) -> Bool
- OCCT:
TDataXtd_Shape::Set(viaOCCTDocumentSetShapeAttr).
shapeAttribute()
Get the shape stored in a TDataXtd_Shape attribute on this label.
public func shapeAttribute() -> Shape?
- OCCT:
TDataXtd_Shape::Get(viaOCCTDocumentGetShapeAttr).
hasShapeAttribute
Check if this label has a TDataXtd_Shape attribute.
public var hasShapeAttribute: Bool { get }
- OCCT:
TDataXtd_Shape::Find.
TDataXtd Position Attribute
setPositionAttribute(x:y:z:)
Set a position (3D point) attribute on this label.
@discardableResult
public func setPositionAttribute(x: Double, y: Double, z: Double) -> Bool
- OCCT:
TDataXtd_Position::Set(viaOCCTDocumentSetPositionAttr).
positionAttribute()
Get the position attribute from this label.
public func positionAttribute() -> (x: Double, y: Double, z: Double)?
- Returns: The stored position, or
nilif no attribute exists. - OCCT:
TDataXtd_Position::Get(viaOCCTDocumentGetPositionAttr).
hasPositionAttribute
Check if this label has a TDataXtd_Position attribute.
public var hasPositionAttribute: Bool { get }
TDataXtd Geometry Attribute
setGeometryType(_:)
Set a geometry type attribute on this label.
@discardableResult
public func setGeometryType(_ type: GeometryType) -> Bool
- OCCT:
TDataXtd_Geometry::Set(viaOCCTDocumentSetGeometryAttr).
geometryType()
Get the geometry type from this label.
public func geometryType() -> GeometryType?
- Returns: The
GeometryTypecase, ornilif no attribute exists. - OCCT:
TDataXtd_Geometry::GetType(viaOCCTDocumentGetGeometryType).
hasGeometryAttribute
Check if this label has a TDataXtd_Geometry attribute.
public var hasGeometryAttribute: Bool { get }
TDataXtd Triangulation Attribute
setTriangulationFromShape(_:deflection:)
Set a triangulation attribute on this label by meshing a shape.
@discardableResult
public func setTriangulationFromShape(_ shape: Shape, deflection: Double = 1.0) -> Bool
Meshes the shape and stores every face’s triangulation, merged into one Poly_Triangulation in the shape’s own coordinate system: per-face locations are applied to the nodes, and reversed faces have their winding and node normals flipped so the stored mesh is consistently outward. Node normals survive only if every contributing face carries them; per-face UV nodes are dropped, since they index parameter spaces that no longer mean anything once the faces are pooled. The stored deflection is the worst of the contributing faces’.
The stored coordinate frame changed alongside the every-face fix. This previously fetched each face’s
TopLoc_Locationand discarded it, storing one face’s nodes in that face’s local frame. It now stores them in the shape’s frame. For a shape with a non-identity location (an assembly component, anything fromShape.moved(dx:dy:dz:)orlocated(matrix:)) the numbers move independently of the node-count change: a box translated to (100, 200, 300) used to store a node at the origin and now stores it at (100, 200, 300). Re-read any OCAF document persisted before this change if you compare stored triangulations.
Node normals are transformed and reversed here, which Shape.mesh(...) does not do for its own Mesh.normals (only the winding swap matches), so the two disagree for a located or reversed face. BRepMesh_IncrementalMesh produces no node normals at all, so this only arises for a face carrying a triangulation from elsewhere, such as glTF import.
- Parameters:
shape, the shape to tessellate, faces at any depth included;deflection, linear deflection for meshing (default1.0). - Returns:
falseif the shape has no face, or if nothing in it meshed. - OCCT:
BRepMesh_IncrementalMesh+TDataXtd_Triangulation::Set(viaOCCTDocumentSetTriangulationFromShape). - Example:
let label = doc.createLabel()! label.setTriangulationFromShape(Shape.box(width: 10, height: 10, depth: 10)!, deflection: 1.0) print(label.triangulationNodeCount) // 24, all six faces, not 4 print(label.triangulationTriangleCount) // 12
triangulationNodeCount
Get the number of nodes in the triangulation attribute.
public var triangulationNodeCount: Int32 { get }
- OCCT:
Poly_Triangulation::NbNodes(viaOCCTDocumentTriangulationNbNodes).
triangulationTriangleCount
Get the number of triangles in the triangulation attribute.
public var triangulationTriangleCount: Int32 { get }
- OCCT:
Poly_Triangulation::NbTriangles(viaOCCTDocumentTriangulationNbTriangles).
triangulationNode(at:)
Read one node of the triangulation attribute, in the frame it was stored in.
public func triangulationNode(at index: Int32) -> SIMD3<Double>?
Nodes are numbered from 1, as Poly_Triangulation numbers them. Before this existed the attribute exposed only its counts and deflection, so nothing in the Swift API could see the coordinates it held.
- Parameters:
index, 1-based node index. - Returns: The node position, or
nilif the label has no triangulation attribute orindexis out of range. - OCCT:
Poly_Triangulation::Node(viaOCCTDocumentTriangulationNode). - Example:
let moved = Shape.box(width: 10, height: 10, depth: 10)!.moved(dx: 100, dy: 200, dz: 300)! label.setTriangulationFromShape(moved, deflection: 1.0) print(label.triangulationNode(at: 1)!) // absolute, not the box's local frame
triangulationNormal(at:)
Read one node normal of the triangulation attribute, in the frame it was stored in.
public func triangulationNormal(at index: Int32) -> SIMD3<Double>?
Node normals exist only when the meshed faces carried them. BRepMesh_IncrementalMesh produces none, so this returns nil for anything meshed from B-Rep and a value for a shape whose faces arrived with a triangulation from elsewhere, such as glTF import.
- Parameters:
index, 1-based node index. - Returns: The unit normal, or
nilif there is no attribute, the stored triangulation has no node normals, orindexis out of range. - OCCT:
Poly_Triangulation::Normalguarded byHasNormals(viaOCCTDocumentTriangulationNormal). - Example:
let imported = Shape.loadGLTF(from: url)! // glTF meshes carry vertex normals label.setTriangulationFromShape(imported, deflection: 1.0) print(label.triangulationNormal(at: 1)!)
triangulationDeflection
Get the deflection of the triangulation attribute.
public var triangulationDeflection: Double { get }
- OCCT:
Poly_Triangulation::Deflection(viaOCCTDocumentTriangulationDeflection).
TDataXtd Point/Axis/Plane Attributes
setPointAttribute(x:y:z:)
Set a point attribute on this label.
@discardableResult
public func setPointAttribute(x: Double, y: Double, z: Double) -> Bool
- OCCT:
TDataXtd_Point::Set(viaOCCTDocumentSetPointAttr).
setAxisAttribute(originX:originY:originZ:directionX:directionY:directionZ:)
Set an axis attribute on this label (origin + direction).
@discardableResult
public func setAxisAttribute(originX: Double, originY: Double, originZ: Double,
directionX: Double, directionY: Double, directionZ: Double) -> Bool
- OCCT:
TDataXtd_Axis::Set(viaOCCTDocumentSetAxisAttr).
setPlaneAttribute(originX:originY:originZ:normalX:normalY:normalZ:)
Set a plane attribute on this label (origin + normal).
@discardableResult
public func setPlaneAttribute(originX: Double, originY: Double, originZ: Double,
normalX: Double, normalY: Double, normalZ: Double) -> Bool
- OCCT:
TDataXtd_Plane::Set(viaOCCTDocumentSetPlaneAttr). - Example:
guard let label = doc.createLabel() else { return } _ = label.setPlaneAttribute(originX: 0, originY: 0, originZ: 5, normalX: 0, normalY: 0, normalZ: 1)