KnigaRead.com/
KnigaRead.com » Компьютеры и Интернет » Программирование » Thomas Larsson - Введение в написание скриптов на Питоне для Блендера 2.5x. Примеры кода

Thomas Larsson - Введение в написание скриптов на Питоне для Блендера 2.5x. Примеры кода

На нашем сайте KnigaRead.com Вы можете абсолютно бесплатно читать книгу онлайн "Thomas Larsson - Введение в написание скриптов на Питоне для Блендера 2.5x. Примеры кода". Жанр: Программирование издательство неизвестно, год неизвестен.
Перейти на страницу:

import bpy, os 


def run(origin):

 # Загрузка файла с рисунком. Измените здесь, если каталог snippets

 # расположен не в Вашем домашнем каталоге.

    realpath = os.path.expanduser('~/snippets/textures/color.png')

    try:

        img = bpy.data.images.load(realpath)

    except:

        raise NameError("Cannot load image %s" % realpath)


    # Создание текстуры image из загруженного рисунка

    cTex = bpy.data.textures.new('ColorTex', type = 'IMAGE')

    cTex.image = img


    # Создание процедурной текстуры

    sTex = bpy.data.textures.new('BumpTex', type = 'STUCCI')

    sTex.noise_basis = 'BLENDER_ORIGINAL'

    sTex.noise_scale = 0.25

    sTex.noise_type = 'SOFT_NOISE'

    sTex.saturation = 1

    sTex.stucci_type = 'PLASTIC'

    sTex.turbulence = 5


    # Создание текстуры blend с цветовой полосой (color ramp)

    # Не знаю, как добавлять элементы к полосе, так что сейчас только два

    bTex = bpy.data.textures.new('BlendTex', type = 'BLEND')

    bTex.progression = 'SPHERICAL'

    bTex.use_color_ramp = True

    ramp = bTex.color_ramp

    values = [(0.6, (1,1,1,1)), (0.8, (0,0,0,1))]

    for n,value in enumerate(values):

        elt = ramp.elements[n]

        (pos, color) = value

        elt.position = pos

        elt.color = color


    # Создание материала

    mat = bpy.data.materials.new('TexMat')


    # Добавление текстурного слота для цветной текстуры

    mtex = mat.texture_slots.add()

    mtex.texture = cTex

    mtex.texture_coords = 'UV'

    mtex.use_map_color_diffuse = True

    mtex.use_map_color_emission = True

    mtex.emission_color_factor = 0.5

    mtex.use_map_density = True

    mtex.mapping = 'FLAT'


    # Добавление текстурного слота для bump-текстуры

    mtex = mat.texture_slots.add()

    mtex.texture = sTex

    mtex.texture_coords = 'ORCO'

    mtex.use_map_color_diffuse = False

    mtex.use_map_normal = True

    #mtex.rgb_to_intensity = True


    # Добавление текстурного слота

    mtex = mat.texture_slots.add()

    mtex.texture = bTex

    mtex.texture_coords = 'UV'

    mtex.use_map_color_diffuse = True

    mtex.diffuse_color_factor = 1.0

    mtex.blend_type = 'MULTIPLY'


    # Создание нового куба и наложение на него UV-раскладки

    bpy.ops.mesh.primitive_cube_add(location=origin)

    bpy.ops.object.mode_set(mode='EDIT')

    bpy.ops.uv.smart_project()

    bpy.ops.object.mode_set(mode='OBJECT')


    # Добавление материала к текущему объекту

    ob = bpy.context.object

    me = ob.data

    me.materials.append(mat)


    return 


if __name__ == "__main__":

    run((0,0,0))


Множественные материалы

Эта программа добавляет три материала к одному мешу.



#----------------------------------------------------------

# File multi_material.py

#----------------------------------------------------------

import bpy 


def run(origin):

    # Создание трёх материалов

    red = bpy.data.materials.new('Red')

    red.diffuse_color = (1,0,0)

    blue = bpy.data.materials.new('Blue')

    blue.diffuse_color = (0,0,1)

    yellow = bpy.data.materials.new('Yellow')

    yellow.diffuse_color = (1,1,0)


   # Создание меша и назначение материалов

    bpy.ops.mesh.primitive_uv_sphere_add(

        segments = 16,

        ring_count = 8,

        location=origin)

    ob = bpy.context.object

    ob.name = 'MultiMatSphere'

    me = ob.data me.materials.append(red)

    me.materials.append(blue)

    me.materials.append(yellow)


    # Назначение материалов граням

    for f in me.faces:

        f.material_index = f.index % 3


    # Установка левой половины сферы в плавное затенение,

    # правой половины — в плоское затенение

    for f in me.faces:

        f.use_smooth = (f.center[0] < 0)  


if __name__ == "__main__":

    run((0,0,0))


Слои UV-раскладки

Эта программа добавляет два UV-слоя к мешу.



