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

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

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

from mathutils import Vector  NObjects = 7Seed = 444 


def addSceneGameSettings(scn):

    # Данные игровой сцены

    sgdata = scn.game_settings

    sgdata.fps = 25 sgdata.frequency = True

    sgdata.material_mode = 'GLSL'

    sgdata.show_debug_properties = True

    sgdata.show_framerate_profile = True

    sgdata.show_fullscreen = True

    sgdata.show_physics_visualization = True

    sgdata.use_animation_record = True return 


def addMonkeyGameSettings(ob):

    # Настройки игрового объекта

    goset = ob.game

    goset.physics_type = 'RIGID_BODY'

    goset.use_actor = True

    goset.use_ghost = False

    goset.mass = 7.0

    goset.damping = 0.0


     goset.use_collision_bounds = True

    goset.collision_bounds_type = 'BOX'


    goset.show_actuators = True goset.show_controllers = True

    goset.show_debug_state = True

    goset.show_sensors = True goset.show_state_panel = True


    return 


def run(origin):

    # Смена движка рендера с BLENDER_RENDER на BLENDER_GAME

    bpy.context.scene.render.engine = 'BLENDER_GAME'  


    # Создание пола

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

    bpy.ops.transform.resize(value=(20, 20, 20))

    floor = bpy.context.object

    mat = bpy.data.materials.new(name = 'FloorMaterial')

    mat.diffuse_color = (0.5, 0.5, 0.5)  


    # Создание кучи объектов

    objectType = ["cube", "ico_sphere", "monkey"]

    objects = []

    deg2rad = math.pi/180

    random.seed(Seed)

    for n in range(NObjects):

        x = []

        for i in range(3):

            x.append( random.randrange(0, 360, 1) )

        dx = 0.5*random.random()

        dy = 0.5*random.random()

        obType = objectType[ random.randrange(0, 3, 1) ]

        fcn = eval("bpy.ops.mesh.primitive_%s_add" % obType)

        fcn(location=origin+Vector((dx, dy, 3*n+3)),

            rotation=deg2rad*Vector((x[0], x[1], x[2])))

        ob = bpy.context.object objects.append( ob )

        mat = bpy.data.materials.new(name='Material_%02d' % n) c = []

        for j in range(3):

        c.append( random.random() ) mat.diffuse_color = c

        ob.data.materials.append(mat)  


    # Установка игровых настроек для пола

    fset = floor.game

    fset.physics_type = 'STATIC'  


    # Установка игровых настроек для объектов

    for n in range(NObjects):

        addMonkeyGameSettings(objects[n])  


    # Установка игровых настроек для сцены

    scn = bpy.context.scene

    addSceneGameSettings(scn)

    scn.frame_start = 1

    scn.frame_end = 200 return 


if __name__ == "__main__":

    bpy.ops.object.select_by_type(type='MESH')

    bpy.ops.object.delete()

    run(Vector((0,0,0)))

    bpy.ops.view3d.game_start()


Жидкости

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

Изображение кадра 57, после добавления нескольких материалов. Капли в основном отрендерены полностью, если они имеют низкую прозрачность, около alpha = 0,2.





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

# File fluid.py

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

import bpy, math

from mathutils import Vector

from math import pi  


def createDomain(origin):

    # Домен

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

    bpy.ops.transform.resize(value=(4, 4, 4))

    domain = bpy.context.object

    domain.name = 'Domain'

    bpy.ops.object.shade_smooth()

    # Добавление модификатора домену

    mod = domain.modifiers.new(name='FluidDomain', type='FLUID_SIMULATION')

    # mod.settings is FluidSettings

    mod.settings.type = 'DOMAIN'

    # mod.settings now changed to DomainFluidSettings

    settings = mod.settings

    settings.use_speed_vectors = False

    settings.simulation_scale = 3.0

    settings.slip_type = 'FREESLIP'

    settings.tracer_particles = 10

    settings.generate_particles = 1.5

    #settings.start_time = 0.0

    #settings.end_time = 2.0

    return domain  


def createFluid(origin):

    # Жидкость

    bpy.ops.mesh.primitive_ico_sphere_add(

        size=3.5,

        subdivisions=1,

        location=origin)

    fluid = bpy.context.object

    fluid.name = 'Fluid'

    fluid.hide = True

    fluid.hide_render = True

    # Добавление модификатора жидкости

    mod = fluid.modifiers.new(name='Fluid', type='FLUID_SIMULATION')

    mod.settings.type = 'FLUID'

    return fluid 


