Как сложить UV-остров с помощью Python в Blender?

Sep 18 2020

Я ищу помощь / решение своего вопроса «Как сложить UV-остров с помощью Python в Blender.

Я не ушел далеко от начала, но это все, что у меня получилось:

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 

Это вопрос для очень новичков, и мы будем благодарны за любую помощь и подсказки.

------------------РЕДАКТИРОВАТЬ---------------------

Вот иллюстрация того, чего я хочу достичь с помощью сценария:

  1. Выбрать UV-остров

  2. Привязка UV-острова к 2D-курсору

  3. Повторите этапы 1 и 2 для каждой грани в сетке, чтобы в конечном итоге все грани накладывались друг на друга.

Ответы

2 lemon Sep 18 2020 at 13:52

Здесь нам понадобятся три вещи:

  • Найдите 2-ю позицию курсора
  • Перед обработкой UV-координат проверьте, в каком режиме мы находимся.
  • Используйте слой UV, чтобы найти координаты UV

Для каждого лица, как только UV-координаты найдены, вычислите их центр и сместите координаты на разницу от курсора.

Обратите внимание: если УФ-редактор не открыт, курсор не будет обнаружен и ничего не сделает.

Прокомментированный код:

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)