#----------------------------------------------------------

# File uvs.py

#----------------------------------------------------------

import bpy import os 


def createMesh(origin):

    # Создание меша и объекта

    me = bpy.data.meshes.new('TetraMesh')

    ob = bpy.data.objects.new('Tetra', me)

    ob.location = origin

    # Привязка объекта к сцене

    scn = bpy.context.scene

    scn.objects.link(ob)

    scn.objects.active = ob scn.update()


    # Списки вершин и граней

    verts = [

        (1.41936, 1.41936, -1),

        (0.589378, -1.67818, -1),

        (-1.67818, 0.58938, -1),

        (0, 0, 1)

    ]

    faces = [(1,0,3), (3,2,1), (3,0,2), (0,1,2)]

    # Создание меша из передаваемых списков вершин, рёбер, граней.

    # Или рёбра или грани должны быть [], или Вам нужны проблемы

    me.from_pydata(verts, [], faces)


    # Обновление меша с новыми данными

    me.update(calc_edges=True)


    # Первый текстурный слой: Главная UV текстура (UVMain)

    texFaces = [

        [(0.6,0.6), (1,1), (0,1)],

        [(0,1), (0.6,0), (0.6,0.6)],

        [(0,1), (0,0), (0.6,0)],

        [(1,1), (0.6,0.6), (0.6,0)]

    ]

    uvMain = createTextureLayer("UVMain", me, texFaces)


   # Второй текстурный слой: проекция спереди (UVFront)

    texFaces = [

        [(0.732051,0), (1,0), (0.541778,1)],

        [(0.541778,1), (0,0), (0.732051,0)],

        [(0.541778,1), (1,0), (0,0)],

        [(1,0), (0.732051,0), (0,0)]

    ]

    uvFront = createTextureLayer("UVFront", me, texFaces)


    # Третий текстурный слой: Умная проекция

    bpy.ops.mesh.uv_texture_add()

    uvCyl = me.uv_textures.active

    uvCyl.name = 'UVCyl'

    bpy.ops.object.mode_set(mode='EDIT')

    bpy.ops.uv.cylinder_project()

    bpy.ops.object.mode_set(mode='OBJECT')


# Хотим сделать Главный слой активным, но, кажется, это не работает - TBF

    me.uv_textures.active = uvMain

    me.uv_texture_clone = uvMain

    uvMain.active_render = True

    uvFront.active_render = False

    uvCyl.active_render = False

    return ob 


def createTextureLayer(name, me, texFaces):

    uvtex = me.uv_textures.new()

    uvtex.name = name

    for n,tf in enumerate(texFaces):

        datum = uvtex.data[n]

        datum.uv1 = tf[0]

        datum.uv2 = tf[1]

        datum.uv3 = tf[2]

    return uvtex 


def createMaterial():

    # Создание текстуры image из картинки. Измените здесь, если

    # каталог snippet расположен не в Вашем домашнем каталоге.

     realpath = os.path.expanduser('~/snippets/textures/color.png')

    tex = bpy.data.textures.new('ColorTex', type = 'IMAGE')

    tex.image = bpy.data.images.load(realpath)

    tex.use_alpha = True 


    # Создание незатеняемого материала и MTex

    mat = bpy.data.materials.new('TexMat')

    mat.use_shadeless = True

    mtex = mat.texture_slots.add()

    mtex.texture = tex

    mtex.texture_coords = 'UV'

    mtex.use_map_color_diffuse = True

    return mat 


def run(origin):

    ob = createMesh(origin)

    mat = createMaterial()

    ob.data.materials.append(mat)

    return 


if __name__ == "__main__":

    run((0,0,0))



Действия (Actions) и управляющие элементы (drivers)

Действие объекта

Прыгающий мяч.



#--------------------------------------------------

# File ob_action.py

#--------------------------------------------------

import bpy import math 


def run(origin):

    # Установка начала и конца анимации

    scn = bpy.context.scene

    scn.frame_start = 11

    scn.frame_end = 200


    # Создание ico-сферы

    bpy.ops.mesh.primitive_ico_sphere_add(location=origin)

    ob = bpy.context.object


  # Вставка ключевых кадров с operator code (кодом оператора ???)

    # Объект должен быть выбранным автоматически

    z = 10

    t = 1

    for n in range(5):

        t += 10

        bpy.ops.anim.change_frame(frame = t)

        bpy.ops.transform.translate(value=(2, 0, z))

        bpy.ops.anim.keyframe_insert_menu(type='Location')

        t += 10

        bpy.ops.anim.change_frame(frame = t)

        bpy.ops.transform.translate(value=(2, 0, -z))

        bpy.ops.anim.keyframe_insert_menu(type='Location')

        z *= 0.67


    action = ob.animation_data.action

Перейти на страницу:
Прокомментировать
Подтвердите что вы не робот:*