TRELLIS.2 icon indicating copy to clipboard operation
TRELLIS.2 copied to clipboard

Trellis generating duplicate inner mesh walls

Open firesightstudios opened this issue 8 months ago • 1 comments

Most generations add an entire inner shell of the mesh.

I was able to create a function in blender that can 99% remove the inner shell but results in some random issues

Image Image

Stats on Model post Trellis2 Generation at 1024 Resolution and 2048 Texture Size

POST TRELLIS 2 Generation:

Image

Post Healing Script - Removing Inner Walls:

Image

Blender 5.1.0 Base Blender Script used:

import bpy
import bmesh
from mathutils.bvhtree import BVHTree

class GeometryAlgorithm:
    Mathematical targeted healing of AI mesh anomalies.

    @staticmethod
    def heal_geometry(obj):
        if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
            bpy.ops.object.mode_set(mode='OBJECT')

        bpy.ops.object.select_all(action='DESELECT')
        obj.hide_set(False)
        obj.select_set(True)
        bpy.context.view_layer.objects.active = obj

        # 1. Apply Transforms (Crucial for Mixamo auto-rigger)
        bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
        bpy.ops.mesh.customdata_custom_splitnormals_clear()

        bpy.ops.object.mode_set(mode='EDIT')


        # ==========================================
        # --- PASS 1: LINE-OF-SIGHT SEED & SPREAD ---
        # ==========================================
        bm = bmesh.from_edit_mesh(obj.data)
        bm.faces.ensure_lookup_table()
        
        # Deselect everything to prepare for seeding
        for f in bm.faces:
            f.select = False

        verts_co = [v.co for v in bm.verts]
        faces_indices = [[v.index for v in f.verts] for f in bm.faces]
        tree = BVHTree.FromPolygons(verts_co, faces_indices)

        seed_count = 0
        
        # 1. Raycast Seed: If a face's normal points directly at the sky, it's 100% outer shell.
        for f in bm.faces:
            # Nudge the origin slightly to prevent hitting the face itself
            origin = f.calc_center_median() + (f.normal * 0.0001)
            loc, _, _, _ = tree.ray_cast(origin, f.normal)
            
            if loc is None:
                f.select = True
                seed_count += 1
                
        # 2. Extreme Bounds Seed: An absolute guarantee to find the outer limits of the mesh
        if bm.verts:
            extremes = [
                min(bm.verts, key=lambda v: v.co.z), max(bm.verts, key=lambda v: v.co.z),
                min(bm.verts, key=lambda v: v.co.x), max(bm.verts, key=lambda v: v.co.x),
                min(bm.verts, key=lambda v: v.co.y), max(bm.verts, key=lambda v: v.co.y)
            ]
            for v in extremes:
                for f in v.link_faces:
                    if not f.select:
                        f.select = True
                        seed_count += 1

        bmesh.update_edit_mesh(obj.data)

        if seed_count > 0:
            # 3. The Spread: Select everything connected to the outer shell seeds!
            # This perfectly protects backpacks, deep armpits, and tight crevices.
            bpy.ops.mesh.select_linked()
            
            # 4. The Purge: Delete everything that is detached/inside (The Phantom Inner Wall)
            bpy.ops.mesh.select_all(action='INVERT')
            bpy.ops.mesh.delete(type='FACE')


        # ==========================================
        # --- PASS 2: SURGICAL BMESH STRAY EDGE SNIP ---
        # ==========================================
        # Re-initialize bmesh after the face deletion
        bm = bmesh.from_edit_mesh(obj.data)
        for _ in range(2):
            bm.edges.ensure_lookup_table()
            bm.verts.ensure_lookup_table()
            
            stray_edges = [e for e in bm.edges if len(e.link_faces) == 0]
            if stray_edges:
                bmesh.ops.delete(bm, geom=stray_edges, context='EDGES')

            stray_verts = [v for v in bm.verts if len(v.link_faces) == 0]
            if stray_verts:
                bmesh.ops.delete(bm, geom=stray_verts, context='VERTS')
                
        bmesh.update_edit_mesh(obj.data)


        # ==========================================
        # --- PASS 3: SAFE MACRO GEOMETRY HEALING ---
        # ==========================================
        for _ in range(3):
            bpy.ops.mesh.select_all(action='SELECT')
            
            # Since the phantom inner shell was vaporized, it is now 
            # 100% safe to run the vertex merge without the walls pinching together!
            bpy.ops.mesh.remove_doubles(threshold=0.0005)

            # Blender's native interior face selector handles any remaining micro-webbing
            bpy.ops.mesh.select_all(action='DESELECT')
            bpy.ops.mesh.select_interior_faces()
            bpy.ops.mesh.delete(type='FACE')

            # Instantly bridges any holes shut left by the purge.
            bpy.ops.mesh.select_all(action='SELECT')
            bpy.ops.mesh.fill_holes(sides=100)


        # ==========================================
        # --- PASS 4: DEGENERATE FACE CLEANUP ---
        # ==========================================
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.delete_loose()
        
        # Safely eliminates the 88k micro-faces AI tools generate
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.dissolve_degenerate(threshold=0.002)

        # Force all normals outward to fix Mixamo voxelizer holes
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.normals_make_consistent(inside=False)


        # ==========================================
        # --- CLEANUP ---
        # ==========================================
        try:
            bpy.ops.object.mode_set(mode='SCULPT')
            bpy.ops.paint.mask_clear()
        except Exception:
            pass

        bpy.ops.object.mode_set(mode='OBJECT')

