Metadata-Version: 2.4
Name: sanchousf-ai-toolkit-cad
Version: 0.4.0
Summary: Modular 3D CAD modeling, procedural synthesis, and interactive scene viewer
Author: sanchousf
Author-email: sanchousf@gmail.com
License-Expression: MIT
Project-URL: Homepage, https://github.com/sanchousf/ai-toolkit
Project-URL: Repository, https://github.com/sanchousf/ai-toolkit
Project-URL: Issues, https://github.com/sanchousf/ai-toolkit/issues
Project-URL: Documentation, https://github.com/sanchousf/ai-toolkit#readme
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
Classifier: Topic :: Multimedia :: Graphics :: Viewers
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: dearpygui>=1.10.0
Requires-Dist: numpy>=1.22.0
Requires-Dist: scipy>=1.9.0
Requires-Dist: scikit-image>=0.19.0
Requires-Dist: trimesh>=3.15.0
Requires-Dist: PyOpenGL>=3.1.5
Requires-Dist: pillow>=9.0.0
Requires-Dist: shapely>=2.0.0
Requires-Dist: manifold3d>=3.0.0
Requires-Dist: glfw>=2.5.0
Requires-Dist: matplotlib>=3.5.0
Requires-Dist: rich>=12.0.0
Requires-Dist: tomli>=1.1.0; python_version < "3.11"
Provides-Extra: remesh
Requires-Dist: pyvista>=0.40.0; extra == "remesh"
Provides-Extra: blender
Requires-Dist: bpy>=4.0.0; extra == "blender"
Provides-Extra: test
Requires-Dist: pytest>=8.0.0; extra == "test"
Requires-Dist: pytest-cov>=7.0.0; extra == "test"
Requires-Dist: pyvista>=0.40.0; extra == "test"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
Requires-Dist: pyvista>=0.40.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Provides-Extra: all
Requires-Dist: pyvista>=0.40.0; extra == "all"
Requires-Dist: bpy>=4.0.0; extra == "all"

# 3D CAD Toolkit

A high-performance, modular 3D Computer-Aided Design (CAD), procedural modeling, and visualization engine engineered for both interactive human workflows and autonomous AI agent collaboration.

---

## Key Features

- **Interactive 3D Viewport**:
  - Built with [Dear PyGui](https://github.com/hoffstadt/DearPyGui) for responsive, lightweight cross-platform GUI.
  - Hardware-accelerated OpenGL offscreen rendering with true per-pixel depth buffering (Z-buffer), polygon offset shaded-wireframe overlays, and automatic CPU rasterizer fallback.
  - 3D translation/rotation/scale manipulator gizmos, flying and orbit camera controls, RGB coordinate axes, and build-plate grid.
  - Interactive measurement tools (point-to-point distance, angles, surface area).

- **AI Agent CollabBridge (HTTP & CLI)**:
  - Built-in HTTP JSON API (`port 8765`) and CLI (`bridge.py`) designed specifically for AI pair programmers and autonomous agents.
  - Allows external processes to query scene state, select/inspect objects, trigger parametric tweaks, draw temporary 3D debug overlays, and command camera movements in real time without restarting the viewer.

- **Procedural & Parametric Modeling**:
  - **Primitives**: Box, Sphere, Cylinder, Capsule, Cone, Torus, Extruded Text, and 3D Polylines.
  - **File Asset Loading**: Universal polymorphic asset importing (`FileModel`, `MeshFileModel`, `FileGroupModel`) supporting 3MF, STL, OBJ, PLY, GLB, GLTF, BLEND, and Python scene files (.py) with full multi-part hierarchy grouping and exact triangle mesh Signed Distance Field (SDF) evaluation.
  - **CSG Operations**: Exact Boolean Union, Difference, Intersection, Chamfer, Fillet, Sweep, and Loft via [Manifold3D](https://github.com/elalish/manifold).
  - **Assembly Management**: Hierarchical object groups, transformation hierarchies, and interactive exploded views.

- **Signed Distance Fields (SDF) & Meshing**:
  - Mathematical SDF representation with smooth polynomial CSG blending (`smooth_union`, `smooth_difference`, `smooth_intersection`).
  - Exact Euclidean triangle distance with Voronoi region projection and watertight interior/exterior parity evaluation for arbitrary mesh files (`TriangleMeshSDF`).
  - High-resolution Marching Cubes and Dual Contouring meshing with integrated quadric mesh decimation/simplification.

- **3D Printability Analysis**:
  - Watertight / manifold topology validation.
  - Critical overhang detection and support volume estimation.
  - Build-volume verification against popular printer presets (Bambu Lab, Prusa MK3/MK4, Ender 3, Voron 2.4/350).
  - Automatic print orientation optimization (`--auto-orient`) to minimize support requirements and maximize build-plate contact area.

- **Multi-Format Export & Rendering**:
  - **3D Formats**: 3MF (3D Manufacturing Format with multi-object metadata), Binary/ASCII STL, OBJ, PLY, GLB, and DXF.
  - **High-Resolution Snapshots**: Anti-aliased (SSAA 1x/2x/4x) image snapshots in PNG (with alpha transparency), JPEG, WebP, TIFF, and BMP with customizable camera angles and backgrounds.

- **Cross-Platform & Headless Compatibility**:
  - Tested and supported across Linux (Ubuntu, Debian, and Android Termux/PRoot), macOS, and Windows.
  - Intelligent OpenGL driver probe and caching system to handle headless virtual machines and software rasterization environments.

---

## Directory Structure

```text
cad/
├── view.py                  # Main interactive 3D CAD viewer application
├── save.py                  # Headless scene exporter, snapshot generator & CLI
├── check.py                 # Dedicated headless scene validator & health analyzer
├── bridge.py                # CollabBridge CLI for external & AI agent control
├── remesh.py                # Standalone mesh decimation & remeshing tool
├── check.sh / check.bat     # Shell launchers for headless validation
├── requirements.txt         # Core runtime dependencies
├── requirements-dev.txt     # Development and testing dependencies
├── pytest.ini               # Pytest configuration (90% coverage enforcement)
│
├── core/                    # Core engine implementation
│   ├── analysis/            # 3D printability, overhangs, bed envelopes
│   ├── bridge/              # HTTP CollabBridge server & protocol
│   ├── common/              # Global constants and progress reporting
│   ├── config.py            # Workspace configuration loader & schema
│   ├── init.py              # Project scaffolder (cad init / cad config)
│   ├── introspection.py     # Schema introspection & scene template generator
│   ├── geometry/            # Mesh representations, transforms, STL I/O
│   ├── io/                  # Multi-format mesh exporters (STL, OBJ, GLB, etc.)
│   ├── modeling/            # CSG booleans, assemblies, sketches, remeshing
│   ├── primitives/          # Parametric shapes, text, polyline sweeps
│   ├── rendering/           # OpenGL FBO renderer, DPG viewport, gizmo, camera
│   ├── scratchpad/          # Temporary geometric canvas for experiments
│   ├── sdf/                 # Mathematical SDF models and Marching Cubes mesher
│   └── spatial/             # Raycasting, BVH, and screen-space object picking
│
├── scenes/                  # Ready-to-run procedural scene definitions
│   ├── assembly_demo.py     # Multi-part mechanical assembly with exploded view
│   ├── parametric_demo.py   # Live slider-driven parametric model
│   ├── polyline.py          # Complex 3D swept path demonstrations
│   └── test.py              # 3D primitives, text, and SDF CSG / Gyroid models
│
├── scripts/                 # Modular helper scripts
│   ├── env.sh / env.bat     # Dynamic virtual environment and path discovery
│   ├── setup_base.sh/.bat   # Unified 5-step installer backend
│   ├── check_gl.sh          # Self-testing OpenGL compatibility probe & cache
│   └── probe_gl.py          # Micro-probe for OpenGL rasterization validation
│
├── ci/                      # Continuous Integration
│   └── action.yml           # GitHub Actions composite action for CAD
│
└── tests/                   # Test suite (314 unit & integration tests)
```

---

## Installation & Setup

Automated setup scripts create an isolated `.venv`, upgrade `pip`, install all requirements, and verify core library imports.

### Runtime Installation (Users)
- **Linux / macOS / Termux**:
  ```bash
  ./setup.sh
  ```
- **Windows**:
  ```cmd
  setup.bat
  ```

### Developer Installation (Includes Testing & Coverage Tools)
- **Linux / macOS / Termux**:
  ```bash
  ./setup_dev.sh
  ```
- **Windows**:
  ```cmd
  setup_dev.bat
  ```

---

## Quick Start

### 1. Project Initialization & Scaffolding (`cad init`)

Initialize a new CAD modeling workspace with auto-detected directories, workspace configuration, starter scene, and convenience launchers:

```bash
# Initialize current directory with auto-detected scenes/ and output/
cad init

# Initialize a custom directory with a 300x300x400 mm bed and pre-installed agent skill
cad init path/to/project --bed 300x300x400 --install-skill

# Machine-readable JSON output for automated AI agent scaffolding
cad init path/to/project --bed voron350 --json
```

**Generated Project Artifacts:**
- `cad.config.json` & `.cadrc`: Workspace configuration defining `scenes_dir`, `export_dir`, `default_scene`, and `printer_bed`.
- `scenes/`: Dedicated scene folder with an auto-generated starter template (if empty).
- `output/`: Default target for headless STL/GLB exports.
- Convenience Launchers:
  - `view.bat` / `view.sh` (or `run.bat` / `run.sh`): Interactive 3D CAD viewport.
  - `check.bat` / `check.sh`: Headless manifold and printability validator.
  - `export.bat` / `export.sh`: Headless 3D mesh exporter.
  - `new_scene.bat`: Scene template generator (`cad new-scene`).
  - `bridge.bat` / `bridge.sh`: AI agent CollabBridge CLI.

---

### 2. Workspace Configuration & Schema (`cad config` & `cad schema`)

Inspect, validate, or introspect workspace settings:

```bash
# Print active workspace configuration and resolved directory paths
cad config show
cad config show --json

# Validate workspace configuration syntax, scenes directory, and printer bed settings
cad config validate

# Dump full JSON schema for workspace configuration
cad schema config --json
cad config schema
```

---

### 3. Launching the Interactive 3D Viewer

**Viewing scenes in your active project folder or custom path (`view.sh` / `view.bat`):**
```bash
# By default, discovers scenes in the current terminal directory:
./view.sh

# Or specify a target directory, relative or absolute path, or standalone scene file:
./view.sh path/to/scenes/
./view.sh path/to/my_scene.py
# Windows: view.bat [path]
```

**Running bundled repository example scenes (`run.sh` / `run.bat`):**
```bash
./run.sh
# Windows: run.bat
```

Load a specific scene:
```bash
./run.sh -s scenes/assembly_demo.py
./run.sh -s scenes/parametric_demo.py
```

#### Viewport Navigation Controls:
- **Left Mouse Click / Drag**: Rotate camera around focal point / select objects in pick mode.
- **Right Mouse Drag**: First-person look / pan-tilt camera in place (WASD + Q/E to fly in 3D).
- **Middle Mouse Drag**: Pan camera horizontally and vertically in view plane.
- **Mouse Wheel / Scroll**: Zoom in and out.
- **Ctrl + Left Mouse Drag**: Draw 3D polyline annotations directly onto object surfaces or in 3D scene space.
- **C**: Cycle active stroke color through palette (`Yellow`, `Red`, `Green`, `Blue`, `Cyan`, `Purple`, `Orange`, `White`).
- **1 – 8**: Quick-select stroke colors (1: Yellow, 2: Red, 3: Green, 4: Blue, 5: Cyan, 6: Purple, 7: Orange, 8: White).
- **Ctrl + Z**: Undo the last drawn scratchpad stroke.
- **Toolbar & Panels**: Switch between Move, Rotate, Scale, and Measure tools; toggle shaded and wireframe modes; inspect object geometry; recolor strokes; sweep strokes to solid tubes (`Sweep to Solid`) or polylines.

---

### 4. Headless Scene Exporting & Snapshot Generation (`save.py`)

Export a scene directly to binary STL:
```bash
./save.sh -s scenes/assembly_demo.py -o output.stl
```

Export to OBJ, GLB, or PLY format:
```bash
./save.sh -s scenes/parametric_demo.py -e model.glb
```

Generate a high-resolution 4K isometric preview image with anti-aliasing:
```bash
./save.sh -s scenes/assembly_demo.py -i preview.png --resolution 3840x2160 --cam-ori iso --supersample 4
```

Analyze 3D printability and optimize print orientation for a Bambu Lab bed:
```bash
./save.sh -s scenes/assembly_demo.py --analyze-print --printer-bed bambu --auto-orient
```

Merge scene objects using Smooth Boolean Union (SDF Marching Cubes):
```bash
./save.sh -s scenes/assembly_demo.py --sdf-merge smooth_union --sdf-k 3.0 -o merged.stl
```

---

### 5. AI Agent CollabBridge (`bridge.py`)

When `view.py` is running, the viewer hosts an HTTP JSON endpoint on port `8765`. AI agents or terminal users can query and control the application live via `./bridge.sh`:

```bash
# Check viewer status and active scene
./bridge.sh status

# List all available scenes
./bridge.sh scenes

# Load a new scene dynamically
./bridge.sh scene scenes/assembly_demo.py

# Select an object by name
./bridge.sh select "BasePlate"

# Translate selected object by [+10mm X, 0mm Y, +5mm Z]
./bridge.sh translate "10,0,5"

# Adjust exploded view ratio (0.0 = assembled, 1.0 = exploded)
./bridge.sh explode 0.5

# Request a 3D printability check
./bridge.sh print-check

# Query scratchpad 3D drawings with lengths, bounds, and colors
./bridge.sh drawings --json

# Query or set active stroke color
./bridge.sh color
./bridge.sh color red
./bridge.sh color green 0   # Recolor stroke #0 to green

# Clear all annotations
./bridge.sh clear-drawings

# Sweep last stroke to a 3D solid tube or PolylineModel
./bridge.sh sweep -1 2.5
./bridge.sh polyline -1 1.5

# Export current viewer model to disk
./bridge.sh export "exported_model.stl"
```

---

### 6. Headless Scene Validation & Health Analyzer (`check.py` / `check.sh` / `check.bat`)

Verify CAD scene files headlessly without opening an OS window. Performs import validation, scene instantiation, UI dry-run via mock DearPyGui context, geometric evaluation, and 3D printability diagnostics:

```bash
# Validate a specific scene:
./check.sh scenes/parametric_demo.py
# Windows: check.bat scenes\parametric_demo.py

# Emit machine-parseable structured JSON output:
./check.sh scenes/parametric_demo.py --json

# Validate all scenes in the workspace or custom directory:
./check.sh --all --json

# Override scene parameters for validation:
./check.sh scenes/parametric_demo.py --param length=120 --param width=80

# Strict mode (exit with code 1 on non-watertight geometry or bed limit violation):
./check.sh scenes/parametric_demo.py --strict --bed 300x300x400
```

---

### 7. Running Tests & Code Coverage

Execute the complete test suite:
```bash
./run_tests.sh
# Windows: run_tests.bat
```

- **Enforced Coverage**: [pytest.ini](pytest.ini) requires a minimum of **90% test coverage** across the `core/` package; test runs below this threshold automatically fail.
- **Coverage Reports**: HTML reports are generated at `cad/htmlcov/index.html` and XML reports at `cad/coverage.xml`.

---

## OpenGL Driver Compatibility & Probing

In certain virtualized, containerized, or headless environments (e.g. Android PRoot, headless CI runners, or systems without GPU drivers), default OpenGL drivers may trigger errors or lack WGL/GLX support.

The toolkit includes an automated driver probe:
- **Automatic Fallback**: [scripts/check_gl.sh](scripts/check_gl.sh) tests OpenGL rasterization via [scripts/probe_gl.py](scripts/probe_gl.py) and caches the result in `.venv/.gallium_probe`. If default Mesa `llvmpipe` fails, it automatically selects `softpipe`.
- **Force Re-testing**: Pass `--retest-gl` to any launcher script to re-evaluate the host environment:
  ```bash
  ./run.sh --retest-gl
  ./run_tests.sh --retest-gl
  # Or via check_gl.sh directly:
  ./scripts/check_gl.sh --retest
  ```
- **Inspect Status**:
  ```bash
  ./scripts/check_gl.sh --status
  ```

---

## Continuous Integration

Cross-platform CI is configured in [`.github/workflows/cad.yml`](../.github/workflows/cad.yml) and executes on every push and pull request to `main`, `dev/**`, and `release/**`:
- **Matrix**: Ubuntu 24.04 (with Xvfb), Windows Server 2022, and macOS 14/15 on Python 3.12.
- **Action**: Uses the self-contained composite action in [ci/action.yml](ci/action.yml).
- **Artifacts**: Uploads HTML coverage reports on all platforms and submits to Codecov.
