#! python 3
# -*- coding: utf-8 -*-
"""
SelDupAnyType
=============
Selects objects that occupy the same space, regardless of object type.

Unlike the built-in SelDup, which only matches objects of the same geometry
type, this command compares a type-independent geometric fingerprint, so an
extrusion and a mesh that occupy the same volume are reported as duplicates.

Fingerprint:
    * bounding box (used only to prefilter candidates, never to decide a
      match -- see the note in matches())
    * volume / area / length, depending on the object's dimensionality
    * centroid
    * moments of inertia + product moments, taken about the centroid
      (so they describe shape only and stay stable wherever the object
      sits in the model)

Two objects match when every one of those values agrees within tolerance.
The centroid pins the position down, while the measures and moments pin the
shape down, so a copy of the same shape sitting somewhere else -- or a
rotated copy sharing the same bounding box -- is not a false positive.

Options
-------
Tolerance   Distance tolerance for centroid comparison. Defaults to the
            model absolute tolerance.
Precision   Relative tolerance (%) for volume/area/length and moments.
            Raise this when comparing a coarse mesh against a smooth
            NURBS object; lower it to demand near-exact matches.
Scope       All objects in the document, or only the current selection.
Include     Solids only, or every object (open surfaces, curves, points).
Mode        SelectAll   - select every member of each duplicate set
            SelectExtras- leave one object per set unselected, so the
                          selection can be deleted directly

Author: McNeel Korea
"""

import System
import Rhino
import Rhino.Input.Custom as ric
from Rhino.Geometry import (
    AreaMassProperties, BoundingBox, Brep, Extrusion, LengthMassProperties,
    Point3d, RTree, SubD, SubDToBrepOptions, Surface, VolumeMassProperties,
    Vector3d, Curve, Point, Mesh,
)

# kind ranks -- objects of different kinds are never compared
KIND_POINT, KIND_CURVE, KIND_AREA, KIND_VOLUME = 0, 1, 2, 3

_defaults = {
    "tol": None,        # None -> model absolute tolerance
    "precision": 1.0,   # percent
    "scope_all": True,
    "solids_only": True,
    "select_all": True,
}


# --------------------------------------------------------------------------
# geometry helpers
# --------------------------------------------------------------------------
def to_comparable(geo):
    """Convert geometry to a form the mass property calculators accept."""
    if isinstance(geo, Extrusion):
        brep = geo.ToBrep(True)
        return brep if brep else geo
    if isinstance(geo, SubD):
        try:
            brep = geo.ToBrep(SubDToBrepOptions.DefaultPacked)
            if brep:
                return brep
        except Exception:
            pass
        try:
            return Mesh.CreateFromSubD(geo, 3)
        except Exception:
            return geo
    if isinstance(geo, Surface) and not isinstance(geo, Brep):
        brep = Brep.CreateFromSurface(geo)
        return brep if brep else geo
    return geo


def is_solid(geo):
    val = getattr(geo, "IsSolid", None)
    if val is None:
        val = getattr(geo, "IsClosed", None)
    return bool(val)


class Signature(object):
    """Type-independent geometric fingerprint of one object."""

    __slots__ = ("oid", "kind", "bbox", "measure", "area", "centroid",
                 "inertia", "product", "scale", "diag")

    def __init__(self, oid, kind, bbox, measure, area, centroid,
                 inertia, product):
        self.oid = oid
        self.kind = kind
        self.bbox = bbox
        self.measure = measure
        self.area = area
        self.centroid = centroid
        self.inertia = inertia
        self.product = product
        diag = bbox.Diagonal.Length
        self.diag = diag
        # magnitude used to scale relative comparisons of the moments
        base = abs(measure) if measure else 1.0
        self.scale = max(base * diag * diag, 1e-12)