firesightstudios avatar Mar 22 '26 23:03 firesightstudios

Adding another approach to the inner-shell problem, for anyone who hits it: the connectivity-based fix posted above (select outer shell → select_linked → invert → delete) doesn't fully work when the inner shell is welded to the outer shell through the mesh's own default holes — since they're one connected island, select_linked grabs the inner wall right along with the outer one and nothing gets removed.

This variant instead tests each face by visibility, not connectivity: it casts ~26 rays outward from every face center in a roughly even spherical distribution. If none of the rays escape to open space, the face is fully enclosed by other geometry and gets deleted — regardless of whether it's topologically connected to the outer shell, and regardless of normal direction. In testing this correctly strips buried inner shells that the connectivity method leaves behind.

It's slower (O(faces × rays), so a few minutes on a dense mesh) and it's a general "remove enclosed geometry" technique rather than anything Trellis-specific, but it's been reliable where the simpler fix wasn't.

"""
Trellis - Inner Shell Remover (visibility-based)
=================================================
Removes a duplicate INNER SHELL baked into a mesh by narrow-band UDF +
dual-contouring remesh steps (e.g. Trellis 2 / pixal3d), including cases
where the inner shell is welded to the outer shell through the mesh's own
holes (so a connectivity-based select_linked fix can't separate them).

HOW IT WORKS
Each face is tested by casting several rays outward from its center in a
roughly even spherical distribution. If at least one ray escapes to open
space, the face is on the outside -> keep. If every ray hits other
geometry, the face is fully enclosed -> delete. This ignores mesh
connectivity and normal direction entirely, so it still works when the
inner shell is topologically fused to the outer one.

USAGE
1. Back up your mesh first (destructive).
2. 2. Select the mesh object in Object Mode.
3. 3. Scripting tab -> Text -> Open -> this file -> Run Script.
4. 4. Toggle System Console (Window menu) to watch progress on large meshes.
5. """
import bpy
import bmesh
import math
import time
from mathutils import Vector
from mathutils.bvhtree import BVHTree

# ------------------------- settings -------------------------
NUM_RAYS = 26          # directions sampled on a sphere per face
KEEP_THRESHOLD = 1     # faces with >= this many escaping rays are kept
EPS = 1e-4             # offset so rays don't hit their own face
DO_CLEANUP = True      # stray-edge snip, delete loose, fix normals afterwards
FILL_HOLES = False     # fill holes after deletion (off by default - the
                       # original holes bridge inner+outer walls; filling
                       # them can distort the result, check first)