def createObstacle(origin):

    # Препятствие

    bpy.ops.mesh.primitive_cylinder_add(

        vertices=12,

        radius=0.3,

        depth=2,

        cap_ends=True,

        location=origin + Vector((0,0,-2.5)),

        rotation=(pi/2, 0, 0))

    bpy.ops.object.modifier_add(type='FLUID_SIMULATION')

    obst = bpy.context.object

    obst.name = 'Obstacle'

    # Добавление модификатора препятствию

    bpy.ops.object.modifier_add(type='FLUID_SIMULATION')

    mod = obst.modifiers[-1]

    mod.settings.type = 'OBSTACLE'  


    # Анимация препятствия

    scn = bpy.context.scene

    scn.frame_current = 1

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

    scn.frame_current = 26

    bpy.ops.transform.rotate(value=(pi/2,), axis=(-0, -0, -1))

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

    scn.frame_current = 1

    for fcu in obst.animation_data.action.fcurves:

        fcu.extrapolation = 'LINEAR'

        for kp in fcu.keyframe_points:

            kp.interpolation = 'LINEAR'

    return obst 


def createInflow(origin):

    # Приток

    bpy.ops.mesh.primitive_circle_add(

        radius=0.75,

        fill=True,

        location=origin+Vector((-3.9,0,3)),

        rotation=(0, pi/2, 0))

    inflow = bpy.context.object

    inflow.name = 'Inflow'

    # Добавление модификатора притоку

    bpy.ops.object.modifier_add(type='FLUID_SIMULATION')

    mod = inflow.modifiers[-1]

    mod.settings.type = 'INFLOW'

    settings = mod.settings

    settings.inflow_velocity = (1.5,0,0)

    settings.volume_initialization = 'SHELL'

    return inflow 


def createOutflow(origin):

    # Отток

    bpy.ops.mesh.primitive_circle_add(

        radius=0.75,

        fill=True,

        location=origin+Vector((3.9,0,-3)),

        rotation=(0, -pi/2, 0))

    outflow = bpy.context.object

    outflow.name = 'Outflow'

    # Добавление модификатора оттоку

    bpy.ops.object.modifier_add(type='FLUID_SIMULATION')

    mod = outflow.modifiers[-1]

    mod.settings.type = 'OUTFLOW'

    mod.settings.volume_initialization = 'SHELL'

    return outflow 


def createFluidParticle(name, origin, data):

    # Частицы жидкости

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

    monkey = bpy.context.object

    monkey.name = name

    # Добавление модификатора жидкости-частиц

    bpy.ops.object.modifier_add(type='FLUID_SIMULATION')

    mod = monkey.modifiers[-1]

    mod.settings.type = 'PARTICLE'

    (drops, floats, tracer) = data

    mod.settings.use_drops = drops

    mod.settings.use_floats = floats

    mod.settings.show_tracer = tracer  


    # Настройка типа частиц созданной системы частиц

    psys = monkey.modifiers[-1].particle_system

    psys.name = name+'Psys'

    #psys.settings.name = name+'Pset'

    return (mod.settings, None)  


def run(origin):

    domain = createDomain(origin)

    fluid = createFluid(origin)

    obst = createObstacle(origin)

    inflow = createInflow(origin)

    outflow = createOutflow(origin)


    (settings, pset) = createFluidParticle('Drops',

        origin+Vector((-2,7,0)), (True, False, False))

    settings.particle_influence = 0.7

    settings.alpha_influence = 0.3


    (settings, pset) = createFluidParticle('Floats',

        origin+Vector((0,7,0)), (False, True, False))


    (settings, pset) = createFluidParticle('Tracer',

        origin+Vector((2,7,0)), (False, False, True))

    settings.particle_influence = 1.5

    settings.alpha_influence = 1.2

    return 


if __name__ == "__main__":

    bpy.ops.object.select_all(action='SELECT')

    bpy.ops.object.delete() run(Vector((0,0,0)))

    #bpy.ops.fluid.bake()




Ноды

Эта программа создаёт нодовую сеть.



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

# File nodes.py

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

import bpy, math 


# Включение нодов

bpy.context.scene.use_nodes = True

tree = bpy.context.scene.node_tree

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