Skip to content

Instantly share code, notes, and snippets.

@satabol
Last active September 14, 2025 17:49
Show Gist options
  • Select an option

  • Save satabol/42b1b5892f44b3d02bfd65323fa37bc8 to your computer and use it in GitHub Desktop.

Select an option

Save satabol/42b1b5892f44b3d02bfd65323fa37bc8 to your computer and use it in GitHub Desktop.
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
### Описание:
### Пример шаблона нода Sverchok: https://github.com/nortikin/sverchok
### Нод Cuboid (Параллелепипед) с параметрами Длина, Ширина, Высота (X, Y, Z), Origin (Corner, Center, Bottom)
### Обязательно:
### Добавить название класса SvCuboidNode в файле index.yaml в раздел меню Generators, чтобы этот нод появился в списке меню
import bpy
from bpy.props import FloatProperty, EnumProperty
from mathutils import Matrix, Vector
import numpy as np
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, list_match_func, list_match_modes, ensure_nesting_level
from sverchok.utils.modules.matrix_utils import matrix_apply_np
class SvCuboidNode(SverchCustomTreeNode, bpy.types.Node):
"""
Triggers: Cuboid
Tooltip: Generate a Cuboid primitive. [default]\n\tOrigin: Center/Bottom/Corner, [Center]\n\tSize: (float). Num or List of float, [1.0] \n\tDivisions: X / Y / Z (int), [1]\n\tMatrix Transform
"""
bl_idname = 'SvCuboidNode'
bl_label = 'Cuboid'
bl_icon = 'MESH_CUBE'
### 3. (Параметры нода) Параметр центра параллелепипеда в виде выпадающего списка
origin_modes = [
('CENTER', 'Center', 'Origin at center of the box', 0),
('BOTTOM', 'Bottom', 'Origin at the bottom center of the box', 1),
('CORNER', 'Corner', 'Origin at the bottom left front corner of the box', 2),
]
origin: EnumProperty(
name="Origin",
description="Behavior on different list lengths, multiple objects level",
items=origin_modes, default="CENTER",
update=updateNode)
### 3. (Параметры нода) Размеры параллелепипеда (длина X, ширина Y, высота Z)
size_x: FloatProperty(
name='Size X', description='Size X',
default=1.0, min=0.0,
update=updateNode
)
size_y: FloatProperty(
name='Size Y', description='Size Y',
default=1.0, min=0.0,
update=updateNode
)
size_z: FloatProperty(
name='Size Z', description='Size Z',
default=1.0, min=0.0,
update=updateNode
)
### Функция инициализации нода. Вызывается один раз при создании нода через меню (Shift-A)
def sv_init(self, context):
### 1. Входной сокет, Matrixes, позволяющий задать матрицы модификации объектов. Количество параллелепипедов будет создано по количеству матриц. По-умолчанию задаётся елиничная матрица
self.inputs.new('SvMatrixSocket', "matrixes")
self.inputs['matrixes'].label = 'Matrixes' # Наименование входного сокета, надпись, которая выводится справа от сокета
### 2. Выходные сокеты с параметрами результирующей полигональной сеткой параллелепипеда
self.outputs.new('SvVerticesSocket', "vertices").label = "Vertices"
self.outputs.new('SvStringsSocket', "edges").label = "Edges"
self.outputs.new('SvStringsSocket', "polygons").label = "Polygons"
### 3. Вывод параметров параллелепипеда в интерфейс ноды.
def draw_buttons(self, context, layout):
layout.row().prop(self, "origin", expand=False)
layout.row().prop(self, "size_x", expand=False)
layout.row().prop(self, "size_y", expand=False)
layout.row().prop(self, "size_z", expand=False)
### 4. Функция расчёта параллелепипеда на основе параметров заданных в интерфейсе нода и матриц (их может быть несколько), полученных во входном сокете Matrixes
def process(self):
outputs = self.outputs
### Если входные ноды не подключены, то не выполнять обработку параметров, т.к. результат никуда не выводится (пропустить в целях производительности).
if not any(s.is_linked for s in outputs):
return
_Matrixes = self.inputs['matrixes'].sv_get(default=[[Matrix()]], deepcopy=False)
Matrixes2 = ensure_nesting_level(_Matrixes, 2)
size_x, size_y, size_z = self.size_x, self.size_y, self.size_z
### Создание полгональной сетки параллелепипеда по заданным размерам:
verts_out = [[ 0, 0, 0], [ 0, 0, size_z], [ 0, size_y, 0], [ 0, size_y, size_z],
[size_x, 0, 0], [size_x, 0, size_z], [size_x, size_y, 0], [size_x, size_y, size_z],]
edges_out = [[2,0], [0,1], [1,3], [3,2], [6,2], [3,7], [7,6], [4,6], [7,5], [5,4], [0,4], [5,1] ]
faces_out = [[0,1,3,2], [2,3,7,6], [6,7,5,4], [4,5,1,0], [2,6,4,0], [7,3,1,5] ]
### Смещание вершин параллелепипеда относительно точки (0,0,0) с учётом значения параметра центральной точки
if self.origin=='CORNER':
pass
elif self.origin=='BOTTOM':
T = Matrix.Translation((-size_x/2, -size_y/2, 0.0))
verts_t = [T @ Vector(p) for p in verts_out]
verts_out = [[p.x, p.y, p.z] for p in verts_t]
pass
elif self.origin=='CENTER':
T = Matrix.Translation((-size_x/2, -size_y/2, -size_z/2))
verts_t = [T @ Vector(p) for p in verts_out]
verts_out = [[p.x, p.y, p.z] for p in verts_t]
pass
arr_verts = []
### Создать несколько параллелепипедов по количеству матриц:
for index, mat in enumerate(Matrixes2[0]):
verts_t = [mat @ Vector(p) for p in verts_out]
verts = [[p.x, p.y, p.z] for p in verts_t]
arr_verts.append(verts)
verts_out = arr_verts
edges_out = [edges_out for n in range(len(arr_verts))]
faces_out = [faces_out for n in range(len(arr_verts))]
### Передать данные в выходные сокеты
outputs['vertices'].sv_set(verts_out)
outputs['edges'] .sv_set(edges_out)
outputs['polygons'].sv_set(faces_out)
### Регистрация класса в Blender:
classes = [SvCuboidNode, ]
register, unregister = bpy.utils.register_classes_factory(classes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment