{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# STL import and facet repair\n",
    "\n",
    "STL is the most common exchange format for scans, 3D printing and meshes from other programs. It\n",
    "stores loose triangles: no faces, no edges, no units, often no consistent orientation, sometimes\n",
    "with holes. Before such a file can be meshed for a simulation it has to become a closed body.\n",
    "\n",
    "| step | call | result |\n",
    "|---|---|---|\n",
    "| read | `load(\"part.stl\")` | a `FacetBody`: triangles joined at their corners, grouped into faces at sharp edges |\n",
    "| orient | `body.repaired()` | every triangle faces out of the material |\n",
    "| close | `body.closed()` | holes in the skin filled from their rims, no point added |\n",
    "| rebuild | `body.exact()` | planes, cylinders, cones, spheres and tori recognised; an exact CAD solid |\n",
    "| mesh | `FacetMesher` on the facets or `TetrahedralMesher` on the exact solid | tetrahedra |\n",
    "\n",
    "The file `stl_import_facet_repair.stl` is written by `stl_import_facet_repair_geometry.py`, which\n",
    "builds the part with the CAD objects of OneSimulation, writes its triangles and damages them on\n",
    "purpose.\n",
    "\n",
    "**Reference.** The pillow block in closed form: base plate $L\\times W\\times t$, boss of radius\n",
    "$R$ and height $h$, two bolt holes of radius $r_h$ through the plate and a bore of radius $r_b$\n",
    "through plate and boss:\n",
    "$V = LWt + \\pi R^2 h - 2\\pi r_h^2 t - \\pi r_b^2 (t + h)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from collections import Counter\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d3 import Cylinder\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import FacetMesher, TetrahedralMesher\n",
    "from onesim.meshing.quality import quality\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading the file\n",
    "\n",
    "The units of an STL file are not stored; the file is in metres. `holes()` lists the open rims\n",
    "of the skin."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "raw = load(\"stl_import_facet_repair.stl\")\n",
    "exact = (\n",
    "    0.12 * 0.05 * 0.015\n",
    "    + np.pi * 0.022**2 * 0.03\n",
    "    - 2 * np.pi * 0.005**2 * 0.015\n",
    "    - np.pi * 0.012**2 * 0.045\n",
    ")\n",
    "print(\n",
    "    f\"{len(raw.points)} points, {len(raw.triangles)} triangles, {len(raw.faces)} faces found at sharp edges\"\n",
    ")\n",
    "print(\n",
    "    f\"closed: {raw.is_closed}, valid: {raw.is_valid}, open rims: {len(raw.holes())} with {[len(rim) for rim in raw.holes()]} edges\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Repair\n",
    "\n",
    "Orientation first, then the holes. The repaired skin encloses a volume again."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "oriented = raw.repaired()\n",
    "closed = oriented.closed()\n",
    "print(\n",
    "    f\"after repaired(): closed {oriented.is_closed}, open rims {len(oriented.holes())}\"\n",
    ")\n",
    "print(\n",
    "    f\"after closed():   closed {closed.is_closed}, valid {closed.is_valid}, {len(closed.triangles)} triangles, \"\n",
    "    f\"{len(closed.points)} points (none added)\"\n",
    ")\n",
    "print(\n",
    "    f\"volume of the facet body {closed.measure * 1e6:.4f} cm3, closed form {exact * 1e6:.4f} cm3, \"\n",
    "    f\"deviation {closed.measure / exact - 1:+.2%} (round walls as polygons)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## From triangles to an exact solid\n",
    "\n",
    "`exact()` fits a plane, cylinder, cone, sphere or torus to every face and rebuilds the solid from\n",
    "them. The bore and the holes are round again, so the volume is that of the part, not of its\n",
    "polygon. The rebuilt solid is a CAD object like any other: here a cross hole is drilled through\n",
    "the boss."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solid = closed.exact()\n",
    "print(\n",
    "    f\"exact solid: valid {solid.is_valid}, faces {dict(Counter(face.kind for face in solid.faces))}\"\n",
    ")\n",
    "print(\n",
    "    f\"volume {solid.measure * 1e6:.5f} cm3, closed form {exact * 1e6:.5f} cm3, deviation {solid.measure / exact - 1:+.1e}\"\n",
    ")\n",
    "drilled = solid - Cylinder(\n",
    "    radius=0.003, length=0.06, origin=(0.06, -0.005, 0.035), axis=(0, 1, 0)\n",
    ").named(\"cross_hole\")\n",
    "print(\n",
    "    f\"with a cross hole of 6 mm: {(solid.measure - drilled.measure) * 1e9:.1f} mm3 removed\"\n",
    ")\n",
    "\n",
    "on_facets = FacetMesher(target_size=0.005).generate(closed)\n",
    "on_solid = TetrahedralMesher(target_size=0.005).generate(drilled)\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    raw, camera=view, title=\"Imported STL: faces found at sharp edges\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    on_solid,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Rebuilt solid with cross hole: {on_solid.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Both meshes against the closed-form volume; the mesh of the facet body inherits the polygonal\n",
    "bore, the mesh of the exact solid lies on the true cylinders."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for name, mesh, reference in (\n",
    "    (\"mesh of the facet body\", on_facets, exact),\n",
    "    (\"mesh of the exact solid with cross hole\", on_solid, drilled.measure),\n",
    "):\n",
    "    report = quality(mesh)\n",
    "    print(\n",
    "        f\"{name:40s} {mesh.cell_count:6d} cells, volume {report['size'].sum() * 1e6:.4f} cm3 \"\n",
    "        f\"against {reference * 1e6:.4f} cm3 ({report['size'].sum() / reference - 1:+.2%}), smallest shape {report['shape'].min():.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The repaired facet body with its open rims closed, the exact solid with its recognised faces,\n",
    "and the mesh of the facet body."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.geometry(closed, camera=view, title=\"Repaired and closed facet body\", ax=fig[0])\n",
    "plots.geometry(\n",
    "    solid,\n",
    "    selection={\n",
    "        \"planes\": solid.boundaries.plane,\n",
    "        \"cylinders\": solid.boundaries.cylinder,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Exact solid: recognised planes and cylinders\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    on_facets,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Mesh of the facet body: {on_facets.cell_count} tetrahedra\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Read the same part from OBJ, PLY or 3MF (`load` takes them all), give the unit with\n",
    "`load(\"part.stl\", unit=\"mm\")`, or fillet the edges of the rebuilt solid before meshing."
   ]
  }
 ]
}