# ------------------------------------------------------------


def _sphere_directions(n):
    """Evenly distributed directions on a sphere (Fibonacci spiral)."""
    dirs = []
    golden = math.pi * (3.0 - math.sqrt(5.0))
    for i in range(n):
        y = 1.0 - (i / float(n - 1)) * 2.0
        radius = math.sqrt(max(0.0, 1.0 - y * y))
        theta = golden * i
        dirs.append(Vector((math.cos(theta) * radius, y, math.sin(theta) * radius)))
    return dirs


def remove_enclosed_faces(obj):
    t0 = time.time()

    if bpy.context.active_object and bpy.context.active_object.mode != 'OBJECT':
        bpy.ops.object.mode_set(mode='OBJECT')

    bpy.ops.object.select_all(action='DESELECT')
    obj.hide_set(False)
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj

    bpy.ops.object.mode_set(mode='EDIT')
    bm = bmesh.from_edit_mesh(obj.data)
    bm.faces.ensure_lookup_table()

    n_faces = len(bm.faces)
    print(f"[V2] {obj.name}: {n_faces} faces. Building BVH...")

    verts_co = [v.co.copy() for v in bm.verts]
    faces_idx = [[v.index for v in f.verts] for f in bm.faces]
    tree = BVHTree.FromPolygons(verts_co, faces_idx)

    directions = _sphere_directions(NUM_RAYS)

    print(f"[V2] Casting {NUM_RAYS} rays per face...")
    kill = []
    report_step = max(1, n_faces // 20)

    for fi, f in enumerate(bm.faces):
        center = f.calc_center_median()
        escapes = 0
        for d in directions:
            origin = center + d * EPS
            loc, _, _, _ = tree.ray_cast(origin, d)
            if loc is None:
                escapes += 1
                if escapes >= KEEP_THRESHOLD:
                    break
        if escapes < KEEP_THRESHOLD:
            kill.append(f)

        if fi % report_step == 0:
            pct = 100.0 * fi / n_faces
            print(f"[V2]   {pct:5.1f}%  ({fi}/{n_faces})  buried so far: {len(kill)}")

    print(f"[V2] Deleting {len(kill)} buried faces ({100.0*len(kill)/max(1,n_faces):.1f}% of mesh)...")
    bmesh.ops.delete(bm, geom=kill, context='FACES')

    if DO_CLEANUP:
        for _ in range(2):
            bm.edges.ensure_lookup_table()
            bm.verts.ensure_lookup_table()
            stray_e = [e for e in bm.edges if len(e.link_faces) == 0]
            if stray_e:
                bmesh.ops.delete(bm, geom=stray_e, context='EDGES')
            stray_v = [v for v in bm.verts if len(v.link_faces) == 0]
            if stray_v:
                bmesh.ops.delete(bm, geom=stray_v, context='VERTS')

    bmesh.update_edit_mesh(obj.data)

    if DO_CLEANUP:
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.delete_loose()
        if FILL_HOLES:
            bpy.ops.mesh.select_all(action='SELECT')
            bpy.ops.mesh.fill_holes(sides=100)
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.normals_make_consistent(inside=False)

    bpy.ops.object.mode_set(mode='OBJECT')
    print(f"[V2] Done in {time.time() - t0:.1f}s. "
          f"Faces: {n_faces} -> {len(obj.data.polygons)}")


if __name__ == "__main__":
    target = bpy.context.active_object
    if target is None or target.type != 'MESH':
        raise RuntimeError("Select a MESH object before running this script.")
    remove_enclosed_faces(target)

Tuning: bump NUM_RAYS up if you're seeing false positives in deep crevices (armpits, folds), and set FILL_HOLES = True if you want the original Trellis holes patched afterward instead of left open.

ectomia avatar Jul 23 '26 20:07 ectomia