Давайте реализуем сложную параметрическую пирамиду с использованием кривых Безье. Вот усовершенствованный скрипт:
python Copy code
import bpy
import math
from mathutils import Vector
def create_bezier_pyramid(
name="ParametricPyramid",
sides=5,
base_radius=3,
height=4,
edge_radius=0.5,
bevel_resolution=16,
vertical_radius=None,
resolution_u=32
):
# Очистка сцены
bpy.ops.object.select_all(action='DESELECT')
# Создаём новую кривую
curve_data = bpy.data.curves.new(name=name, type='CURVE')
curve_data.dimensions = '3D'
curve_data.resolution_u = resolution_u
curve_data.bevel_resolution = bevel_resolution
# Рассчитываем вершины основания
angle_step = 2 * math.pi / sides
base_vertices = []
for i in range(sides):
angle = i * angle_step
x = base_radius * math.cos(angle)
y = base_radius * math.sin(angle)
base_vertices.append(Vector((x, y, 0)))
apex = Vector((0, 0, height))
# Создаём сплайны для каждого ребра
for i in range(sides):
# Получаем параметры радиуса
current_radius = edge_radius[i] if isinstance(edge_radius, list) else edge_radius
vert_radius = vertical_radius[i] if isinstance(vertical_radius, list) else vertical_radius or current_radius
# Боковое ребро (основание -> вершина)
create_bezier_edge(
curve_data,
start=base_vertices[i],
end=apex,
radius=vert_radius,
connection_radius=current_radius
)
# Ребро основания
next_idx = (i + 1) % sides
create_bezier_edge(
curve_data,
start=base_vertices[i],
end=base_vertices[next_idx],
radius=current_radius,
spiral_factor=0.0
)
# Создаём объект и добавляем в сцену
curve_obj = bpy.data.objects.new(name, curve_data)
bpy.context.collection.objects.link(curve_obj)
# Настройка материалов
setup_materials(curve_obj)
return curve_obj
def create_bezier_edge(curve_data, start, end, radius=0.5, connection_radius=None, spiral_factor=0.2):
spline = curve_data.splines.new('BEZIER')
spline.bezier_points.add(1)
# Рассчитываем направление
direction = end - start
length = direction.length
direction.normalize()
# Настраиваем контрольные точки
bp_start = spline.bezier_points[0]
bp_end = spline.bezier_points[1]
# Параметры кривизны
connection_radius = connection_radius or radius
tangent_offset = direction * length * 0.4 * spiral_factor
normal_offset = direction.cross(Vector((0, 0, 1))) * radius
# Начальная точка
bp_start.co = start
bp_start.handle_right_type = 'ALIGNED'
bp_start.handle_left_type = 'ALIGNED'
bp_start.handle_right = start + tangent_offset + normal_offset
bp_start.handle_left = start - tangent_offset - normal_offset
# Конечная точка
bp_end.co = end
bp_end.handle_right_type = 'ALIGNED'
bp_end.handle_left_type = 'ALIGNED'
bp_end.handle_right = end - tangent_offset + normal_offset
bp_end.handle_left = end + tangent_offset - normal_offset
# Настройка толщины
spline.bezier_points[0].radius = connection_radius
spline.bezier_points[1].radius = radius
def setup_materials(obj):
# Создаём материал с настройкой анимации
mat = bpy.data.materials.new(name="ParametricMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
# Очищаем стандартные ноды
for node in nodes:
nodes.remove(node)
# Создаём шейдер
bsdf = nodes.new('ShaderNodeBsdfPrincipled')
bsdf.location = (0, 0)
output = nodes.new('ShaderNodeOutputMaterial')
output.location = (400, 0)
# Связываем ноды
mat.node_tree.links.new(bsdf.outputs['BSDF'], output.inputs['Surface'])
# Назначаем материал объекту
obj.data.materials.append(mat)
# Параметры пирамиды
PYRAMID_PARAMS = {
"name": "CustomPyramid",
"sides": 5,
"base_radius": 3.5,
"height": 5,
"edge_radius": [0.8, 0.4, 0.6, 0.3, 0.5], # Радиусы для каждого ребра
"vertical_radius": 0.3, # Радиус вертикальных рёбер
"bevel_resolution": 32,
"resolution_u": 64
}
# Создание пирамиды
pyramid = create_bezier_pyramid(**PYRAMID_PARAMS)
# Автоматическая настройка камеры
bpy.ops.object.camera_add(location=(10, -10, 7))
bpy.context.scene.camera = bpy.context.object
Этот скрипт создаёт полностью параметрическую модель, которую можно анимировать и модифицировать непосредственно в Blender после создания.