Skip to content

Instantly share code, notes, and snippets.

@rickomax
Created July 16, 2024 21:54
Show Gist options
  • Save rickomax/32830cfe168a551a26b91c1fc94de9e1 to your computer and use it in GitHub Desktop.
Save rickomax/32830cfe168a551a26b91c1fc94de9e1 to your computer and use it in GitHub Desktop.
# This Python script for Blender first tries to convert all the Blender scene meshes into quads
# It will then proceed to merge all vertices that occupy the same position
# Lastly, it will subdivide the quad edges until every edge has at least the length of the "max_edge_length" variable
# You can use this script to subdivide the scene into quads, which is ideal for vertex lighting
# Please set the "max_edge_length" and "vert_merge_distance" variables value accordingly
# Set the maximum edge length here. The smaller the value, the more the edges get subdivided
max_edge_length = 300.0
# Set the minimum distance a vertex can have from each other not to be merged here
vert_merge_distance = 0.00001
import bpy
import bmesh
def remove_duplicates(obj, merge_distance):
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.remove_doubles(threshold = merge_distance)
bpy.ops.object.mode_set(mode='OBJECT')
def tris_to_quads(obj):
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.tris_convert_to_quads()
bpy.ops.object.mode_set(mode='OBJECT')
def subdivide_quads_by_length(obj, max_length):
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
me = obj.data
bm = bmesh.from_edit_mesh(me)
subdivided_edges = set()
for face in bm.faces:
for edge in face.edges:
if edge.calc_length() > max_length:
if edge not in subdivided_edges:
subdivided_edges.add(edge)
bmesh.ops.subdivide_edges(bm, edges=list(subdivided_edges), cuts=1, use_grid_fill=True, use_only_quads=True)
bmesh.update_edit_mesh(me)
bpy.ops.object.mode_set(mode='OBJECT')
return bool(subdivided_edges)
for obj in bpy.context.scene.objects:
if obj.type == 'MESH':
tris_to_quads(obj)
remove_duplicates(obj, vert_merge_distance)
subdivide = True
while subdivide:
subdivide = subdivide_quads_by_length(obj, max_edge_length)
@rickomax
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment