end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

blender python で 原点変更や objectのsize変更やmeshの結合

import bpy
import copy
import math
import bmesh
import sys
from mathutils import Vector

def main():
    #全object削除
    remove_all_obj()

    #cube 追加
    new_obj_1 = add_cube_1()
    new_obj_2 = add_cube_2()

    # objectの原点位置を変更 (object自体は移動しません)
    set_origin_cursor(new_obj_1.name, (3,4,5) )

    # objectのsize変更
    set_dimensions(new_obj_2.name, (3,4,5) )
    
    # 存在する全meshの結合
    union_all_objects()

def set_dimensions(obj_name, new_dimensions):

    ob = bpy.data.objects[obj_name]
    ob.dimensions = new_dimensions
    
def set_origin_cursor(arg_objectname='Default',
                      arg_location=(0,0,0) ):
    # 一旦、全objectの選択を解除
    for ob in bpy.context.scene.objects:
        ob.select_set(False)

    # objectを名前で取得し、選択 & active化
    ob = bpy.data.objects[arg_objectname]
    ob.select_set(True)
    bpy.context.view_layer.objects.active = ob

    # 3d cursorの位置をcopy
    cursor_org_pos = copy.copy(bpy.context.scene.cursor.location)

    bpy.context.scene.cursor.location = arg_location
    # objectの原点を3d cursorの位置へ
    bpy.ops.object.origin_set(type='ORIGIN_CURSOR')

    # 3d cursorを元の位置へ
    bpy.context.scene.cursor.location = cursor_org_pos
    return ob

def union_all_objects():
    for ob in bpy.context.scene.objects:
        if ob.type != 'MESH':
            ob.select_set(False)       # 選択解除
            continue
        
        ob.select_set(True)
        bpy.context.view_layer.objects.active = ob
            
    bpy.ops.object.join()

def add_cube_1():
    bpy.ops.mesh.primitive_cube_add(
        size=1.0,
        align='WORLD',
        location=(1.0, 2.0, 3.0), # meter
        rotation=(math.radians(0),
                  math.radians(0),
                  math.radians(0)),
        scale=(3.6+0.25,        #桁
               2.475,           #妻
               2.7+0.25)        #高
    )
    # 作成したobject参照を取得
    obj = bpy.context.view_layer.objects.active
    return obj

def add_cube_2():
    bpy.ops.mesh.primitive_cube_add(
        location=( -1, -2, -3 ),
        rotation=( math.pi/3, 0, 0 ) )
    
    # 作成したobject参照を取得
    obj = bpy.context.view_layer.objects.active
    obj.name  = 'MakeCube'      # 名前変更
    obj.scale = ( 1, 1, 1 )     # scale変更
    obj.select_set(False)       # 選択解除
    return obj


def remove_all_obj():
    for col in bpy.data.collections:
        for item in col.objects:
            col.objects.unlink(item)
            bpy.data.objects.remove(item)

    for item in bpy.context.scene.collection.objects:
        bpy.context.scene.collection.objects.unlink(item)
        bpy.data.objects.remove(item)

    for item in bpy.data.meshes:
        bpy.data.meshes.remove(item)

    for item in bpy.data.materials:
        bpy.data.materials.remove(item)

if __name__ == '__main__':
    main()