def build_signature(rhobj, solids_only):
    """Return a Signature for a Rhino object, or None if it cannot be used."""
    raw = rhobj.Geometry
    if raw is None:
        return None
    geo = to_comparable(raw)

    bbox = geo.GetBoundingBox(True)
    fast = geo.GetBoundingBox(False)
    if fast.IsValid:
        # Union with the fast box. The accurate box of a Brep whose faces are
        # RevSurfaces (spheres, tori) can come back far too small once the
        # object lives in a document, and this box is a prefilter only.
        bbox.Union(fast)
    if not bbox.IsValid:
        return None

    # --- volumetric ------------------------------------------------------
    if is_solid(geo):
        try:
            vmp = VolumeMassProperties.Compute(geo, True, True, True, True)
        except Exception:
            vmp = None
        if vmp and vmp.Volume > 0.0:
            area = None
            try:
                amp = AreaMassProperties.Compute(geo)
                if amp:
                    area = amp.Area
            except Exception:
                pass
            return Signature(
                rhobj.Id, KIND_VOLUME, bbox, vmp.Volume, area, vmp.Centroid,
                vmp.CentroidCoordinatesMomentsOfInertia,
                vmp.CentroidCoordinatesProductMoments)

    if solids_only:
        return None

    # --- area ------------------------------------------------------------
    if isinstance(geo, (Brep, Mesh, Surface)):
        try:
            amp = AreaMassProperties.Compute(geo, True, True, True, True)
        except Exception:
            amp = None
        if amp and amp.Area > 0.0:
            return Signature(
                rhobj.Id, KIND_AREA, bbox, amp.Area, amp.Area, amp.Centroid,
                amp.CentroidCoordinatesMomentsOfInertia,
                amp.CentroidCoordinatesProductMoments)

    # --- length ----------------------------------------------------------
    if isinstance(geo, Curve):
        try:
            lmp = LengthMassProperties.Compute(geo, True, True, True, True)
        except Exception:
            lmp = None
        if lmp and lmp.Length > 0.0:
            return Signature(
                rhobj.Id, KIND_CURVE, bbox, lmp.Length, None, lmp.Centroid,
                lmp.CentroidCoordinatesMomentsOfInertia,
                lmp.CentroidCoordinatesProductMoments)

    # --- point -----------------------------------------------------------
    if isinstance(geo, Point):
        return Signature(rhobj.Id, KIND_POINT, bbox, 0.0, None, geo.Location,
                         Vector3d.Zero, Vector3d.Zero)

    return None


# --------------------------------------------------------------------------
# comparison
# --------------------------------------------------------------------------
def _near(a, b, rel, floor):
    return abs(a - b) <= max(abs(a), abs(b)) * rel + floor


def _near_vector(a, b, rel, scale):
    # relative per component, plus a small absolute floor so components that
    # sit near zero (product moments of symmetric shapes) do not dominate
    floor = scale * rel * 0.01
    for x, y in ((a.X, b.X), (a.Y, b.Y), (a.Z, b.Z)):
        if abs(x - y) > max(abs(x), abs(y)) * rel + floor:
            return False
    return True


def matches(a, b, tol, rel):
    if a.kind != b.kind:
        return False
    # Bounding boxes deliberately take no part in the decision: a mesh that
    # approximates a NURBS object has a slightly smaller box, and the accurate
    # box is not reliable for every surface type. Position is pinned down by
    # the centroid instead, and shape by the measures and moments below.
    limit = max(tol, max(a.diag, b.diag) * rel * 0.1)
    if a.centroid.DistanceTo(b.centroid) > limit:
        return False
    if not _near(a.measure, b.measure, rel, 1e-12):
        return False
    if a.area is not None and b.area is not None:
        if not _near(a.area, b.area, rel, 1e-12):
            return False
    if a.kind != KIND_POINT:
        scale = max(a.scale, b.scale)
        if not _near_vector(a.inertia, b.inertia, rel, scale):
            return False
        if not _near_vector(a.product, b.product, rel, scale):
            return False
    return True


class UnionFind(object):
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, i):
        while self.parent[i] != i:
            self.parent[i] = self.parent[self.parent[i]]
            i = self.parent[i]
        return i

    def union(self, i, j):
        ri, rj = self.find(i), self.find(j)
        if ri != rj:
            self.parent[rj] = ri


def find_groups(signatures, tol, rel):
    """Return a list of groups; each group is a list of indices, len >= 2."""
    count = len(signatures)
    if count < 2:
        return []

    tree = RTree()
    for i, sig in enumerate(signatures):
        tree.Insert(sig.bbox, i)

    uf = UnionFind(count)
    for i, sig in enumerate(signatures):
        box = BoundingBox(sig.bbox.Min, sig.bbox.Max)
        box.Inflate(tol + sig.diag * rel)
        hits = []

        def collect(sender, args, bucket=hits):
            bucket.append(args.Id)

        tree.Search(box, collect)
        for j in hits:
            if j <= i:
                continue
            if uf.find(i) == uf.find(j):
                continue
            if matches(sig, signatures[j], tol, rel):
                uf.union(i, j)

    buckets = {}
    for i in range(count):
        buckets.setdefault(uf.find(i), []).append(i)
    return [g for g in buckets.values() if len(g) > 1]


