¿Cómo apilar la isla UV usando Python en Blender?

Sep 18 2020

Estoy buscando ayuda / solución a mi pregunta "Cómo apilar la isla UV usando Python en Blender.

No me he alejado mucho del principio, pero esto es todo lo que llegué hasta aquí:

import bpy

me = bpy.context.object.data
uv_layer = me.uv_layers.active.data

for poly in me.polygons:
    # Here I want to move the selected poly in the location of my 2D cursor
    # So eventually all my polygons are stacked into the same pile 

Esta es una pregunta para principiantes y toda la ayuda y las sugerencias son muy apreciadas.

------------------EDITAR---------------------

Aquí está la ilustración de lo que quiero lograr con el guión:

  1. Seleccione isla UV

  2. Ajuste la isla UV al cursor 2D

  3. Repita las fases 1 y 2 para cada cara de la malla, de modo que eventualmente todas las caras se apilen una encima de la otra.

Respuestas

2 lemon Sep 18 2020 at 13:52

Aquí necesitamos tres cosas:

  • Encuentra la posición del cursor 2d
  • Verifique el modo en el que estamos antes de procesar las coordenadas UV
  • Utilice la capa UV para encontrar las coordenadas UV

Para cada cara, una vez que se encuentran las coordenadas UV, calcula su centro y compensa las coordenadas por la diferencia con el cursor.

Tenga en cuenta que si no se abre ningún editor UV, no encontrará el cursor y no hará nada.

Código comentado:

import bpy
from mathutils import Vector


def find_cursor_location():
    # Look through area and find the first image editor
    for area in bpy.context.screen.areas:
        if area.type == 'IMAGE_EDITOR':
            return area.spaces.active.cursor_location
    return None

obj = bpy.context.object
cursor = find_cursor_location()

if cursor:
    #Check the mode as we cant do it in edit mode
    mode = obj.mode
    if mode != 'OBJECT':
        bpy.ops.object.mode_set(mode='OBJECT')
        
    me = obj.data #Need to get it here in case mode is changed
    uv_layer = me.uv_layers.active

    if uv_layer:
        for poly in me.polygons:
            # Get all Uv coordinates of the face
            uvs = [uv_layer.data[loop_index].uv for loop_index in poly.loop_indices]
            # Its center
            center = sum(uvs, Vector((0,0))) / len(uvs)
            # The needed offset
            delta = center - cursor
            # Shift UV coords
            for uv_data in [uv_layer.data[loop_index] for loop_index in poly.loop_indices]:
                uv_data.uv -= delta

    #Back to the mode we were in
    if mode != 'OBJECT':
        bpy.ops.object.mode_set(mode=mode)