=============== LIBRARY RULES =============== From library maintainers: - OCCTSwiftScripts is a CadQuery/OpenSCAD-style harness for OCCTSwift, not a CAD kernel. Geometry comes from the OCCTSwift API (`import OCCTSwift`); a script accumulates bodies in a `ScriptContext`, calls `emit()`, and OCCTSwiftViewport live-reloads. - Script entry point is `Sources/Script/main.swift`; build then `swift run Script`. Always: `let ctx = ScriptContext()`, build geometry, `try ctx.add(shape, id:, color:)` per body, `try ctx.emit()` LAST. Headless: `occtkit run .swift`. - Fallible OCCTSwift factories return optionals — unwrap with `guard let`/`if let`, or `!` only in throwaway scripts. `ScriptContext.add()` accepts `Shape`, `Wire`, or `Edge`; `addCompound([Shape])` and `addGraph(_:)` also exist. - Colors are `ScriptContext.Colors` constants (`.steel`, `.brass`, `.copper`, `.red`, ...), passed as the `color:` argument; they are `[Float]` RGBA under the hood. - Output: one `body-N.brep` per add + an optional combined `output.step`, to iCloud `.../CloudDocs/OCCTSwiftScripts/output/` if present, else `~/.occtswift-scripts/output/`. `manifest.json` is written LAST so a partial failure keeps the prior frame. - `occtkit` is a busybox-style multi-call binary: run a verb as `occtkit ...`, `swift run occtkit ...`, or an installed symlink (`make install`). 29 verbs span script-host, graph, drawings, reconstruct, construction, I/O, mesh, render, XCAF. - Every occtkit verb takes flag-form OR JSON-form input (JSON on stdin or a file-path argv), plus a `--serve` mode: a JSONL loop reading `{"args":[...]}` and emitting one `{ok,exit,stdout,stderr,error?}` envelope per request. OCCTMCP drives it this way. - Stable topology IDs use `face[N]`/`edge[N]`/`vertex[N]` (index in `Shape.faces()`/`.edges()`/`.vertices()` order), deterministic per BREP. IDs from `query-topology` feed `render-preview --highlight`, `feature-recognize` topologyRefs, and `graph-select`. - This repo OWNS `render-preview`: render a headless PNG with `render-preview ... --output [--camera iso|front|top|...] [--display-mode shaded|wireframe|...] [--highlight face[N]]`, wrapping OCCTSwiftViewport's OffscreenRenderer. - Library products `ScriptHarness` (the `ScriptContext` output pipeline) and `DrawingComposer` (`Composer.render(spec:shape:)`, the multi-view ISO drawing engine behind `drawing-export`) import directly into downstream Swift packages without the CLI. ### Install occtkit CLI Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Installs the occtkit CLI to the system. Builds the binary if necessary and creates symlinks for each verb. Can be configured with a custom prefix. ```bash make install ``` ```bash make install PREFIX=$HOME/.local ``` ```bash make uninstall ``` -------------------------------- ### Run a Recipe Example Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Command to execute a specific recipe example from the command line using the occtkit tool. The output format and destination can be specified. ```bash swift run occtkit run recipes/01-mounting-bracket/main.swift --format brep --output /tmp/out ``` -------------------------------- ### Add Geometry Usage Examples Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/ScriptHarness.md Shows practical examples of using the add functions with specific IDs, colors, and names for solids, wires, and compounds. ```swift try ctx.add(shape, id: "part", color: C.steel, name: "Bracket") // solid try ctx.add(wire, id: "sketch", color: C.yellow) // wireframe try ctx.addCompound([a, b], id: "assembly", color: C.gray) // compound ``` -------------------------------- ### Install occtkit CLI Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Installs the occtkit CLI to /usr/local/bin or a custom prefix. This creates symlinks for all available verbs. ```bash # install to /usr/local/bin (creates symlinks: graph-validate, drawing-export, ...) make install # or: make install PREFIX=$HOME/.local ``` -------------------------------- ### Create ManifestMetadata Instance Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Example of creating an instance of ManifestMetadata with sample data and initializing a ScriptContext with it. ```swift let meta = ManifestMetadata( name: "Mounting Bracket Assembly", revision: "2.1", dateCreated: Date(timeIntervalSince1970: 0), source: "https://github.com/myorg/cad-designs", tags: ["fastener", "aluminum", "cast"], notes: "Mounting bracket for the secondary encoder. Cast aluminum with drilled holes." ) let ctx = ScriptContext(metadata: meta) ``` -------------------------------- ### Install occtkit CLI Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/getting-started.md Install the occtkit command-line tool to your system's PATH. You can specify a custom installation prefix if needed. ```bash make install # installs to /usr/local/bin make install PREFIX=$HOME/.local ``` -------------------------------- ### Invoke occtkit CLI Verbs Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Demonstrates the three equivalent ways to invoke an occtkit verb after installation: using the installed symlink, the umbrella binary, or directly from a source checkout. ```bash # 1. Installed symlink — shortest, busybox-style graph-validate body.brep ``` ```bash # 2. Umbrella binary — useful when the symlinks are not on $PATH occtkit graph-validate body.brep ``` ```bash # 3. From a checkout — no install needed swift run occtkit graph-validate body.brep ``` -------------------------------- ### Example Usage of emit Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Demonstrates adding shapes and then calling emit to generate output files and trigger the viewport. Ensure emit is called last. ```swift import OCCTSwift import ScriptHarness let ctx = ScriptContext() let C = ScriptContext.Colors.self let profile = Wire.rectangle(width: 20, height: 10)! let solid = Shape.extrude(profile: profile, direction: SIMD3(0, 0, 1), length: 5)! let final = solid.filleted(radius: 1.0) ?? solid try ctx.add(profile, id: "sketch", color: C.yellow) try ctx.add(final, id: "part", color: C.steel) try ctx.emit(description: "Filleted rectangular extrusion") ``` -------------------------------- ### Scaffold a New Recipe Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Command to generate a new recipe scaffold using the make utility. This is useful for starting new parametric examples. ```bash make recipe NAME=my-widget ``` -------------------------------- ### Test All Recipes Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Command to perform a smoke test on all available recipe examples using the make utility. This ensures basic functionality of all recipes. ```bash make recipes-test ``` -------------------------------- ### Minimal ScriptContext Lifecycle Example Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/ScriptHarness.md Demonstrates the basic workflow: create a context, add geometry bodies with IDs and colors, and emit the final result with a description. This script can be run using `swift run Script` or `occtkit run .swift`. ```swift import OCCTSwift import ScriptHarness let ctx = ScriptContext() let C = ScriptContext.Colors.self // Sketch a profile let profile = Wire.rectangle(width: 20, height: 10)! try ctx.add(profile, id: "sketch", color: C.yellow) // Extrude → fillet let solid = Shape.extrude(profile: profile, direction: SIMD3(0, 0, 1), length: 5)! let filleted = solid.filleted(radius: 1.0)! try ctx.add(filleted, id: "body", color: C.blue) // Boolean cut let hole = Shape.cylinder(radius: 3, height: 10)!.translated(by: SIMD3(5, 0, -1))! let result = filleted.subtracting(hole)! try ctx.add(result, id: "final", color: C.steel) try ctx.emit(description: "Filleted plate with hole") ``` -------------------------------- ### Worked Example: Drilled Mounting Bracket Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/script-iteration.md A comprehensive script to build a mounting bracket. It creates a blank, drills holes, cuts a slot, applies a fillet, and registers each stage for visualization. ```swift import OCCTSwift import ScriptHarness let ctx = ScriptContext(metadata: ManifestMetadata( name: "Drilled mounting bracket", revision: "1", dateModified: Date(), source: "Internal design", tags: ["bracket", "mounting", "hardware"], notes: "80 × 40 × 8 mm blank; M5 holes at 10 mm from each corner; 20 × 6 mm centre slot" )) let C = ScriptContext.Colors.self // ── 1. Blank ────────────────────────────────────────────────────────────────── guard let blank = Shape.box(width: 80, height: 40, depth: 8) else { fatalError("box") } // ── 2. Drill four M5 mounting holes (⌀ 5.3 mm through) ────────────────────── let holePositions: [SIMD3] = [ SIMD3( 10, 10, -1), SIMD3( 70, 10, -1), SIMD3( 10, 30, -1), SIMD3( 70, 30, -1), ] let drillDir = SIMD3(0, 0, 1) var drilled = blank for pos in holePositions { guard let next = drilled.drilled(at: pos, direction: drillDir, radius: 2.65, depth: 10) else { fatalError("drill failed at \(pos)") } drilled = next } // ── 3. Centre slot (20 × 6 mm, milled through) ─────────────────────────────── let slotProfile = Wire.rectangle(width: 20, height: 6)! .translated(by: SIMD3(30, 17, 0))! // centre at (40, 20) guard let slotTool = Shape.extrude(profile: slotProfile, direction: SIMD3(0, 0, 1), length: 10)? .translated(by: SIMD3(0, 0, -1)) else { fatalError("slot tool") } guard let bracket = drilled.subtracting(slotTool) else { fatalError("slot cut") } // ── 4. Light fillet on top face edges ──────────────────────────────────────── let finished = bracket.filleted(radius: 1.5) ?? bracket // ── 5. Emit ────────────────────────────────────────────────────────────────── try ctx.add(finished, id: "bracket", color: C.steel, name: "Bracket") // Show the footprint wire for cross-section inspection let footprint = Wire.rectangle(width: 80, height: 40)! try ctx.add(footprint, id: "footprint", color: C.yellow, name: "Footprint") // Show one drill-axis edge for orientation reference let refAxis = Edge.line(from: SIMD3(10, 10, -1), to: SIMD3(10, 10, 9))! try ctx.add(refAxis, id: "drill-axis", color: C.red, name: "Drill axis (ref)") try ctx.emit(description: "Drilled mounting bracket") ``` -------------------------------- ### Add Topology Graph Usage Example Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/ScriptHarness.md Illustrates how to add a part, export its topology graph with SQLite support, and emit a description. Note that occtkit run can automate addGraphsForAllShapes. ```swift try ctx.add(part, id: "part") try ctx.addGraphsForAllShapes(sqlite: true) // → graph-0.json + graph-0.sqlite try ctx.emit(description: "part + topology graph") ``` -------------------------------- ### Flag-form Input Examples Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Examples of using the flag-form input for occtkit verbs, which uses positional arguments and flags similar to traditional Unix tools. ```bash # Validate a B-Rep graph and emit warnings to stdout graph-validate body.brep ``` ```bash # Export a single HLR view to DXF dxf-export bracket.brep bracket.dxf --view 0,0,1 ``` ```bash # Graph ML export with custom sampling density graph-ml part.brep --uv-samples 16 --edge-samples 32 > part.json ``` -------------------------------- ### Example: Validating Graphs with occtkit graph-validate --serve Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Demonstrates sending two requests to the `graph-validate` verb in serve mode: one for a valid file and one for a non-existent file. This shows how the server handles both successful and failed requests. ```bash printf '{"args":["good.brep"]}\n{"args":["missing.brep"]}\n' \ | occtkit graph-validate --serve ``` ```json {"exit":0,"ok":true,"stderr":"","stdout":"graph-validate: OK (42 nodes, 0 warnings)\n"} {"error":"file not found: missing.brep","exit":1,"ok":false,"stderr":"","stdout":""} ``` -------------------------------- ### Basic Script Structure with Metadata Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/SCRIPT_WORKFLOW.md Initializes the script context with metadata, including name, revision, dates, source, tags, and notes. This is the starting point for any OCCTSwift script. ```swift import OCCTSwift import ScriptHarness let ctx = ScriptContext(metadata: ManifestMetadata( name: "JIS 60kg Rail", revision: "2", dateCreated: ISO8601DateFormatter().date(from: "2026-03-18T00:00:00Z"), dateModified: Date(), source: "JIS E 1101:2012", tags: ["rail", "profile", "Z-scale", "NEM-120"], notes: "Built from standard dimensions table" )) let C = ScriptContext.Colors.self // ... geometry code ... try ctx.emit(description: "JIS 60kg rail profile") ``` -------------------------------- ### Example manifest.json Structure Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/script-iteration.md This JSON structure represents the manifest file generated by `ScriptContext`, including body information and metadata. ```json { "bodies": [ { "color": [0.7, 0.7, 0.75, 1.0], "file": "body-0.brep", "format": "brep", "id": "bracket", "name": "Bracket" }, { "color": [1.0, 0.9, 0.2, 1.0], "file": "body-1.brep", "format": "brep", "id": "footprint", "name": "Footprint" } ], "description": "Drilled mounting bracket", "metadata": { "dateModified": "2026-06-20T00:00:00Z", "name": "Drilled mounting bracket", "notes": "80 × 40 × 8 mm blank; M5 holes at 10 mm from each corner; 20 × 6 mm centre slot", "revision": "1", "source": "Internal design", "tags": ["bracket", "hardware", "mounting"] }, "timestamp": "2026-06-20T00:00:00Z", "version": 1 } ``` -------------------------------- ### Invoke occtkit Verb from Source Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Illustrates invoking a verb directly from a source code checkout without installation. This is useful for development and testing. ```bash swift run occtkit graph-validate body.brep ``` -------------------------------- ### Markdown Page Layout Example Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/README.md Illustrates the standard markdown structure for documenting a family of OCCTSwiftScripts commands. This includes frontmatter, a family description, entry links, and detailed sections for each verb. ```markdown --- title: parent: CLI & API Reference nav_order: --- # <1–3 sentences: what this family is for and when you reach for it.> ## Entries [`verb-a`](#verb-a) · [`verb-b`](#verb-b) · … --- ## `verb-name` ← one `##` per verb / API entry, in the page's order **Input** — flag-form, JSON-form (stdin or argv path), or both. Note `--serve` if relevant. **Parameters** | name | type | required | description | |------|------|:--------:|-------------| | `--output` / `output` | string | yes | … | | `--kind` / `kind` | enum | yes | one of `linear` \| `circular` \| `mirror` | **Returns** — **Example** ​```bash occtkit verb-name in.brep --output out.brep --kind circular ​``` ​```json // example result (stdout JSON) { "ok": true, "outputs": ["out.brep"] } ​``` **Drives** — the OCCTSwift / library call behind it. *(omit if not applicable)* **Notes** — gotchas / cross-references. *(omit if none)* ``` -------------------------------- ### Query Topology Output (Planar Faces) Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/introspection-and-measurement.md Example JSON output for querying planar faces, showing results with stable IDs, surface type, area, center of mass, normal, and bounding box for each face. ```json { "entity": "face", "results": [ { "id": "face[0]", "surfaceType": "plane", "area": 2400.0, "centerOfMass": [0.0, 0.0, 49.0], "normal": [0.0, 0.0, 1.0], "boundingBox": { "min": [-40.0, -30.0, 49.0], "max": [40.0, 30.0, 49.0] } }, { "id": "face[1]", "surfaceType": "plane", "area": 2400.0, "centerOfMass": [0.0, 0.0, 0.0], "normal": [0.0, 0.0, -1.0], "boundingBox": { "min": [-40.0, -30.0, 0.0], "max": [40.0, 30.0, 0.0] } } ], "total": 2, "truncated": false } ``` -------------------------------- ### Clone and Build OCCTSwiftScripts Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/getting-started.md Clone the repository and build the project. The first build may take longer than subsequent incremental builds. ```bash git clone https://github.com/SecondMouseAU/OCCTSwiftScripts.git cd OCCTSwiftScripts swift build # first build ~30s, incremental ~1-2s ``` -------------------------------- ### Run OCCTSwiftScripts Recipe Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/authoring-geometry.md Executes a Swift script using the occtkit run harness. Use --format brep for BREP files or --format step for STEP files. ```bash swift run occtkit run recipes/01-mounting-bracket/main.swift --format brep ``` -------------------------------- ### Render Recipe Previews Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/recipes/README.md Regenerate the output PNG preview images for all recipes using 'make recipes-render'. This process can be skipped if Metal is not available. ```bash make recipes-render ``` -------------------------------- ### ScriptContext init Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Initializes a script context, accumulating geometry and writing BREP + STEP files to the output directory on emit(). ```APIDOC ## ScriptContext init ### Description Initializes a script context; accumulates geometry and writes BREP + STEP files to the output directory on `emit()`. ### Signature ```swift ScriptContext(exportSTEP: Bool = true, metadata: ManifestMetadata? = nil) ``` ### Parameters #### Initializer Parameters - **exportSTEP** (Bool) - Optional - Whether to write a combined `output.step` file (disable to skip STEP for speed) - **metadata** (ManifestMetadata?) - Optional - Optional project metadata (name, revision, tags, notes) written into `manifest.json` ### Notes `ScriptContext` is `Sendable` (thread-safe via internal NSLock). Output directory is cleaned on init; if you call `ScriptContext()` multiple times in one script, only the final `emit()` persists. ``` -------------------------------- ### Uninstall occtkit CLI Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Uninstalls the occtkit CLI by removing the installed files and symlinks. ```bash make uninstall ``` -------------------------------- ### Standard ISO-View Render with Edge Overlay Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/mesh-and-render.md Generates a standard PNG preview with shaded edges from a BREP file. Requires a Metal-compatible device. ```bash occtkit render-preview part.brep \ --output /tmp/part_iso.png \ --camera iso \ --display-mode shaded-with-edges \ --background light \ --width 1200 \ --height 900 ``` -------------------------------- ### Load BREP File Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/io.md Loads a .brep file and emits a manifest entry. Specify the input BREP path and the output directory for the manifest. ```bash occtkit load-brep /tmp/part.brep --emit-manifest /tmp/output --id mypart --color "#a0a0c0" ``` -------------------------------- ### Add Component-Level Metadata Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/io-and-assemblies.md Applies metadata to a specific component within an assembly, identified by its ID. This example adds metadata to the 'MountingPlate' component. ```bash occtkit set-metadata /tmp/bracket_meta.xbf \ --output /tmp/bracket_meta.xbf \ --scope component \ --component-id 3 \ --title "Mounting Plate" \ --part-number "MP-0003" \ --revision "A" \ --material "304 Stainless Steel" \ --weight 0.42 ``` -------------------------------- ### Drawing Export Command Line Usage Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/DrawingComposer.md Examples of how to use the `drawing-export` command with a JSON specification. You can pipe the JSON directly or provide a file path. ```bash echo '{ ... spec above ... }' | drawing-export ``` ```bash drawing-export spec.json ``` -------------------------------- ### Successful Script Execution Result Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Example JSON output for a successful script execution. It indicates success, exit code, and a summary of the output generated by the script. ```json { "ok": true, "exit": 0, "stdout": "Script output: 2 bodies written to ~/.occtswift-scripts/output\n STEP: output.step\n Graphs: 1 topology graph(s)" } ``` -------------------------------- ### Load BREP and Emit Manifest Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Loads a BREP file and generates a ScriptManifest for OCCTSwiftViewport. Supports specifying ID, color, and allowing invalid geometry. ```bash load-brep part.brep --emit-manifest ~/.occtswift-scripts/output --color "#7799bb" ``` -------------------------------- ### Add Solid Shapes with Color Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Example of adding solid shapes with predefined colors using the ScriptContext. Use custom RGBA arrays for custom colors. ```swift let C = ScriptContext.Colors.self try ctx.add(solid, id: "chassis", color: C.steel) try ctx.add(fastener, id: "bolt", color: C.copper) ``` -------------------------------- ### Export Full Topology Graph with UV and Edge Samples Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/topology-graph.md Use this command to export the complete topology graph, including UV grids and edge samples. Adjust --uv-samples and --edge-samples to control the density of these samples. Defaults are 16 and 32 respectively. ```bash occtkit graph-ml bracket_clean.brep --uv-samples 12 --edge-samples 24 ``` -------------------------------- ### Script Execution Error Result Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/script-harness.md Example JSON output for a script execution that resulted in an error. It indicates failure, the exit code, and details of the error reported in stderr. ```json { "ok": false, "exit": 1, "stderr": "Build failed:\nerror: ...", "error": "Build failed:\nerror: ..." } ``` -------------------------------- ### Build and Run OCCTSwiftScripts Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Build the project and then run your Swift script. Ensure your geometry code is in Sources/Script/main.swift. ```bash swift build ``` ```bash swift run Script ``` -------------------------------- ### Extract Physical Properties Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/introspection-and-measurement.md Use this command to get the volume, surface area, and optimal bounding box of a BREP file. Ensure the file exists and is a valid BREP. ```bash # 1. Physical properties occtkit metrics part.brep --metrics volume,surfaceArea,boundingBoxOptimal ``` -------------------------------- ### Run a Swift Script Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/getting-started.md Execute a Swift script using the 'swift run' command. This will generate output files like .brep, .step, and manifest.json. ```bash swift run Script ``` -------------------------------- ### Query Topology Output (Area Threshold) Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/introspection-and-measurement.md Example JSON output for faces meeting the area threshold, showing a single result that satisfies both the surface type and minimum area criteria. ```json { "entity": "face", "results": [ { "id": "face[0]", "surfaceType": "plane", "area": 2400.0, "centerOfMass": [0.0, 0.0, 49.0], "normal": [0.0, 0.0, 1.0], "boundingBox": { "min": [-40.0, -30.0, 49.0], "max": [40.0, 30.0, 49.0] } } ], "total": 1, "truncated": false } ``` -------------------------------- ### OCCTSwift Script Execution Flow Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Illustrates the process of a Swift script generating BREP files for individual bodies, a combined STEP file for external tools, and a manifest.json to trigger viewport updates. ```text Sources/Script/main.swift ──swift run──> ~/.occtswift-scripts/output/ ├─ manifest.json (trigger file) ├─ body-0.brep (wire sketch) ├─ body-1.brep (filleted solid) ├─ body-2.brep (bolt assembly) └─ output.step (combined, for external tools) │ kqueue watcher (demo app) │ viewport displays ``` -------------------------------- ### Pattern BREP Instances (Mirror, Linear, Circular) Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Create multiple instances of a BREP using the `pattern` verb. Supports mirror, linear, and circular patterns. Output instances are saved as separate files in the specified output directory. ```bash pattern bolt.brep --kind circular --axis-origin 0,0,0 --axis-direction 0,0,1 --total-count 6 --output-dir /tmp/bolts ``` -------------------------------- ### Render Preview Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Renders a PNG preview of BREP files from a specified camera angle. Supports headless rendering, various display modes, background colors, and highlighting specific geometry elements. ```APIDOC ## render-preview ### Description Render a PNG preview of one or more BREPs at a named camera angle, headless, via OCCTSwiftViewport's `OffscreenRenderer`. **This repo owns `render-preview`** — it is the ecosystem's way to embed 3D previews in docs and reports. ### Flag Form `render-preview ... --output [--camera iso|front|back|top|bottom|left|right] [--camera-position x,y,z --camera-target x,y,z [--camera-up x,y,z]] [--width N] [--height N] [--display-mode shaded|wireframe|shaded-with-edges|flat|xray|rendered] [--background light|dark|transparent|#hex] [--show-axes] [--axes-position origin|center|outside|x,y,z] [--show-workplane xy|yz|xz] [--highlight face[N],edge[M],vertex[K]] [--highlight-color #hex]` (defaults: `--camera iso`, `--width 800`, `--height 600`, `--display-mode shaded`, `--background light`) ### JSON Form `{ "inputs": ["a.brep",...], "outputPath": "...", "camera": "iso", "width": N, ... }` ### Output `{ outputPath, width, height, mimeType: "image/png" }` ### Examples ```bash render-preview part.brep --output part.png --camera iso --display-mode shaded-with-edges render-preview part.brep --output hl.png --highlight 'face[3],edge[7]' --highlight-color '#ffa500' ``` ``` -------------------------------- ### Feature Recognition Output Example Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/introspection.md This JSON output represents the detected pockets, holes, and unified features from a BREP model. It includes geometric details, topological references, and confidence scores for each identified feature. ```json { "pockets": [ { "floorFaceIndex": 10, "wallFaceIndices": [11, 12, 13], "zLevel": 0.0, "depth": 5.0, "isOpen": false, "bounds": { "min": [0.0, 0.0, -5.0], "max": [20.0, 20.0, 0.0] } } ], "holes": [ { "faceIndex": 4, "radius": 3.0, "depth": 12.0 }, { "faceIndex": 5, "radius": 3.0, "depth": 12.0 } ], "features": [ { "id": "feat[0]", "kind": "pocket", "confidence": 1.0, "params": { "zLevel": 0.0, "depth": 5.0, "isOpen": 0.0, "pocketIndex": 0.0 }, "topologyRefs": ["face[10]", "face[11]", "face[12]", "face[13]"] }, { "id": "feat[1]", "kind": "hole", "confidence": 1.0, "params": { "radius": 3.0, "depth": 12.0, "holeIndex": 0.0 }, "topologyRefs": ["face[4]"] } ] } ``` -------------------------------- ### Example: Handling Malformed JSON Requests Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Illustrates how the OCCTKit server responds to a malformed JSON request line while continuing to process subsequent valid requests. An error envelope is emitted for the invalid request. ```bash printf 'not json\n{"args":["body.brep"]}\n' \ | occtkit graph-validate --serve ``` ```json {"error":"invalid request JSON: ...","exit":1,"ok":false,"stderr":"","stdout":""} {"exit":0,"ok":true,"stderr":"","stdout":"graph-validate: OK (42 nodes, 0 warnings)\n"} ``` -------------------------------- ### Import STEP/IGES/STL/OBJ Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/io-and-assemblies.md Use `occtkit import` to load neutral CAD files. The format is inferred from the file extension. `--emit-manifest` outputs scene data, and `--id-prefix` customizes generated IDs. ```bash occtkit import /tmp/bracket_assy.step \ --emit-manifest /tmp/scene \ --id-prefix bracket ``` ```json { "addedBodyIds": ["bracket_0"], "assembly": null, "warnings": [] } ``` -------------------------------- ### load-brep Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Loads a .brep file and generates a ScriptManifest for OCCTSwiftViewport. This is a no-compile alternative to writing a script for adding and emitting geometry. ```APIDOC ## load-brep ### Description Loads a .brep file and generates a ScriptManifest for OCCTSwiftViewport. This is a no-compile alternative to writing a script for adding and emitting geometry. ### Method Command-line verb ### Parameters #### Path Parameters - **input.brep** (string) - Required - The input BREP file path. #### Optional Flags - **--emit-manifest** (string) - Required - Directory to emit the manifest files. - **--id** (string) - Optional - The ID for the BREP body. - **--color** (string) - Optional - The color for the BREP body in hex format (e.g., \"#rrggbb\"). - **--allow-invalid** (boolean) - Optional - Allows loading of invalid geometry. ### JSON Form ```json { "inputBrep": "string", "emitManifest": "string", "id": "string", "color": "#rrggbb|#rrggbbaa", "allowInvalid": bool } ``` ### Output `{ bodyId, isValid, shapeType, faceCount, edgeCount, vertexCount, boundingBox{min,max} }` ### Example ```bash load-brep part.brep --emit-manifest ~/.occtswift-scripts/output --color "#7799bb" ``` ``` -------------------------------- ### List All occtkit Verbs Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/occtkit-cli.md Lists all available occtkit verbs with their one-line summaries. Useful for discovering available commands. ```bash occtkit --help ``` -------------------------------- ### BREP Metrics Output Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/introspection-and-measurement.md Example JSON output detailing computed metrics including volume, surface area, and optimal bounding box. Note that `centerOfMass` and `boundingBox` might be null if not explicitly computed or relevant. ```json { "volume": 18432.6, "surfaceArea": 7804.1, "centerOfMass": null, "boundingBox": null, "boundingBoxOptimal": { "min": [-40.0, -30.0, 0.0], "max": [40.0, 30.0, 49.0] }, "principalAxes": null } ``` -------------------------------- ### load-brep Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/io.md Loads a `.brep` file and emits a manifest entry for OCCTSwiftViewport. It supports loading topologically invalid shapes and allows customization of body ID and color. ```APIDOC ## `load-brep` ### Description Load a `.brep` file and emit a manifest entry for OCCTSwiftViewport. ### Input Flag form or JSON form (stdin or argv path). ### Parameters #### Path Parameters - **inputBrep** (string) - yes - Path to the `.brep` file to load; manifest output directory. - **--emit-manifest** (string) - yes - Path to the `.brep` file to load; manifest output directory. #### Query Parameters - **id** (string) - no - Body ID to assign; auto-generated from filename if omitted. - **--id** (string) - no - Body ID to assign; auto-generated from filename if omitted. - **color** (string) - no - Hex colour `#rrggbb` or `#rrggbbaa` (0–255 per channel); omit for default. - **--color** (string) - no - Hex colour `#rrggbb` or `#rrggbbaa` (0–255 per channel); omit for default. - **allowInvalid** (boolean) - no - Load a topologically invalid shape as-is; default `false`. - **--allow-invalid** (boolean) - no - Load a topologically invalid shape as-is; default `false`. ### Returns JSON envelope with `bodyId`, `isValid`, `shapeType` (lowercase: `solid`, `shell`, `compound`, `face`, `wire`, `edge`, `vertex`), `faceCount`, `edgeCount`, `vertexCount`, `boundingBox` (`{ min: [...], max: [...] }`). Side effect: writes `.brep` and `manifest.json` to `--emit-manifest` directory. ### Request Example ```bash occtkit load-brep /tmp/part.brep --emit-manifest /tmp/output --id mypart --color "#a0a0c0" ``` ### Response Example ```json { "bodyId": "mypart", "isValid": true, "shapeType": "solid", "faceCount": 6, "edgeCount": 12, "vertexCount": 8, "boundingBox": { "min": [0.0, 0.0, 0.0], "max": [100.0, 50.0, 25.0] } } ``` ``` -------------------------------- ### Select Face Neighbors with Convexity Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/topology-graph.md Use `graph-select` with `face-neighbors` query to get adjacent faces, their convexity, shared edge count, and plane information. Specify the face index using `--face N`. ```bash occtkit graph-select bracket_clean.brep --query face-neighbors --face 2 ``` ```json { "query": "face-neighbors", "face": 2, "isPlanar": true, "isVertical": false, "isHorizontal": true, "normal": [0, 1, 0], "neighbors": [ { "face": 0, "convexity": "convex", "sharedEdgeCount": 1 }, { "face": 3, "convexity": "concave", "sharedEdgeCount": 1 } ] } ``` -------------------------------- ### Run occtkit graph-compact Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Compacts a BREP file using the occtkit CLI. ```bash graph-compact in.brep out.brep ``` -------------------------------- ### Progressively union multiple BREP instances Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/construction.md This script demonstrates how to progressively union multiple BREP files into a single compound. It starts by copying the first file and then iteratively unions subsequent files into it, creating intermediate files. ```bash cp /tmp/holes/pattern_0.brep /tmp/holes_all.brep for i in 1 2 3 4 5; do occtkit boolean --op union \ --a /tmp/holes_all.brep \ --b /tmp/holes/pattern_$i.brep \ --output /tmp/holes_all_next.brep mv /tmp/holes_all_next.brep /tmp/holes_all.brep done ``` -------------------------------- ### render-preview Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/render.md Renders a headless PNG preview of one or more BREPs. Supports camera presets, display modes, and AIS scene overlays. ```APIDOC ## render-preview ### Description Render a headless PNG preview of one or more BREPs with camera presets, display modes, and AIS scene overlays. ### Method This is a command-line tool or can be invoked via stdin/argv path for JSON input. ### Endpoint N/A (CLI Tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Input can be flag-form or JSON-form (stdin or argv path). - **`` / `inputs`** (string[]) - Required - One or more BREP paths; or a `--manifest` path (directory with `manifest.json`). - **`--output` / `outputPath`** (string) - Required - Write path for the PNG file. - **`--camera` / `camera`** (enum) - Optional - Camera preset: `iso` | `front` | `back` | `top` | `bottom` | `left` | `right`. Default: `iso`. - **`--camera-position` / `cameraPosition`** (float[3]) - Optional - Explicit camera eye position `x,y,z`. Overrides preset. - **`--camera-target` / `cameraTarget`** (float[3]) - Optional - Explicit look-at point `x,y,z`. Required if `--camera-position` is given. - **`--camera-up` / `cameraUp`** (float[3]) - Optional - Camera up vector `x,y,z`. Default: `0,0,1`. - **`--width` / `width`** (integer) - Optional - Output image width in pixels. Default: 800. - **`--height` / `height`** (integer) - Optional - Output image height in pixels. Default: 600. - **`--display-mode` / `displayMode`** (enum) - Optional - Rendering style: `shaded` | `wireframe` | `shaded-with-edges` | `flat` | `xray` | `rendered`. Default: `shaded`. - **`--background` / `background`** (string) - Optional - Background color: `light` | `dark` | `transparent` | `#rrggbb` | `#rrggbbaa`. Default: `light`. - **`--show-axes` / `showAxes`** (boolean) - Optional - Overlay an AIS Trihedron (X/Y/Z axes). Default: false. - **`--axes-position` / `axesPosition`** (string) - Optional - Trihedron anchor: `origin` | `center` | `outside` | `x,y,z`. Default: `outside`. - **`--show-workplane` / `showWorkplane`** (enum) - Optional - Overlay a construction plane: `xy` | `yz` | `xz`. - **`--highlight` / `highlight`** (string[]) - Optional - Extract and highlight sub-shapes from the **first** input BREP: `face[N],edge[M],vertex[K]` (comma-separated). - **`--highlight-color` / `highlightColor`** (string) - Optional - Sub-shape highlight color: `#rrggbb` | `#rrggbbaa`. Default: `#ffa500` (orange). ### Request Example ```bash occtkit render-preview part.brep --output /tmp/part.png --camera iso --display-mode shaded-with-edges --width 1200 --height 900 --show-axes --axes-position outside ``` ### Response #### Success Response Returns a JSON envelope with the output PNG path and rendered image dimensions. - **`outputPath`** (string) - Path to the written PNG file. - **`width`** (integer) - Width of the rendered image in pixels. - **`height`** (integer) - Height of the rendered image in pixels. - **`mimeType`** (string) - MIME type of the output, always `image/png`. #### Response Example ```json { "outputPath": "/tmp/part.png", "width": 1200, "height": 900, "mimeType": "image/png" } ``` ### Error Handling Fails if the input BREP is invalid, Metal device is unavailable, or a highlighted sub-shape (face/edge/vertex) is not found on the source (warning to stderr, continues). ``` -------------------------------- ### Create Helical Spring using Pipe Sweep Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/sweeps-lofts-patterns.md Generates a helical spring by sweeping a circular profile along a helix path. Ensure the section circle is positioned at the helix start and oriented along the tangent to avoid errors. ```swift // Coil centre-line about Z let path = Wire.helix(radius: meanRadius, pitch: pitch, turns: activeCoils)! // Section at the helix start, facing along the start tangent // Helix tangent at θ=0: (0, R, pitch/2π), normalised let t = SIMD3(0, meanRadius, pitch / (2 * .pi)) let tLen = (t.x*t.x + t.y*t.y + t.z*t.z).squareRoot() let tangent = t / tLen let section = Wire.circle(origin: SIMD3(meanRadius, 0, 0), normal: tangent, radius: wireDia / 2)! let spring = Shape.sweep(profile: section, along: path)! ``` -------------------------------- ### Tessellate and Inspect Mesh Quality Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/mesh-and-render.md Run mesh tessellation with specified linear and angular deflection. Use --no-return-geometry to suppress inline geometry and focus on quality metrics. Omit --output to get inline geometry. ```bash occtkit mesh part.brep \ --linear-deflection 0.05 \ --angular-deflection 0.3 \ --parallel \ --no-return-geometry ``` ```json { "triangleCount": 8214, "vertexCount": 4112, "quality": { "minAspectRatio": 1.04, "meanAspectRatio": 2.11, "degenerateTriangles": 0, "nonManifoldEdges": 0 }, "geometry": null, "outputPath": null } ``` -------------------------------- ### Run occtkit graph-ml with options Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/README.md Generates a graph ML representation from a BREP file with specified UV and edge samples. ```bash graph-ml part.brep --uv-samples 16 --edge-samples 32 > part.json ``` -------------------------------- ### Import CAD Files and Emit Manifest Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/occtkit-verbs.md Imports various CAD formats (STEP, IGES, STL, OBJ) and emits a BREP file per top-level body. Supports preserving assembly structure and healing geometry. ```bash import widget.step --emit-manifest /tmp/out --preserve-assembly ``` -------------------------------- ### Minimal Reconstruct Example: Revolve then Drill Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/reconstruction-and-sheet-metal.md This snippet demonstrates the minimal configuration for the `reconstruct` verb, creating a revolved body and then drilling a hole in it. The JSON input defines the output directory, name, and the sequence of features to build. The `occtkit reconstruct` command executes the process. ```bash cat > /tmp/shaft.json <<'EOF' { "outputDir": "/tmp/out", "outputName": "shaft", "features": [ { "kind": "revolve", "id": "body", "profile_points_2d": [[0,0], [12,0], [12,60], [0,60]], "axis_origin": [0, 0, 0], "axis_direction": [0, 0, 1], "angle_deg": 360 }, { "kind": "hole", "id": "centre_hole", "center": [0, 0, 0], "direction": [0, 0, 1], "radius": 4, "depth": 60 } ] } EOF occtkit reconstruct /tmp/shaft.json ``` -------------------------------- ### Tessellate-Decimate-Preview Pipeline Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/cookbook/mesh-and-render.md This script demonstrates a complete pipeline for processing a 3D part. It includes steps for checking tessellation quality, generating a fine mesh, creating a simplified LOD mesh for web viewing, and rendering a PNG preview with specified camera and display settings. ```bash # 1. Check tessellation quality. occtkit mesh part.brep \ --linear-deflection 0.05 --angular-deflection 0.3 \ --no-return-geometry ``` ```bash # 2. Write the fine mesh if metrics are acceptable. occtkit mesh part.brep \ --linear-deflection 0.05 --angular-deflection 0.3 \ --output /tmp/part_fine.stl ``` ```bash # 3. Produce a lightweight LOD mesh for the web viewer. occtkit simplify-mesh part.brep \ --linear-deflection 0.05 \ --target-reduction 0.75 \ --max-hausdorff-distance 0.2 \ --output /tmp/part_lod.obj ``` ```bash # 4. Render a PNG preview with axes. occtkit render-preview part.brep \ --output docs/guides/cookbook/images/render-preview-demo.png \ --camera iso \ --display-mode shaded-with-edges \ --background light \ --width 1200 --height 900 \ --show-axes ``` -------------------------------- ### Initialize ScriptContext Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/reference/ScriptHarness.md The ScriptContext initializer sets up the output directory, cleaning it before use. It supports optional STEP export and metadata. ```swift public final class ScriptContext: Sendable { public let exportSTEP: Bool public let metadata: ManifestMetadata? public init(exportSTEP: Bool = true, metadata: ManifestMetadata? = nil) } ``` -------------------------------- ### occtkit CLI --serve Mode Source: https://github.com/secondmouseau/occtswiftscripts/blob/main/docs/guides/getting-started.md Utilize the --serve mode of occtkit for processing requests line by line in JSONL format, suitable for automated consumers. ```bash # --serve: one envelope per request line printf '{"args":["a.brep"]}\n{"args":["b.brep"]}\n' | occtkit graph-validate --serve ```