"""DfAM Practitioner Program, Lab 3 - multi-objective build orientation (starter code).

Run:  python T3_orientation.py            (uses a built-in L-bracket)
      python T3_orientation.py part.stl   (uses your own binary STL)

For a grid of orientations the script computes three objectives from the facets:
  support area, area-weighted cusp height and build height, then lists the Pareto-optimal orientations.
"""
import struct, sys
import numpy as np


def l_bracket(a=60.0, b=40.0, t=10.0, width=80.0):
    """Triangles (n x 3 x 3) of an L-shaped bracket with an inclined gusset face, extruded by 'width'."""
    poly = np.array([[0, 0], [a, 0], [a, t], [t + 15, t], [t, b], [0, b]], float)   # counter-clockwise
    lo = np.c_[poly, np.zeros(6)]; hi = np.c_[poly, np.full(6, width)]
    tris = []
    for i in range(6):
        j = (i + 1) % 6
        tris += [[lo[i], lo[j], hi[j]], [lo[i], hi[j], hi[i]]]                       # side faces, outward normals
    caps = [(0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 4, 5)]
    for i, j, k in caps:
        tris.append([hi[i], hi[j], hi[k]])                                           # top cap, +z
        tris.append([lo[i], lo[k], lo[j]])                                           # bottom cap, -z
    return np.array(tris)


def read_binary_stl(path):
    with open(path, "rb") as f:
        f.read(80); n = struct.unpack("<I", f.read(4))[0]
        tris = np.zeros((n, 3, 3))
        for i in range(n):
            rec = struct.unpack("<12fH", f.read(50))
            tris[i] = np.array(rec[3:12]).reshape(3, 3)
    return tris


def rotation(ax_deg, ay_deg):
    ax, ay = np.radians([ax_deg, ay_deg])
    Rx = np.array([[1, 0, 0], [0, np.cos(ax), -np.sin(ax)], [0, np.sin(ax), np.cos(ax)]])
    Ry = np.array([[np.cos(ay), 0, np.sin(ay)], [0, 1, 0], [-np.sin(ay), 0, np.cos(ay)]])
    return Ry @ Rx


def objectives(tris, R, layer=0.1, crit_deg=45.0):
    """Support area (mm2), mean cusp height (mm) and build height (mm) for rotation matrix R."""
    T = tris @ R.T
    e1, e2 = T[:, 1] - T[:, 0], T[:, 2] - T[:, 0]
    cr = np.cross(e1, e2)
    area = 0.5 * np.linalg.norm(cr, axis=1)
    nz = cr[:, 2] / (2 * area)
    zmin = T[:, :, 2].min()
    on_plate = (T[:, :, 2].max(axis=1) - zmin) < 1e-6           # faces resting on the build plate
    needs = (-nz > np.cos(np.radians(crit_deg))) & ~on_plate
    support_area = area[needs].sum()
    inclined = np.abs(nz) < 0.999                               # horizontal faces have no staircase
    cusp = (area[inclined] * layer * np.abs(nz[inclined])).sum() / area[inclined].sum()
    height = T[:, :, 2].max() - zmin
    return support_area, cusp, height


def pareto(F):
    """Indices of non-dominated rows of F (all objectives minimised)."""
    keep = []
    for i in range(len(F)):
        dom = np.any(np.all(F <= F[i] + 1e-12, axis=1) & np.any(F < F[i] - 1e-12, axis=1))
        if not dom:
            keep.append(i)
    return keep


if __name__ == "__main__":
    tris = read_binary_stl(sys.argv[1]) if len(sys.argv) > 1 else l_bracket()
    angles = [(ax, ay) for ax in range(0, 360, 30) for ay in range(0, 360, 30)]
    F = np.array([objectives(tris, rotation(ax, ay)) for ax, ay in angles])
    Fr = np.round(F, 4)
    _, first = np.unique(Fr, axis=0, return_index=True)        # many angle pairs give the same orientation
    idx = sorted(first)
    front = [idx[i] for i in pareto(Fr[idx])]
    print("orientations evaluated: %d   distinct results: %d   Pareto-optimal: %d" % (len(angles), len(idx), len(front)))
    print("%8s %8s %14s %12s %10s" % ("rot-x", "rot-y", "support mm2", "cusp mm", "height mm"))
    for i in sorted(front, key=lambda k: F[k, 0]):
        print("%8d %8d %14.1f %12.4f %10.1f" % (angles[i][0], angles[i][1], F[i, 0], F[i, 1], F[i, 2]))
    w = np.array([0.4, 0.3, 0.3])                               # weighted-sum choice among the Pareto set
    Fn = F[front] / np.maximum(F[front].max(axis=0), 1e-12)
    best = front[int(np.argmin(Fn @ w))]
    print("weighted-sum choice (0.4, 0.3, 0.3): rot-x %d, rot-y %d" % angles[best])
