{
 "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": [
    "# Ship hull geometry\n",
    "\n",
    "A hull is drawn as a set of cross-sections, the stations, along its length; the shell runs\n",
    "smoothly through them. `Loft(sections=[(profile, position), ...])` does exactly that: with more\n",
    "than two sections the surface is a smooth interpolation through all of them.\n",
    "\n",
    "The Wigley hull of length $L$, beam $B$ and draft $T$ has the half-breadth\n",
    "\n",
    "$$y(x,z) = \\frac{B}{2}\\Big(1-\\big(\\tfrac{2x}{L}\\big)^2\\Big)\\Big(1-\\big(\\tfrac{z}{T}\\big)^2\\Big),\n",
    "  \\qquad -\\tfrac{L}{2}\\le x\\le \\tfrac{L}{2},\\ -T\\le z\\le 0 .$$\n",
    "\n",
    "At every station the side $y(z)$ is a parabola, which is exactly a quadratic Bézier curve: from\n",
    "the waterline point $(b,0)$ with control point $(b,-T/2)$ to the keel point $(0,-T)$, where $b$ is\n",
    "the half-breadth of the station. Above the waterline the sides rise vertically to the deck at a\n",
    "freeboard of $F$. The stem and the stern are cut at $|x| = 0.45L$, where the hull still has a\n",
    "tenth of its beam.\n",
    "\n",
    "**Reference.** Integrating the hull equation between the end stations $\\pm x_e$,\n",
    "\n",
    "$$\\nabla = \\frac{4}{3} B T \\Big(x_e - \\frac{4x_e^3}{3L^2}\\Big),\\qquad\n",
    "  A_{WP} = 2B\\Big(x_e - \\frac{4x_e^3}{3L^2}\\Big),\\qquad z_B = -\\frac{3}{8}T ,$$\n",
    "\n",
    "displacement volume, waterplane area and height of the centre of buoyancy (W. C. S. Wigley,\n",
    "*A comparison of experiment and calculated wave-profiles and wave-resistances for a form having\n",
    "parabolic waterlines*, Proc. Royal Society A 144 (1934) 144-159)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Path, PlanarRegion, Profile, Segment\n",
    "from onesim.cad.d3 import Box, Loft\n",
    "from onesim.meshing import OctreeMesher\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": [
    "## Stations and loft\n",
    "\n",
    "A model hull of 4 m length, 0.4 m beam, 0.25 m draft and 0.1 m freeboard, eleven stations from\n",
    "stern to stem. Each station is a closed profile in its own plane: deck line, side, keel, side."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hull_length, beam, draft, freeboard = 4.0, 0.4, 0.25, 0.1\n",
    "end = 0.45 * hull_length\n",
    "stations = np.linspace(-end, end, 11)\n",
    "half_breadth = lambda x: beam / 2 * (1 - (2 * x / hull_length) ** 2)\n",
    "sections = [\n",
    "    (\n",
    "        Profile(\n",
    "            Path(\n",
    "                (b, freeboard),\n",
    "                (\n",
    "                    Segment((b, 0.0)),\n",
    "                    Segment((0.0, -draft), control=((b, -draft / 2),)),\n",
    "                    Segment((-b, 0.0), control=((-b, -draft / 2),)),\n",
    "                    Segment((-b, freeboard)),\n",
    "                    Segment((b, freeboard)),\n",
    "                ),\n",
    "            )\n",
    "        ),\n",
    "        x,\n",
    "    )\n",
    "    for x, b in zip(stations, half_breadth(stations))\n",
    "]\n",
    "hull = Loft(sections=sections, axis=(1.0, 0.0, 0.0))\n",
    "print(\n",
    "    f\"hull: {len(hull.faces)} faces, bounding box {np.round(hull.bounding_box[0], 4)} to {np.round(hull.bounding_box[1], 4)} m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The underwater body\n",
    "\n",
    "The part of the hull below the waterline $z=0$ is the hull less a box above it. It is filled with\n",
    "tetrahedra cut from a grid of cubes of 30 mm at the shell, which grow to 60 mm inside; the grid\n",
    "follows a fine triangulation of the lofted shell (`faceted()`)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "underwater = hull - Box(\n",
    "    length=hull_length,\n",
    "    width=beam,\n",
    "    height=freeboard,\n",
    "    origin=(-hull_length / 2, -beam / 2, 0.0),\n",
    ")\n",
    "mesh = OctreeMesher(target_size=0.03, coarsening=1).generate(underwater.faceted())\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-50)\n",
    "fig = plots.figure(1, 2, size=(17, 6))\n",
    "plots.geometry(\n",
    "    hull,\n",
    "    selection={\n",
    "        \"shell\": hull.boundaries.side,\n",
    "        \"transom and stem\": hull.boundaries.bottom | hull.boundaries.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Wigley hull lofted through 11 stations\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Underwater body: {mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Displacement of the CAD body and of its mesh, the waterplane area (the section of the hull at\n",
    "the waterline) and the centre of buoyancy against the closed-form integrals; the station areas\n",
    "are exact, so Simpson's rule over them is a second, discrete check of the loft."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "integral = end - 4 * end**3 / (3 * hull_length**2)\n",
    "displacement = 4 / 3 * beam * draft * integral\n",
    "station_areas = (\n",
    "    np.array([profile.area for profile, _ in sections])\n",
    "    - 2 * half_breadth(stations) * freeboard\n",
    ")\n",
    "simpson = (\n",
    "    (stations[1] - stations[0])\n",
    "    / 3\n",
    "    * (\n",
    "        station_areas[0]\n",
    "        + 4 * station_areas[1:-1:2].sum()\n",
    "        + 2 * station_areas[2:-1:2].sum()\n",
    "        + station_areas[-1]\n",
    "    )\n",
    ")\n",
    "waterplane = hull.section((0, 0, 1), (0.0, 0.0, 0.0))\n",
    "print(\n",
    "    f\"displacement: CAD {underwater.measure * 1e3:.4f} l, mesh {quality(mesh)['size'].sum() * 1e3:.4f} l, Simpson over the stations \"\n",
    "    f\"{simpson * 1e3:.4f} l, closed form {displacement * 1e3:.4f} l ({underwater.measure / displacement - 1:+.2e})\"\n",
    ")\n",
    "print(\n",
    "    f\"waterplane area: CAD {waterplane.measure:.6f} m2, closed form {2 * beam * integral:.6f} m2 ({waterplane.measure / (2 * beam * integral) - 1:+.2e})\"\n",
    ")\n",
    "print(\n",
    "    f\"centre of buoyancy: x {underwater.center_of_mass[0]:+.5f} m (0 by symmetry), z {underwater.center_of_mass[2]:+.5f} m, \"\n",
    "    f\"closed form {-3 / 8 * draft:+.5f} m\"\n",
    ")\n",
    "print(\n",
    "    f\"block coefficient over the cut length: {underwater.measure / (2 * end * beam * draft):.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The waterplane with its two parabolic waterlines, the station areas along the hull against the\n",
    "closed form, and the midship station with its two parabolic sides."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(-end, end, 101)\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.geometry(waterplane, title=\"Waterplane: section at z = 0\", ax=fig[0])\n",
    "plots.line(\n",
    "    points={\"station profiles\": (stations, station_areas)},\n",
    "    reference={\"closed form 4/3 b(x) T\": (x, 4 / 3 * half_breadth(x) * draft)},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"underwater section area [m2]\",\n",
    "    title=\"Sectional area curve\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.geometry(\n",
    "    PlanarRegion(profile=sections[5][0]),\n",
    "    title=\"Midship station: deck line, sides, keel\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Mesh the water around the hull (`Box(...) - underwater`) for a flow model, thicken the shell\n",
    "with `hull.surface(hull.boundaries.side).thickened(0.004)` for a structural model, or change the\n",
    "stations to the lines of a real ship."
   ]
  }
 ]
}
