### Example: Print Hostname Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md An example demonstrating how to safely unwrap and print the hostname if available. ```swift if let host = HostInfo.hostName { print("Running on \(host)") } ``` -------------------------------- ### start() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Bounds.md Start (or resume) the timer. ```APIDOC ## start() ### Description Start (or resume) the timer. ### Method `public func start()` ### Example ```swift t.start() ``` ``` -------------------------------- ### Diameter Value Calculation Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/DrawingAnnotation.md Example showing how to instantiate a Diameter and access its 'value' property to get the full diameter. ```swift let d = DrawingDimension.Diameter(centre: .zero, radius: 8) print(d.value) // 16.0 ``` -------------------------------- ### Diameter Initialization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/DrawingAnnotation.md Example demonstrating how to create a Diameter instance with a specific tolerance and print its calculated value. ```swift let diam = DrawingDimension.Diameter( centre: SIMD2(30, 30), radius: 10, tolerance: .fitClass("H7") ) print(diam.value) // 20.0 ``` -------------------------------- ### Iterate Through Materials Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md An example demonstrating how to iterate through all materials in a document and print their names and densities. ```swift for mat in doc.materials { print(mat.name, "density:", mat.density) } ``` -------------------------------- ### Example Usage of Helix.build Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Demonstrates how to build a helix using Helix.build and access its resulting curve and achieved tolerance. It prints the error and the starting point of the curve. ```swift if let result = Helix.build( parameterRange: 0...(4 * .pi), pitch: 5, radius: 10 ) { let curve = result.curve print("error:", result.toleranceReached) print("start:", curve.point(at: 0)) } ``` -------------------------------- ### Example: Create a Torus in XY Plane Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape.md An example demonstrating how to create a torus using the majorRadius and minorRadius parameters. The result is checked for nil. ```swift if let ring = Shape.torus(majorRadius: 10, minorRadius: 2) { } ``` -------------------------------- ### Find All Roots Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Solvers.md Example demonstrating `findAllRoots` to find all roots of sin(x) in the interval [0, 4π]. ```swift // Find all roots of sin(x) in [0, 4π] let roots = MathSolver.findAllRoots(in: 0...4*.pi, samples: 40) { x in (sin(x), cos(x)) } ``` -------------------------------- ### Example: Calculate Midpoint of Face UV Bounds Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Face.md Demonstrates how to get the UV bounds of a face and calculate the midpoint within those bounds to find a corresponding 3D point. ```swift if let uv = face.uvBounds { let uMid = (uv.uMin + uv.uMax) / 2 let vMid = (uv.vMin + uv.vMax) / 2 let center = face.point(atU: uMid, v: vMid) } ``` -------------------------------- ### DrawingDimension.Ordinate.Feature Initialization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/DrawingAnnotation.md Example demonstrating how to create a new DrawingDimension.Ordinate.Feature instance with a given position. ```swift let f = DrawingDimension.Ordinate.Feature(position: SIMD2(35, 0)) ``` -------------------------------- ### Example: Set and Get Real and Comment Attributes Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md Demonstrates setting a real attribute and a comment attribute on a newly created label, then retrieving and printing them. Ensure a label is successfully created before proceeding. ```swift guard let label = doc.createLabel() else { return } _ = label.setReal(3.14159) _ = label.setComment("pi approximation") print(label.real ?? 0, label.comment ?? "") ``` -------------------------------- ### Point to Circle Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-BSpline-Extrema.md An example demonstrating how to find the nearest point to a circle and calculate its distance. ```swift let pts = ExtremaPointCurve.pointToCircle( point: SIMD3(0, 0, 5), center: .zero, normal: SIMD3(0, 0, 1), radius: 3 ) if let nearest = pts.min(by: { $0.squareDistance < $1.squareDistance }) { print(sqrt(nearest.squareDistance)) } ``` -------------------------------- ### Get Edge Start Vertex Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/TopologyGraph-Detail-History.md Retrieves the index of the start vertex for a given edge. Returns nil if the edge has no recorded start vertex. ```swift public func edgeStartVertex(_ edgeIndex: Int) -> Int? ``` ```swift if let v0 = graph.edgeStartVertex(0) { let pt = graph.vertexPoint(v0) } ``` -------------------------------- ### Example: Initialize and Build PipeShellBuilder Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Demonstrates initializing a PipeShellBuilder with a spine wire, adding a profile, and building the shape. ```swift if let pipe = PipeShellBuilder(spine: spineWire) { pipe.add(profile: profileWire) pipe.build() } ``` -------------------------------- ### Set Relation Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-OCAF-Attributes.md An example demonstrating how to set a relation string for a label. ```swift doc.setRelation(tag: 5, relation: "width = height / 2") ``` -------------------------------- ### Get BSpline Start Point Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve2D-Analytic-Types.md Retrieves the start point of the BSpline curve. Returns SIMD2.zero if the curve is not a BSpline. ```swift public var bsplineStartPoint: SIMD2 { get } ``` ```swift let s = curve.bsplineStartPoint ``` -------------------------------- ### Example: Create Polygon3D with Parameters Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-Recognition.md Demonstrates creating a Polygon3D with both points and curve parameters, and checking for their presence. ```swift let pts: [SIMD3] = [SIMD3(0,0,0), SIMD3(5,0,0), SIMD3(10,0,0)] let params: [Double] = [0, 0.5, 1] if let poly = Polygon3D.create(points: pts, parameters: params) { print(poly.hasParameters) // true } ``` -------------------------------- ### Get Bézier Curve Start Point Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve3D-Analytic-Types.md Retrieves the first pole (start point) of a Bézier curve. Returns .zero if the curve is not a Geom_BezierCurve. ```swift public var bezierStartPoint: SIMD3 { get } ``` ```swift if let curve = Curve3D.bezier(poles: [SIMD3(0,0,0), SIMD3(1,1,0), SIMD3(2,0,0)]) { let start = curve.bezierStartPoint // SIMD3(0,0,0) } ``` -------------------------------- ### Run Visual Workflow Demos Source: https://github.com/secondmouseau/occtswift/blob/main/docs/integration-tests.md Execute visual workflow demonstrations in OCCTSwiftViewport using the Swift Package Manager. ```bash # Visual workflow demos (in OCCTSwiftViewport) cd ../OCCTSwiftViewport swift run OCCTSwiftMetalDemo --test-all-demos ``` -------------------------------- ### Get Elapsed Time from OSD_Timer Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Bounds.md Retrieves the elapsed wall-clock time in seconds from the OSD_Timer. Ensure the timer has been started and stopped to get a meaningful value. ```swift public var elapsedTime: Double { get } ``` ```swift t.start() // ... work ... t.stop() print(t.elapsedTime) ``` -------------------------------- ### Brent Minimization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Solvers.md Example demonstrating how to use `minimizeBrent` to find the minimum of x² within the interval [-2, 2]. ```swift // Minimize x² in [-2, 2] if let res = MathSolver.minimizeBrent(ax: -2, bx: 0.1, cx: 2) { x in (x * x, 2 * x) } { print(res.location) // ≈ 0 } ``` -------------------------------- ### Get Curve2D Start Point Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve2D.md Retrieves the starting point of the Curve2D based on its parameter domain. This is a convenience for accessing the point at the lower bound of the domain. ```swift let seg = Curve2D.segment(from: SIMD2(1, 2), to: SIMD2(4, 5))! print(seg.startPoint) // SIMD2(1.0, 2.0) ``` -------------------------------- ### Example: Make Solid Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Builds the pipe shell and then attempts to convert it into a solid by capping the ends. ```swift pipe.build() pipe.makeSolid() ``` -------------------------------- ### TitleBlock Initialization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Drawing.md Demonstrates how to create a TitleBlock instance with common fields. ```swift let tb = TitleBlock( title: "Mounting Bracket", drawingNumber: "MB-042", creator: "J. Smith", dateOfIssue: "2026-06-21", revision: "B", scale: "1:2" ) ``` -------------------------------- ### Get Start Point of 2D Bézier Curve Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve2D-Analytic-Types.md Retrieves the start point (first pole) of a 2D Bézier curve. Returns .zero if the curve is not a Bézier. ```swift public var bezierStartPoint: SIMD2 { get } ``` ```swift let s = curve.bezierStartPoint ``` -------------------------------- ### Set Name on Main Label Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md An example demonstrating how to get the main label of a document and set its name. This is a common operation for identifying the root of the document. ```swift if let main = doc.mainLabel { _ = main.setName("MyModel") } ``` -------------------------------- ### Example: Getting Paper Size in Portrait Orientation Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Drawing.md Shows how to get the dimensions of an A4 paper size when set to portrait orientation. This is useful for precise layout planning. ```swift let sz = PaperSize.A4.size(in: .portrait) // (210, 297) ``` -------------------------------- ### Example Usage of StepHeader Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Demonstrates initializing a StepHeader, setting author and organization, and checking if it's done. ```swift if let header = StepHeader(filename: "part.stp") { header.author = "Alice" header.organization = "ACME" print(header.isDone) } ``` -------------------------------- ### Example: Wire Building Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Demonstrates creating a wire using WireBuilder by adding edges sequentially and checking for success or errors. ```swift let builder = WireBuilder() builder.addEdge(Shape.edgeFromLine(from: .zero, to: SIMD3(5, 0, 0))!) builder.addEdge(Shape.edgeFromLine(from: SIMD3(5, 0, 0), to: SIMD3(5, 5, 0))!) if builder.isDone, let wire = builder.wire { print("built wire with", wire.edges().count, "edges") } else { print("error:", builder.error) } ``` -------------------------------- ### Example Usage of Cylinder-Sphere Intersection Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Shows how to call the cylinder-sphere intersection function and print the number of resulting curves. This example assumes a basic setup and checks for a non-nil result. ```swift if let n = QuadricIntersection.cylinderSphere(cylinderRadius: 3, sphereCenter: .zero, sphereRadius: 5) { print("\(n) intersection curve(s)") } ``` -------------------------------- ### Gauss Integration Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Solvers.md Example demonstrating `integrate` to calculate the area under the curve of sin(x) from 0 to π. ```swift let area = MathSolver.integrate(from: 0, to: .pi) { x in sin(x) } // ≈ 2.0 ``` -------------------------------- ### bsplineStartPoint Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve2D-Analytic-Types.md Gets the starting point of the BSpline curve. This is the point at the first parameter value. ```APIDOC ## `bsplineStartPoint` ### Description Retrieves the start point of the BSpline curve, corresponding to the first parameter value. ### Returns - Start point as a `SIMD2`; `.zero` if not a BSpline. ### Example ```swift let s = curve.bsplineStartPoint ``` ``` -------------------------------- ### Example Usage of ZLayerSettings.topOSD Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Demonstrates how to use the predefined topOSD layer ID to place an object in a transparent overlay. ```swift let overlayLayerId = ZLayerSettings.topOSD ``` -------------------------------- ### Resolve ConstructionPlane Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Construction.md Demonstrates how to resolve a `ConstructionPlane` recipe against a `TopologyGraph`. This example shows how to handle both successful resolution to a `Placement` and failure with a `ConstructionResolutionError`. ```swift let plane = ConstructionPlane.absolute(origin: .zero, normal: SIMD3(0, 0, 1)) switch graph.resolve(plane) { case .success(let p): print(p.origin, p.zAxis) case .failure(let e): print(e) } ``` -------------------------------- ### Example: Querying Continuity Class Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Surface.md Shows how to get the continuity class of a b-spline surface. ```swift let bsp = Surface.bspline(poles: ..., ...)! print(bsp.continuityClass) // typically .c2 ``` -------------------------------- ### Volume Inertia Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-Measurement.md Example demonstrating how to access and print volume and gyration radii from a computed VolumeInertia object. ```swift if let vi = solid.volumeInertia { print("volume: \(vi.volume)") print("gyration radii: \(vi.gyrationRadii)") } ``` -------------------------------- ### Example of Calculating Linear Dimension Value Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/DrawingAnnotation.md Demonstrates how to access the 'value' property of a DrawingDimension.Linear to get the measured distance. ```swift let lin = DrawingDimension.Linear(from: SIMD2(0, 0), to: SIMD2(30, 40)) print(lin.value) // 50.0 ``` -------------------------------- ### Example Usage of ShapeFixer Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-Completions.md Demonstrates initializing a ShapeFixer, setting precision, performing repairs, and checking if a fix was applied. ```swift let fixer = ShapeFixer(shape: badShape) fixer.setPrecision(1e-4) fixer.perform() if let fixed = fixer.shape { print(fixer.status(2)) } // true = something was fixed ``` -------------------------------- ### Edge Endpoints Property Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Edge.md Get the start and end 3D points (vertices) of the edge. Returns (.zero, .zero) on failure. ```swift public var endpoints: (start: SIMD3, end: SIMD3) { get } ``` ```swift let ep = box.edge(at: 0)!.endpoints print(ep.start, ep.end) ``` -------------------------------- ### Camera.init() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Creates a camera with default settings and a zero-to-one depth range, making its projection matrix directly usable in Metal shaders. ```APIDOC ## Camera.init() ### Description Creates a camera with default settings and zero-to-one depth range. ### Method public init() ### Remarks The underlying `Graphic3d_Camera` is created with `SetZeroToOneDepth(true)` so its projection matrix is directly usable in Metal shaders without remapping. ### OCCT Equivalent `new Graphic3d_Camera()` + `SetZeroToOneDepth(Standard_True)` ### Example ```swift let cam = Camera() cam.eye = SIMD3(0, -100, 50) cam.center = SIMD3(0, 0, 0) cam.up = SIMD3(0, 0, 1) ``` ``` -------------------------------- ### Swift Example: Building a Threaded Rod with a Custom Profile Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/ThreadFeatures.md This example demonstrates how to create a custom thread profile and use it to build a smooth threaded rod. Ensure the custom profile satisfies `ThreadProfile.supportsSmoothRodBuild` for successful generation. ```swift guard let tooth = ThreadProfile(vertices: [ .init(axial: 0.000, depth: 1), .init(axial: 0.125, depth: 1), .init(axial: 0.375, depth: 0), .init(axial: 0.625, depth: 0), .init(axial: 0.875, depth: 1), .init(axial: 1.000, depth: 1), ]), let worm = Shape.threadedRod(customProfile: tooth, nominalDiameter: 12, pitch: 5, cutDepth: 1.8, length: 22) else { return } // worm.isValidSolid == true — smooth, analytic (handful of B-spline faces) ``` -------------------------------- ### Example: Add Profiles at Vertices Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Adds different profiles at the start and end vertices of the spine to define varying cross-sections. ```swift pipe.add(profile: smallCircle, atVertex: spineStart) pipe.add(profile: largeCircle, atVertex: spineEnd) ``` -------------------------------- ### Get Projection Type Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-XCAF-Notes.md Retrieves the current projection type of the view object. Example demonstrates setting and then printing the type. ```swift public var type: ProjectionType { get } ``` ```swift if let view = ViewObject() { view.setType(.parallel) print(view.type) // parallel } ``` -------------------------------- ### Example Usage of HatchBuilder Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-BSpline-Extrema.md Demonstrates how to initialize a HatchBuilder, add a vertical line, trim it against a segment, and then print the number of lines and intervals. Requires a valid initialization. ```swift if let h = HatchBuilder(tolerance: 1e-6) { h.addXLine(5.0) h.trim(x1: 0, y1: 0, x2: 10, y2: 10) print(h.nbLines, h.nbIntervals(lineIndex: 1)) } ``` -------------------------------- ### Global Minimization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Solvers.md Example demonstrating `globalMinimize` to find the minimum of x² + y² within the bounds [-5, 5] for both variables. ```swift if let res = MathSolver.globalMinimize( variables: 2, lower: [-5, -5], upper: [5, 5] ) { x in x[0]*x[0] + x[1]*x[1] } { print(res.minimum) // ≈ 0 } ``` -------------------------------- ### Get Font Path by Index and Aspect Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Retrieves the file system path for a font at a given index and style aspect. Returns nil if the font has no file for that aspect or the index is invalid. Example shows getting the path for a bold font. ```swift if let path = FontManager.fontPath(at: 0, aspect: .bold) { print(path) // e.g. "/System/Library/Fonts/Helvetica-Bold.ttc" } ``` -------------------------------- ### Example: Evaluate Center Point using UV Bounds Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Face.md Shows how to obtain the UV bounds of a face and then use them to evaluate the 3D point at the center of the UV domain. ```swift if let uv = face.uvBounds { let mid = face.point(atU: (uv.uMin + uv.uMax) / 2, v: (uv.vMin + uv.vMax) / 2) } ``` -------------------------------- ### Get Interval Bounds Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-HLR-Geom.md Retrieves the bounds and tolerances of an interval. Returns a Bounds struct containing start, end, tolStart, and tolEnd. ```swift public var bounds: Bounds { get } ``` -------------------------------- ### open() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Build (create/truncate) the file and open it for reading and writing. Returns true on success. ```APIDOC ## open() ### Description Build (create/truncate) the file and open it for reading and writing. ### Method `open() -> Bool` ### Returns - `true` on success. ### Request Example ```swift let f = OSDFile(path: "/tmp/out.txt") if f.open() { f.write("hello") } ``` ``` -------------------------------- ### Centermark Example Usage Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/DrawingAnnotation.md Demonstrates how to create and use a Centermark annotation with custom extent. This example shows the practical application of the Centermark initializer. ```swift let cm = DrawingAnnotation.centermark( DrawingAnnotation.Centermark(centre: SIMD2(50, 50), extent: 10) ) ``` -------------------------------- ### Get First Vertex of Edge Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Retrieves the starting vertex point of an edge shape. Returns zero vector if the shape is not an edge. ```swift public func edgeVertex1() -> SIMD3 ``` -------------------------------- ### VisMaterialPBR.init() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-XCAF-Notes.md Initializes a PBR material with default OCCT values. ```APIDOC ## VisMaterialPBR.init() ### Description Create PBR material with OCCT default values. ### Method `init()` ### Parameters None ### Response None ### Example ```swift public init() ``` ``` -------------------------------- ### Example: Build Pipe Shell Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Attempts to build the pipe shell and includes error handling for build failures. ```swift guard pipe.build() else { /* handle failure */ } ``` -------------------------------- ### Get Tangent at Abscissa Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/CurveAdaptors.md Calculates the unit tangent vector at a specified arc length from the start of the edge. Returns nil on failure. ```swift public func tangent(atAbscissa s: Double) -> SIMD3? ``` ```swift let ec = EdgeCurve(edge)! let t = ec.tangent(atAbscissa: 0) // tangent at the start ``` -------------------------------- ### TopologyGraph Snapshot and Restore Round-trip Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/TopologyGraph-Attributes.md Demonstrates the complete process of creating a graph, setting an attribute, snapshotting it, and then restoring it from the snapshot. ```swift // Round-trip guard let graph = TopologyGraph(shape: myShape) else { return } graph.setAttribute("quality", .string("high"), for: someRef) let snap = try graph.snapshot() let data = try GraphSnapshot.canonicalEncoder().encode(snap) // Later... let snap2 = try JSONDecoder().decode(GraphSnapshot.self, from: data) let graph2 = try TopologyGraph(snapshot: snap2) let quality = graph2.attribute("quality", for: someRef) // quality == .string("high") ``` -------------------------------- ### Example Usage of nextValueOfUV Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Surface-Analysis.md Illustrates using nextValueOfUV for projecting a sequence of points along a surface, starting with an initial UV guess. ```swift if let srf = Surface.sphere(radius: 5) { var prev = srf.valueOfUV(point: SIMD3(5, 0, 0)).uv for pt in samplePoints { let p = srf.nextValueOfUV(previousUV: prev, point: pt) prev = p.uv } } ``` -------------------------------- ### Get Surface Parameter Bounds Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Math-Solvers.md Retrieves the (u, v) parameter domain of a surface. Example shows accessing bounds and printing them. ```swift public var parameterBounds: (uMin: Double, uMax: Double, vMin: Double, vMax: Double) { get } ``` ```swift let s = Surface.cylinder(axis: .zero, direction: SIMD3(0,0,1), radius: 5)! let b = s.parameterBounds print(b.uMin, b.uMax) // 0.0, 2π ``` -------------------------------- ### Material.init Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Color-Material.md Creates a PBR material with specified properties. The metallic, roughness, and transparency values are clamped between 0 and 1. ```APIDOC ## Material.init(baseColor:metallic:roughness:emissive:transparency:) ### Description Creates a PBR material. ### Parameters - **baseColor** (Color) - albedo color (the primary reflective color). - **metallic** (Double) - 0.0 = dielectric (plastic/paint), 1.0 = metal (default `0.0`). Clamped to [0, 1]. - **roughness** (Double) - 0.0 = mirror-smooth, 1.0 = fully matte (default `0.5`). Clamped to [0, 1]. - **emissive** (Color?) - optional self-emission color for glowing materials. - **transparency** (Double) - 0.0 = opaque, 1.0 = fully transparent (default `0.0`). Clamped to [0, 1]. ### Example ```swift let mat = Material( baseColor: Color(red: 0.9, green: 0.7, blue: 0.1), metallic: 1.0, roughness: 0.2 ) ``` ``` -------------------------------- ### Get Font Aspect Name Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Retrieves the string representation for a given FontAspect. Example shows how to print the name of the bold aspect. ```swift print(FontManager.FontAspect.bold.name) // "Bold" ``` -------------------------------- ### IDFilter.init?(ignoreAll:) Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-OCAF-Attributes.md Initializes an attribute-ID filter to manage GUID inclusion/exclusion for OCAF copy/paste. The filter can start in either a deny-all or allow-all mode. ```APIDOC ## IDFilter.init?(ignoreAll:) ### Description Create an attribute-ID filter governing which GUID-keyed attributes are included or excluded during OCAF copy/paste operations. ### Parameters #### Path Parameters - **ignoreAll** (Bool) - Required - when `true` the filter starts in deny-all mode and only GUIDs explicitly `keep`-ed pass through; when `false` it starts in allow-all mode and only `ignore`-ed GUIDs are excluded. ### Response #### Success Response (200) - **IDFilter** (IDFilter) - A configured filter, or `nil` on allocation failure. ### Request Example ```swift if let f = IDFilter(ignoreAll: true) { f.keep("2a96b614-ec8b-11d0-bee7-080009dc3333") } ``` ``` -------------------------------- ### Example Usage Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md Demonstrates how to set and retrieve named real and string values on a label. ```APIDOC ## Example ```swift 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 ``` ``` -------------------------------- ### Get Root Assembly Nodes Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md Retrieves the top-level nodes in the document's assembly structure. Use this to start traversing the assembly hierarchy. ```swift public var rootNodes: [AssemblyNode] { get } ``` ```swift func printTree(_ node: AssemblyNode, indent: Int = 0) { print(String(repeating: " ", count: indent) + (node.name ?? "")) for child in node.children { printTree(child, indent: indent + 1) } } doc.rootNodes.forEach { printTree($0) } ``` -------------------------------- ### OSDFile.init() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Create a temporary file. The path for the temporary file is chosen by OCCT. ```APIDOC ## OSDFile.init() ### Description Create a temporary file (path chosen by OCCT). ### Method `init()` ### Request Example ```swift let tmp = OSDFile() ``` ``` -------------------------------- ### WireBuilder.init() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Initializes an empty wire builder. ```APIDOC ## `WireBuilder.init()` Create an empty wire builder. ### Method ```swift public init() ``` ### Description Initializes an empty wire builder. Unlike `Shape.wireFromEdges(_:)`, `WireBuilder` lets you add edges one-by-one and inspect the error state before retrieving the result. ### OCCT `BRepBuilderAPI_MakeWire()` (via `OCCTWireBuilderCreate`) ``` -------------------------------- ### Get Elapsed Time Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Retrieves the elapsed time in seconds since the timer was started and before it was stopped. This property provides the duration of the measured operation. ```swift public var elapsed: Double ``` -------------------------------- ### Get Curve Start Point Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve3D.md Retrieves the 3D point at the beginning of the curve's parametric domain. This is a convenience for accessing `point(at: domain.lowerBound)`. ```swift let seg = Curve3D.segment(from: SIMD3(1, 2, 3), to: SIMD3(4, 5, 6))! print(seg.startPoint) // SIMD3(1.0, 2.0, 3.0) ``` -------------------------------- ### Create Directory Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Creates a directory at the given file-system path. Returns true on success. Use this to prepare output locations. ```swift DirectoryUtils.create("/tmp/output") ``` -------------------------------- ### Get Point at Abscissa Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/CurveAdaptors.md Calculates the 3D point at a specified arc length from the start of the edge. Returns nil if conversion or evaluation fails. ```swift public func point(atAbscissa s: Double) -> SIMD3? ``` ```swift let ec = EdgeCurve(edge)! let half = ec.point(atAbscissa: ec.length / 2) ``` -------------------------------- ### Example: Get Z-Levels of Box Faces Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Face.md Demonstrates how to extract the Z-levels from all faces of a box shape. Useful for identifying top and bottom faces. ```swift let box = Shape.box(width: 10, height: 10, depth: 5)! let zLevels = box.faces().compactMap { $0.zLevel } // zLevels contains 0.0 (bottom) and 5.0 (top) ``` -------------------------------- ### Example: Create and Build a Filleted Box Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Builders-Fillet.md This example demonstrates initializing a FilletBuilder with a box shape, adding all its edges with a constant radius, and then building the filleted shape. ```swift guard let box = Shape.box(width: 20, height: 20, depth: 20), let builder = FilletBuilder(shape: box) else { return } for edge in box.edges() { _ = builder.addEdge(edge, radius: 2.0) } if let filleted = builder.build() { print("filleted shape valid:", filleted.isValid) } ``` -------------------------------- ### Get View Name Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-XCAF-Notes.md Retrieves the display name of the view. Returns nil if no name has been set. Example shows setting and then printing the name. ```swift public var name: String? { get } ``` ```swift if let view = ViewObject() { view.setName("Front") print(view.name ?? "") // "Front" } ``` -------------------------------- ### Sheet Standard Layout Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/SheetMetal.md Demonstrates how to create a standard layout for a shape, render it into a DXF writer, and save it to a file. Ensure the shape projection is successful. ```swift let sheet = Sheet(size: .a3, projection: .first) let box = Shape.box(width: 80, height: 50, depth: 30)! if let layout = sheet.standardLayout(of: box, scale: .oneToTwo, margin: 15) { let writer = DXFWriter() layout.render(into: writer) try writer.dxfString().write(toFile: "/tmp/bracket.dxf", atomically: true, encoding: .utf8) } ``` -------------------------------- ### Load, Inspect, and Export Assemblies Source: https://github.com/secondmouseau/occtswift/blob/main/docs/guides/cookbook/xcaf-assemblies.md Demonstrates loading a STEP assembly, inspecting its root nodes for names and colors, and exporting it back as a structured STEP file or a GLTF/GLB model. ```swift // load a STEP assembly — structure, names, colors preserved let doc = try Document.load(from: stepURL) for root in doc.rootNodes { print(root.name ?? "—", root.color as Any) } // write it back out, structure intact try Exporter.writeSTEPAssembly(doc, to: outURL) // product-structured STEP try doc.write(to: outURL) // same (STEP) doc.writeGLTF(to: glbURL, binary: true) // GLB for the web (returns Bool) ``` -------------------------------- ### Get Contour Points Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-Features.md Retrieves the starting vertices of all edges in the shape, suitable for simple polygon contours. For curved edges, use `edgePoints(at:maxPoints:)`. ```swift public func contourPoints(maxPoints: Int = 1000) -> [SIMD3] ``` -------------------------------- ### Get 3D Position of Edge's First Vertex Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Geometry-Constructors.md Retrieves the 3D coordinates of the starting vertex of an edge. Useful for geometric calculations and positioning. ```swift public static func firstVertex(_ edge: Shape) -> SIMD3 ``` ```swift let start = EdgeAnalysis.firstVertex(myEdge) ``` -------------------------------- ### Example: Printing All Layer Names Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md Demonstrates how to retrieve and print all layer names from a document, separated by commas. ```swift print("Layers:", doc.layerNames.joined(separator: ", ")) ``` -------------------------------- ### Example Usage: Creating and Measuring a 2D Circle Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Demonstrates how to create a 2D circle using the center and radius factory method and then calculate its length. Ensure the circle is successfully created before attempting to measure it. ```swift if let c = Curve2D.gceCircle(center: SIMD2(0, 0), radius: 5) { print(c.length()) } ``` -------------------------------- ### Get Native Parameter at Abscissa Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/CurveAdaptors.md Finds the native parameter corresponding to a given arc length from the start of the edge. Returns nil if the solver does not converge. ```swift public func parameter(atAbscissa s: Double) -> Double? ``` ```swift let ec = EdgeCurve(edge)! if let u = ec.parameter(atAbscissa: ec.length / 2) { print(u) } ``` -------------------------------- ### Example Usage of Extrude Initializer Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/FeatureReconstructor.md Demonstrates how to create an Extrude feature specification using a square profile, a plane at the origin with a Z-normal, and a specified length. ```swift let pts: [SIMD2] = [.init(-5, -5), .init(5, -5), .init(5, 5), .init(-5, 5)] let ext = FeatureSpec.Extrude( profilePoints2D: pts, planeOrigin: .zero, planeNormal: SIMD3(0, 0, 1), length: 20, id: "block") ``` -------------------------------- ### Example: Analyzing Shape Contents Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Demonstrates how to get extended shape contents for a box shape and print the counts of faces, edges, and B-spline surfaces. ```swift let box = Shape.box(width: 10, height: 10, depth: 10)! let c = box.contentsExtended() print("faces:", c.nbFaces, "edges:", c.nbEdges) print("B-spline surfaces:", c.nbBSplineSurf) ``` -------------------------------- ### PerfMeter.start() Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Starts the performance timer. ```APIDOC ## PerfMeter.start() ### Description Start the performance timer. ### Method POST ### Endpoint /OSD_Host/PerfMeter/start ``` -------------------------------- ### Get OSDFile Size Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Retrieves the size of the file in bytes. Returns nil if the file size cannot be determined, for example, if the file is not open or an error occurs. ```swift public var fileSize: Int? ``` -------------------------------- ### Example: Load Document and Access GD&T Data Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document.md Demonstrates loading a STEP file into a `Document` object and accessing counts and names of dimensions, tolerances, and datums. ```swift 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) } ``` -------------------------------- ### Example: Get Normal at UV Minima Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Face.md Demonstrates retrieving the surface normal at the minimum U and V parameters of a face's UV bounds and printing it. ```swift if let uv = face.uvBounds, let n = face.normal(atU: uv.uMin, v: uv.vMin) { print(n) } ``` -------------------------------- ### Get Unit Tangent at Arc Length Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/CurveAdaptors.md Retrieves the unit tangent vector at a specific arc length from the start of the wire. Returns nil if conversion or evaluation fails. ```swift public func tangent(atAbscissa s: Double) -> SIMD3? ``` ```swift let wc = WireCurve(wire)! let quarterTangent = wc.tangent(atAbscissa: wc.length / 4) ``` -------------------------------- ### Example Usage of SewingBuilder Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-BSpline-Extrema.md Demonstrates how to initialize SewingBuilder, add shapes, perform the sewing operation, and check the result. This is useful for creating a single shell from multiple input shells. ```swift if let sew = SewingBuilder(tolerance: 1e-5) { sew.add(shell1) sew.add(shell2) sew.perform() if let sewn = sew.result { // sewn shell } } ``` -------------------------------- ### BREP Serialization Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Transforms.md Demonstrates serializing a box shape to BREP format and then deserializing it back into a shape. ```swift if let box = Shape.box(width: 5, height: 5, depth: 5), let brep = box.toBREPString(), let restored = Shape.fromBREPString(brep) { // restored is equivalent to box } ``` -------------------------------- ### Example Usage of Shape.section2D Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Construction.md Demonstrates how to use the section2D method to get a 2D contour of a box shape. The resulting drawing's visible edges contain the contour. ```swift let box = Shape.box(width: 50, height: 50, depth: 50)! if let drawing = box.section2D(planeOrigin: SIMD3(0, 0, 25), planeNormal: SIMD3(0, 0, 1)) { // drawing.visibleEdges contains the 50×50 square contour at Z=25 let dxf = Exporter.exportDXF(drawing: drawing) } ``` -------------------------------- ### Initialize OSDFile with a Path Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Create an OSDFile instance for a given file system path. This is useful for working with existing files or creating new ones at a specified location. ```swift public init(path: String) ``` ```swift let f = OSDFile(path: "/tmp/output.txt") ``` -------------------------------- ### Get 3D Point at Arc Length on WireCurve Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/CurveAdaptors.md Calculates the 3D point at a specific arc length 's' from the start of the wire. Returns nil if conversion or evaluation fails. ```swift let wc = WireCurve(Wire.rectangle(width: 40, height: 20)!)! let mid = wc.point(atAbscissa: wc.length / 2) ``` -------------------------------- ### Example: Measure Operation Time Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Demonstrates the usage of PerfMeter to measure the duration of an operation. It involves creating a meter, starting it, performing work, stopping it, and then printing the elapsed time. ```swift let meter = PerfMeter(name: "myOp") meter.start() // ... work ... meter.stop() print(meter.elapsed) ``` -------------------------------- ### Sheet Render BOM Example Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Selection.md Demonstrates rendering a Bill of Materials onto a DXF sheet using default settings. ```swift var writer = DXFWriter() let sheet = Sheet(size: .a3, orientation: .landscape) sheet.render(into: &writer) sheet.renderBOM(bom, into: writer) ``` -------------------------------- ### FaceFixer.init(face:precision:) Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Initializes a face fixer with a given face and precision. ```APIDOC ## FaceFixer.init(face:precision:) ### Description Initializes a face fixer with the given face and precision. ### Method `public init?(face: Shape, precision: Double = 1e-6)` ### OCCT `ShapeFix_Face` (via `OCCTFaceFixerCreate`) ``` -------------------------------- ### Get Edges Adjacent to a Vertex Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Analysis-Builders.md Retrieves the 1-based indices of edges that are adjacent to a specific vertex within the shape. The indices are up to 64. An example shows how to interpret the result of edgeFaceAdjacency. ```swift public func adjacentEdges(forVertex vertex: Shape) -> [Int] ``` ```swift let faceCounts = box.edgeFaceAdjacency() // faceCounts[i] == 2 for interior edges shared by two faces ``` -------------------------------- ### Example: Creating and Using PolygonOnTriangulation with Parameters Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Shape-Recognition.md Demonstrates creating a PolygonOnTriangulation with node indices and parameters, then accessing its node count. ```swift if let poly = PolygonOnTriangulation.create(nodeIndices: [0, 5, 12], parameters: [0, 0.5, 1]) { print(poly.nodeCount) // 3 } ``` -------------------------------- ### Get All Font Names Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Retrieves an array of all available system font family names. Skips fonts whose names cannot be decoded. Example shows checking for the presence of 'Helvetica'. ```swift FontManager.initDatabase() let names = FontManager.allFontNames let hasHelvetica = names.contains("Helvetica") ``` -------------------------------- ### Get Curve Parameter at Arc Length Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Curve2D.md Calculates the curve parameter corresponding to a specific arc-length distance from a starting parameter. Useful for trimming curves or positioning features along their length. ```swift public func parameterAtLength(_ arcLength: Double, from fromParameter: Double? = nil) -> Double? ``` ```swift let seg = Curve2D.segment(from: .zero, to: SIMD2(10, 0))! if let u = seg.parameterAtLength(5) { let pt = seg.point(at: u) // ≈ SIMD2(5, 0) } ``` -------------------------------- ### GraphSnapshot.init(brep:attributes:formatVersion:) Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/TopologyGraph-Attributes.md Creates a GraphSnapshot directly from its components. ```APIDOC ## GraphSnapshot.init(brep:attributes:formatVersion:) ### Description Create a snapshot directly. ### Method `init(brep: String, attributes: NodeAttributeStore, formatVersion: Int = GraphSnapshot.currentFormatVersion)` ### Parameters #### Path Parameters - **brep** (String) - BREP string of the source shape. - **attributes** (NodeAttributeStore) - the attribute store. - **formatVersion** (Int) - defaults to `currentFormatVersion`. ``` -------------------------------- ### Example: Free Bounds Analysis Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Document-Mesh-Fixing.md Demonstrates how to perform free bounds analysis on a shape and print the counts of open and closed free bounds. ```swift let shell = Shape.box(width: 10, height: 10, depth: 10)! // closed — 0 free bounds if let fp = FreeBoundsProperties(shape: shell) { _ = fp.perform() print("closed:", fp.closedCount, "open:", fp.openCount) } ``` -------------------------------- ### Get Font Name by Index Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Retrieves the font family name at a specific 0-based index. Returns nil if the index is out of range. Example shows iterating and printing all font names. ```swift FontManager.initDatabase() for i in 0.. Interval.Bounds ``` -------------------------------- ### Example: Projecting a World Point Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Demonstrates how to use the `project` method to convert a world-space point to normalized device coordinates. ```swift let ndc = cam.project(SIMD3(10, 0, 0)) ``` -------------------------------- ### Check if Font Has Aspect Source: https://github.com/secondmouseau/occtswift/blob/main/docs/reference/Display.md Tests if a font at a given index supports a specific style aspect. Returns true if a file exists for that aspect. Example shows checking for bold italic and then getting its path. ```swift if FontManager.fontHasAspect(at: 0, aspect: .boldItalic) { let path = FontManager.fontPath(at: 0, aspect: .boldItalic) } ```