def collect_objects(doc, scope_all):
    settings = Rhino.DocObjects.ObjectEnumeratorSettings()
    settings.NormalObjects = True
    settings.LockedObjects = False
    settings.HiddenObjects = False
    settings.IncludeLights = False
    settings.IncludeGrips = False
    settings.DeletedObjects = False
    if not scope_all:
        settings.SelectedObjectsFilter = True
    return list(doc.Objects.GetObjectList(settings))


def run(doc, tol, precision, scope_all, solids_only, select_all, verbose=True):
    """Core routine. Returns (group_count, selected_count)."""
    rel = precision / 100.0
    objects = collect_objects(doc, scope_all)

    signatures = []
    for obj in objects:
        sig = build_signature(obj, solids_only)
        if sig:
            signatures.append(sig)

    groups = find_groups(signatures, tol, rel)

    doc.Objects.UnselectAll()
    selected = 0
    for group in groups:
        members = group if select_all else group[1:]
        for idx in members:
            rhobj = doc.Objects.Find(signatures[idx].oid)
            if rhobj:
                rhobj.Select(True)
                selected += 1
    doc.Views.Redraw()

    if verbose:
        if not groups:
            Rhino.RhinoApp.WriteLine(
                "SelDupAnyType: no overlapping objects found "
                "({0} objects tested).".format(len(signatures)))
        else:
            Rhino.RhinoApp.WriteLine(
                "SelDupAnyType: {0} overlapping set(s) found, "
                "{1} object(s) selected.".format(len(groups), selected))
            for n, group in enumerate(groups, 1):
                kinds = []
                for idx in group:
                    rhobj = doc.Objects.Find(signatures[idx].oid)
                    if rhobj:
                        kinds.append(rhobj.Geometry.GetType().Name)
                Rhino.RhinoApp.WriteLine(
                    "  set {0}: {1}".format(n, " + ".join(kinds)))
    return len(groups), selected


# --------------------------------------------------------------------------
# command interface
# --------------------------------------------------------------------------
def prompt_options(doc):
    tol = _defaults["tol"]
    if tol is None:
        tol = doc.ModelAbsoluteTolerance

    opt_tol = ric.OptionDouble(tol, True, 0.0)
    opt_prec = ric.OptionDouble(_defaults["precision"], True, 0.0)

    scope_idx = 0 if _defaults["scope_all"] else 1
    include_idx = 0 if _defaults["solids_only"] else 1
    mode_idx = 0 if _defaults["select_all"] else 1

    go = ric.GetOption()
    go.SetCommandPrompt("Find objects occupying the same space")
    go.AcceptNothing(True)

    while True:
        go.ClearCommandOptions()
        go.AddOptionDouble("Tolerance", opt_tol)
        go.AddOptionDouble("Precision", opt_prec)
        i_scope = go.AddOptionList("Scope", ["All", "Selected"], scope_idx)
        i_incl = go.AddOptionList("Include", ["SolidsOnly", "Everything"],
                                  include_idx)
        i_mode = go.AddOptionList("Mode", ["SelectAll", "SelectExtras"],
                                  mode_idx)

        res = go.Get()
        if res == Rhino.Input.GetResult.Cancel:
            return None
        if res == Rhino.Input.GetResult.Option:
            idx = go.OptionIndex()
            if idx == i_scope:
                scope_idx = go.Option().CurrentListOptionIndex
            elif idx == i_incl:
                include_idx = go.Option().CurrentListOptionIndex
            elif idx == i_mode:
                mode_idx = go.Option().CurrentListOptionIndex
            continue
        break

    _defaults["tol"] = opt_tol.CurrentValue
    _defaults["precision"] = opt_prec.CurrentValue
    _defaults["scope_all"] = (scope_idx == 0)
    _defaults["solids_only"] = (include_idx == 0)
    _defaults["select_all"] = (mode_idx == 0)

    return (opt_tol.CurrentValue, opt_prec.CurrentValue,
            scope_idx == 0, include_idx == 0, mode_idx == 0)


def main():
    doc = Rhino.RhinoDoc.ActiveDoc
    if doc is None:
        return
    settings = prompt_options(doc)
    if settings is None:
        return
    tol, precision, scope_all, solids_only, select_all = settings
    run(doc, tol, precision, scope_all, solids_only, select_all)


if __name__ == "__main__":
    main()
