You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Blender-TexTools/op_island_align_sort.py

177 lines
5.7 KiB
Python

import bpy
import bmesh
import operator
import math
from mathutils import Vector
from collections import defaultdict
from . import utilities_uv
import imp
imp.reload(utilities_uv)
class op(bpy.types.Operator):
4 years ago
bl_idname = "uv.textools_island_align_sort"
bl_label = "Align & Sort"
bl_description = "Rotates UV islands to minimal bounds and sorts them horizontal or vertical"
bl_options = {'REGISTER', 'UNDO'}
4 years ago
is_vertical: bpy.props.BoolProperty(
description="Vertical or Horizontal orientation", default=True)
padding: bpy.props.FloatProperty(
description="Padding between UV islands", default=0.05)
4 years ago
@classmethod
def poll(cls, context):
4 years ago
if not bpy.context.active_object:
return False
4 years ago
if bpy.context.active_object.type != 'MESH':
return False
4 years ago
# Only in Edit mode
4 years ago
if bpy.context.active_object.mode != 'EDIT':
return False
4 years ago
# Only in UV editor mode
4 years ago
if bpy.context.area.type != 'IMAGE_EDITOR':
return False
4 years ago
# Requires UV map
4 years ago
if not bpy.context.object.data.uv_layers:
4 years ago
# self.report({'WARNING'}, "Object must have more than one UV map")
return False
4 years ago
# Not in Synced mode
4 years ago
if bpy.context.scene.tool_settings.use_uv_select_sync:
return False
4 years ago
return True
4 years ago
def execute(self, context):
main(context, self.is_vertical, self.padding)
return {'FINISHED'}
def main(context, isVertical, padding):
4 years ago
print("Executing IslandsAlignSort main {}".format(padding))
4 years ago
# Store selection
4 years ago
utilities_uv.selection_store()
4 years ago
if bpy.context.tool_settings.transform_pivot_point != 'CURSOR':
bpy.context.tool_settings.transform_pivot_point = 'CURSOR'
4 years ago
# Only in Face or Island mode
4 years ago
if bpy.context.scene.tool_settings.uv_select_mode is not 'FACE' or 'ISLAND':
bpy.context.scene.tool_settings.uv_select_mode = 'FACE'
4 years ago
bm = bmesh.from_edit_mesh(bpy.context.active_object.data)
uv_layers = bm.loops.layers.uv.verify()
4 years ago
boundsAll = utilities_uv.getSelectionBBox()
4 years ago
islands = utilities_uv.getSelectionIslands()
4 years ago
allSizes = {} # https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
4 years ago
allBounds = {}
4 years ago
print("Islands: "+str(len(islands))+"x")
4 years ago
bpy.context.window_manager.progress_begin(0, len(islands))
4 years ago
# Rotate to minimal bounds
4 years ago
for i in range(0, len(islands)):
alignIslandMinimalBounds(uv_layers, islands[i])
4 years ago
# Collect BBox sizes
bounds = utilities_uv.getSelectionBBox()
4 years ago
allSizes[i] = max(bounds['width'], bounds['height']) + \
i*0.000001 # Make each size unique
allBounds[i] = bounds
4 years ago
print("Rotate compact: "+str(allSizes[i]))
4 years ago
bpy.context.window_manager.progress_update(i)
4 years ago
bpy.context.window_manager.progress_end()
4 years ago
# Position by sorted size in row
# Sort by values, store tuples
sortedSizes = sorted(allSizes.items(), key=operator.itemgetter(1))
4 years ago
sortedSizes.reverse()
offset = 0.0
for sortedSize in sortedSizes:
index = sortedSize[0]
island = islands[index]
bounds = allBounds[index]
4 years ago
# Select Island
4 years ago
bpy.ops.uv.select_all(action='DESELECT')
utilities_uv.set_selected_faces(island)
4 years ago
# Offset Island
4 years ago
if(isVertical):
4 years ago
delta = Vector(
(boundsAll['min'].x - bounds['min'].x, boundsAll['max'].y - bounds['max'].y))
4 years ago
bpy.ops.transform.translate(value=(delta.x, delta.y-offset, 0))
offset += bounds['height']+padding
else:
print("Horizontal")
4 years ago
delta = Vector(
(boundsAll['min'].x - bounds['min'].x, boundsAll['max'].y - bounds['max'].y))
4 years ago
bpy.ops.transform.translate(value=(delta.x+offset, delta.y, 0))
offset += bounds['width']+padding
4 years ago
# Restore selection
4 years ago
utilities_uv.selection_restore()
def alignIslandMinimalBounds(uv_layers, faces):
4 years ago
# Select Island
bpy.ops.uv.select_all(action='DESELECT')
utilities_uv.set_selected_faces(faces)
steps = 8
4 years ago
angle = 45 # Starting Angle, half each step
4 years ago
bboxPrevious = utilities_uv.getSelectionBBox()
for i in range(0, steps):
# Rotate right
4 years ago
bpy.ops.transform.rotate(
value=(angle * math.pi / 180), orient_axis='Z')
4 years ago
bbox = utilities_uv.getSelectionBBox()
if i == 0:
sizeA = bboxPrevious['width'] * bboxPrevious['height']
sizeB = bbox['width'] * bbox['height']
if abs(bbox['width'] - bbox['height']) <= 0.0001 and sizeA < sizeB:
# print("Already squared")
4 years ago
bpy.ops.transform.rotate(
value=(-angle * math.pi / 180), orient_axis='Z')
break
4 years ago
if bbox['minLength'] < bboxPrevious['minLength']:
4 years ago
bboxPrevious = bbox # Success
4 years ago
else:
# Rotate Left
4 years ago
bpy.ops.transform.rotate(
value=(-angle*2 * math.pi / 180), orient_axis='Z')
4 years ago
bbox = utilities_uv.getSelectionBBox()
if bbox['minLength'] < bboxPrevious['minLength']:
4 years ago
bboxPrevious = bbox # Success
4 years ago
else:
# Restore angle of this iteration
4 years ago
bpy.ops.transform.rotate(
value=(angle * math.pi / 180), orient_axis='Z')
4 years ago
angle = angle / 2
if bboxPrevious['width'] < bboxPrevious['height']:
bpy.ops.transform.rotate(value=(90 * math.pi / 180), orient_axis='Z')
4 years ago
bpy.utils.register_class(op)