Sub topic 14
Auditing a Mesh with a Short Python Script
This chapter assumes you can switch between Object Mode and Edit Mode and run a script from Blender's Text Editor. It also assumes you know the topology terms from earlier chapters: quads, triangles, n-gons, valence and poles. No Python beyond loops and comprehensions is needed.
Why audit with a script
You can find most topology problems by eye. Turn on Statistics in the viewport overlays, select by face sides, and look at the wireframe. This gets slow on a dense mesh, or when you inherit a model and want to know quickly whether it is safe to subdivide.
A script gives you a repeatable check. It counts the same things the same way every time, and it can select the offending elements so you can fix them. It does not replace judgment. A pole in a flat area is fine, and a pole on a curved shoulder is not. The script tells you where poles are, and you decide which ones matter.
What the script reads: the base mesh
An audit reads the base mesh, the cage you edit, not the smoothed result. The Subdivision Surface modifier runs after your topology, and bmesh.from_edit_mesh gives you the vertices, edges and faces as they sit in Edit Mode. That is what you want, because a pole in the base mesh is what causes pinching in the subdivided result.
The script uses the bmesh module. A BMesh is an editable copy of mesh data with direct access to each element's neighbors. from_edit_mesh returns a view of the live Edit Mode mesh, so the script must run while the object is in Edit Mode.
The basic counting script
This is the script from the plan. Run it in Edit Mode on the active mesh object:
import bpy
import bmesh
obj = bpy.context.edit_object
bm = bmesh.from_edit_mesh(obj.data)
tris = sum(1 for f in bm.faces if len(f.verts) == 3)
ngons = sum(1 for f in bm.faces if len(f.verts) > 4)
# valence 3 is an E-pole; valence 5 or more is an N-pole
epoles = sum(1 for v in bm.verts if len(v.link_edges) == 3)
npoles = sum(1 for v in bm.verts if len(v.link_edges) >= 5)
print(f"Triangles: {tris}, n-gons: {ngons}, E-poles: {epoles}, N-poles: {npoles}")Each line is a generator expression that counts elements matching a test:
f.vertslists the vertices of a face, so its length is the number of sides. Three sides is a triangle. More than four is an n-gon. Four is a quad, which needs no count because it is the normal case.v.link_edgeslists the edges that meet at a vertex, so its length is the vertex's valence.- Valence 3 is an E-pole. Valence 5 or more is an N-pole. Valence 4 is the regular case in a quad grid and is not counted.
The output goes to the system console. On Windows, open it with Window > Toggle System Console. On other platforms, start Blender from a terminal. To see the numbers in Blender itself, open Scripting in the workspace tabs and use the Python console, or report the result as a message (see below).
Try it on a known mesh
Add a default cube and enter Edit Mode. The result should be:
Triangles: 0, n-gons: 0, E-poles: 8, N-poles: 0All eight corners have valence 3. This shows an important point: a bare count is not a verdict. A cube is a perfectly clean mesh, and it reports eight E-poles. Poles at the corners of a cube are expected, because that is how a closed box is built from quads. You have to interpret the count in context.
Making the audit trustworthy
The short script works, but a few edge cases make the numbers misleading. Here is a more careful version that handles them.
import bpy
import bmesh
def audit_mesh(bm):
"""Return lists of offending elements in a BMesh."""
bm.verts.ensure_lookup_table()
tris = [f for f in bm.faces if len(f.verts) == 3]
ngons = [f for f in bm.faces if len(f.verts) > 4]
epoles = []
npoles = []
for v in bm.verts:
if v.is_boundary or not v.is_manifold:
continue # open edges and odd geometry change what valence means
valence = len(v.link_edges)
if valence == 3:
epoles.append(v)
elif valence >= 5:
npoles.append(v)
open_edges = [e for e in bm.edges if e.is_boundary]
return tris, ngons, epoles, npoles, open_edges
obj = bpy.context.edit_object
if obj is None or obj.type != 'MESH':
raise RuntimeError("Enter Edit Mode on a mesh object first.")
bm = bmesh.from_edit_mesh(obj.data)
tris, ngons, epoles, npoles, open_edges = audit_mesh(bm)
print(f"Object: {obj.name}")
print(f" Triangles: {len(tris)}")
print(f" N-gons: {len(ngons)}")
print(f" E-poles: {len(epoles)}")
print(f" N-poles: {len(npoles)}")
print(f" Open edges: {len(open_edges)}")Three changes matter here.
- Boundary vertices are skipped. On an open mesh, such as a plane, a vertex on the border has fewer neighbors only because the surface ends there. A regular border vertex of a plane has valence 3, and counting it would flood the E-pole total with false positives. The
is_boundarycheck removes them. - Non-manifold vertices are skipped. These sit where geometry is pinched or shared oddly, such as two surfaces touching at one point. Valence means little there. Check them separately with Select > Select All by Trait > Non Manifold.
- The function returns the elements, not just counts. With the actual vertices and faces in hand, you can select them, which is the next step.
Guarding against bad context
bpy.context.edit_object is None when you are in Object Mode, and the script raises a clear error instead of an obscure AttributeError. The obj.type check keeps you from running it on a curve or a light.
Selecting what the audit finds
A number tells you something is wrong. A selection shows you where. Add this to the end of the script to highlight the problem elements:
# Continue from the previous script: tris, ngons, npoles, bm and obj exist.
bpy.ops.mesh.select_mode(type='VERT')
bpy.ops.mesh.select_all(action='DESELECT')
for v in npoles:
v.select_set(True)
bm.select_flush_mode()
bmesh.update_edit_mesh(obj.data)select_set(True) marks each vertex as selected in the BMesh. select_flush_mode() updates the selection state of connected edges and faces to match. bmesh.update_edit_mesh pushes the change back so the viewport redraws. Without that last call, the selection can exist in the data but not appear on screen.
To select n-gons instead, switch to face select mode (type='FACE') and call f.select_set(True) for each face in ngons.
Reading the results
The workflow below shows how the counts lead to decisions:
Use these rules of thumb when interpreting the numbers:
| Result | Usually means | Action |
|---|---|---|
| N-gons greater than 0 | Faces that subdivide unpredictably | Split into quads unless the face is flat and never smoothed |
| Triangles greater than 0 | May be harmless | Check whether they sit on curved surface or in flat, hidden areas |
| Few E-poles | Normal at corners and where loops change direction | Check location, not count |
| N-poles greater than 0 | Pinching risk | Move to flat or low-curvature areas |
| Open edges greater than 0 | Holes or intentional borders | Confirm each is intended |
Counts alone do not distinguish a clean mesh from a problem mesh. A sphere built from quads and a few poles at the top and bottom is clean. A mesh with the same pole count placed on a cheekbone is not. Always follow a count with the selection step and look at where the elements sit.
Reporting results inside Blender
Reading the system console is awkward. Operators can show a message in the status bar instead. Wrap the script as a function and call report from an operator, or use a simple popup. This snippet shows a popup without defining an operator:
import bpy
def show_message(title, lines):
def draw(self, context):
for line in lines:
self.layout.label(text=line)
bpy.context.window_manager.popup_menu(draw, title=title, icon='INFO')
show_message("Topology audit", ["Triangles: 4", "N-gons: 0", "N-poles: 2"])In a real script, build the lines list from the counts. The values above are placeholders to show the call. Keep the audit logic separate from the display, so you can reuse it from the console or from an add-on later.
Limits of a script audit
- It does not judge edge flow. The script cannot tell whether loops follow the form. That remains a visual task.
- It reads one mesh state. If modifiers such as Mirror come before Subdivision Surface, the base mesh shows only half the model. Poles on the mirror plane look different than they do on the merged result. Audit after you apply the Mirror modifier on a copy, or check the center line manually.
- It runs on the current selection mode and state. Hidden geometry is still counted by
bm.verts, but you cannot see it. Reveal hidden elements with Alt+H before auditing. - Valence thresholds are conventions. Some artists treat valence 3 and 5 as the only poles worth tracking. The thresholds in the script follow this tutorial's definitions.
Exercises
Exercise
You run the basic audit script on a default cube in Edit Mode and it reports 8 E-poles. Is the cube's topology wrong? Why or why not?
Show answer
No. Each cube corner joins three edges, so each has valence 3 and counts as an E-pole. This is the normal way a closed box is built from quads. A pole count is only a problem when poles sit on curved areas where they cause pinching, so the cube is clean.
Exercise
Why does the improved script skip vertices where v.is_boundary is true when counting poles, and what would go wrong without that check?
Show answer
A vertex on the border of an open mesh has fewer connected edges only because the surface ends there. For example, a regular border vertex on a plane has valence 3. Without the check, those vertices would be counted as E-poles, giving many false positives on any open mesh.
Exercise
The script prints "N-poles: 0" and "N-gons: 0" but the subdivided mesh still looks lumpy. Name two reasons the audit could miss, and say what you would check next.
Show answer
The audit does not measure edge flow, so loops may run across the form instead of along it. It may also be reading only the base mesh while a modifier such as Mirror changes the final shape. Check the edge flow visually against the contours, and inspect the center line after applying Mirror on a copy.