Files
RoboMovel/simulacao/robo-movel-godot/tools/robo_rig.py
T
mguinhos d17575771b Projeto: app demo, servidor/firmware em software/, simulacao Godot, planta do bloco D, chapas MDF da base, renders e slides
- app/: app demo (Kivy/buildozer) da API do robo
- software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/)
- simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao
- modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo
- partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd)
- projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso
- ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender
- .gitignore: ignora backups do Blender/FreeCAD e .godot/
2026-10-25 23:38:16 -03:00

274 lines
9.6 KiB
Python

# -*- coding: utf-8 -*-
"""Monta e riga o RoboMovel no Blender e exporta um GLB com skin e texturas.
Uso:
blender -b -P tools/robo_rig.py -- <saida.glb>
Referencial do robô (Blender): X = direita, Y = frente, Z = para cima,
chão em Z = 0, centro em (0, 0). Dimensões reais: 0,50 x 0,50 x 1,06 m.
Armature:
Root — raiz (chão)
Corpo — chassi + prateleiras + tampo + eletrônica
Camera — suporte + câmera frontal
Roda_FD/FE/TD/TE — as quatro rodas mecanum (eixo em X)
Cada peça entra com peso 1 no osso correspondente (deformação rígida).
As peças de MDF recebem textura de veio de madeira gerada em NumPy; o metal,
a borracha, o PCB e o plástico ficam com cores sólidas.
"""
import bpy, bmesh, math, os, sys
import numpy as np
from mathutils import Vector
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
OUT = os.path.abspath(argv[0]) if argv else os.path.abspath("robo_movel.glb")
SEG = 24
# ------------------------------------------------------------------ limpeza
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.context.scene.unit_settings.system = "METRIC"
# ------------------------------------------------------------------ texturas
def _bilinear(a, n):
c = a.shape[0]
x = np.linspace(0, c - 1, n, dtype=np.float32)
x0 = np.floor(x).astype(int)
x1 = np.minimum(x0 + 1, c - 1)
fx = (x - x0)[None, :]
tmp = a[x0, :] * (1 - fx) + a[x1, :] * fx
y = x
y0 = np.floor(y).astype(int)
y1 = np.minimum(y0 + 1, c - 1)
fy = (y - y0)[:, None]
return tmp[:, y0] * (1 - fy) + tmp[:, y1] * fy
def textura_mdf(nome, base, escuro, seed=7, n=512):
rng = np.random.default_rng(seed)
yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) / n
def ruido(cells):
return _bilinear(rng.random((cells, cells)).astype(np.float32), n)
n1, n2, n3 = ruido(6), ruido(48), ruido(240)
veio = 0.5 + 0.5 * np.sin(yy * 95.0 + n1 * 26.0)
var = 0.74 + 0.30 * n2 + 0.16 * n3 + 0.10 * veio
base = np.array(base, np.float32)
escuro = np.array(escuro, np.float32)
cor = base[None, None, :] * var[..., None] + (escuro - base)[None, None, :] * (1 - veio)[..., None] * 0.30
cor = np.clip(cor, 0, 1)
img = bpy.data.images.new(nome, n, n, alpha=False)
img.colorspace_settings.name = "sRGB"
rgba = np.concatenate([cor, np.ones((n, n, 1), np.float32)], axis=2).ravel()
img.pixels.foreach_set(rgba)
img.pack()
return img
def material(nome, cor, rough=0.6, metal=0.0):
m = bpy.data.materials.new(nome)
m.use_nodes = True
b = m.node_tree.nodes.get("Principled BSDF")
b.inputs["Base Color"].default_value = (*cor, 1.0)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
return m
def liga_textura(mat, img):
nt = mat.node_tree
b = nt.nodes.get("Principled BSDF")
tex = nt.nodes.new("ShaderNodeTexImage")
tex.image = img
tex.interpolation = "Linear"
nt.links.new(tex.outputs["Color"], b.inputs["Base Color"])
TEX_MDF = textura_mdf("mdf_wood", (0.74, 0.58, 0.40), (0.44, 0.30, 0.18), 7)
TEX_MDF_ESC = textura_mdf("mdf_wood_escuro", (0.56, 0.42, 0.27), (0.30, 0.19, 0.10), 13)
M_MDF = material("mdf", (0.74, 0.58, 0.40), 0.80)
M_MDF_ESC = material("mdf_escuro", (0.52, 0.39, 0.26), 0.85)
M_METAL = material("metal", (0.12, 0.12, 0.14), 0.45, 0.85)
M_AMARELO = material("amarelo", (0.95, 0.72, 0.12), 0.50)
M_BORRACHA = material("borracha", (0.06, 0.06, 0.07), 0.95)
M_PCB = material("pcb", (0.05, 0.35, 0.15), 0.60)
M_BRANCO = material("branco", (0.90, 0.90, 0.90), 0.50)
liga_textura(M_MDF, TEX_MDF)
liga_textura(M_MDF_ESC, TEX_MDF_ESC)
# ------------------------------------------------------------------ malhas
def gera_caixa(size):
sx, sy, sz = (s * 0.5 for s in size)
v = [(-sx, -sy, -sz), (sx, -sy, -sz), (sx, sy, -sz), (-sx, sy, -sz),
(-sx, -sy, sz), (sx, -sy, sz), (sx, sy, sz), (-sx, sy, sz)]
f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
(1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
return v, f
def gera_cilindro(raio, comp, eixo="Z", seg=SEG):
v = []
f = []
h = comp * 0.5
def ponto(a, t):
if eixo == "X":
return (t, raio * math.cos(a), raio * math.sin(a))
if eixo == "Y":
return (raio * math.cos(a), t, raio * math.sin(a))
return (raio * math.cos(a), raio * math.sin(a), t)
for i in range(seg):
v.append(ponto(2 * math.pi * i / seg, -h))
for i in range(seg):
v.append(ponto(2 * math.pi * i / seg, h))
for i in range(seg):
j = (i + 1) % seg
f.append((i, j, seg + j, seg + i))
f.append(tuple(range(seg - 1, -1, -1)))
f.append(tuple(range(seg, 2 * seg)))
return v, f
PECAS = []
def nova(nome, malha, loc, mat, osso):
verts, faces = malha
verts = [(x + loc[0], y + loc[1], z + loc[2]) for (x, y, z) in verts]
me = bpy.data.meshes.new(nome)
me.from_pydata(verts, [], faces)
me.validate()
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
bm.to_mesh(me)
bm.free()
me.update()
ob = bpy.data.objects.new(nome, me)
bpy.context.collection.objects.link(ob)
ob.data.materials.append(mat)
vg = ob.vertex_groups.new(name=osso)
vg.add([vt.index for vt in me.vertices], 1.0, "REPLACE")
PECAS.append(ob)
return ob
# ------------------------------------------------------------------ robô
nova("Base", gera_caixa((0.5, 0.5, 0.006)), (0, 0, 0.068), M_MDF_ESC, "Corpo")
nova("Parede_Frente", gera_caixa((0.5, 0.006, 0.07)), (0, 0.247, 0.106), M_MDF, "Corpo")
nova("Parede_Tras", gera_caixa((0.5, 0.006, 0.07)), (0, -0.247, 0.106), M_MDF, "Corpo")
nova("Parede_Dir", gera_caixa((0.006, 0.5, 0.07)), (0.247, 0, 0.106), M_MDF, "Corpo")
nova("Parede_Esq", gera_caixa((0.006, 0.5, 0.07)), (-0.247, 0, 0.106), M_MDF, "Corpo")
nova("Tampo_Base", gera_caixa((0.5, 0.5, 0.006)), (0, 0, 0.144), M_MDF_ESC, "Corpo")
for sx in (-1, 1):
for sy in (-1, 1):
nova("Barra_%d%d" % (sx, sy), gera_cilindro(0.004, 0.98),
(sx * 0.228, sy * 0.228, 0.56), M_METAL, "Corpo")
nova("Arduino", gera_caixa((0.18, 0.12, 0.03)), (-0.1, 0.05, 0.16), M_PCB, "Corpo")
nova("Bateria", gera_caixa((0.1, 0.08, 0.04)), (0.12, -0.05, 0.165), M_BRANCO, "Corpo")
for i, z in enumerate((0.38, 0.64, 0.90)):
nova("Prateleira_%d" % (i + 1), gera_caixa((0.5, 0.5, 0.004)), (0, 0, z), M_MDF, "Corpo")
nova("Borda_%d" % (i + 1), gera_caixa((0.5, 0.006, 0.03)), (0, 0.247, z + 0.017), M_MDF_ESC, "Corpo")
nova("Tampo", gera_caixa((0.5, 0.5, 0.006)), (0, 0, 1.04), M_MDF_ESC, "Corpo")
nova("Sup_Camera", gera_caixa((0.12, 0.14, 0.005)), (0, 0.12, 1.048), M_MDF, "Camera")
nova("Cam_Corpo", gera_caixa((0.06, 0.04, 0.05)), (0, 0.20, 1.08), M_METAL, "Camera")
nova("Cam_Lente", gera_cilindro(0.012, 0.03, "Y"), (0, 0.225, 1.08), M_METAL, "Camera")
nova("Seta", gera_caixa((0.02, 0.06, 0.02)), (0, 0.27, 0.08), M_AMARELO, "Corpo")
RODAS = {
"Roda_FD": (0.19, 0.185),
"Roda_FE": (-0.19, 0.185),
"Roda_TD": (0.19, -0.185),
"Roda_TE": (-0.19, -0.185),
}
for nome, (x, y) in RODAS.items():
nova(nome + "_Pneu", gera_cilindro(0.03, 0.04, "X"), (x, y, 0.03), M_BORRACHA, nome)
nova(nome + "_Cubo", gera_cilindro(0.02, 0.046, "X"), (x, y, 0.03), M_AMARELO, nome)
# ------------------------------------------------------------------ junta em uma malha
bpy.ops.object.select_all(action="DESELECT")
for ob in PECAS:
ob.select_set(True)
bpy.context.view_layer.objects.active = PECAS[0]
bpy.ops.object.join()
robo = bpy.context.view_layer.objects.active
robo.name = "RoboMovel"
robo.data.name = "RoboMovelMesh"
# ------------------------------------------------------------------ UVs (projeção de caixa)
me = robo.data
uv = me.uv_layers.new(name="UVMap")
for poly in me.polygons:
n = poly.normal
ax = max(range(3), key=lambda i: abs(n[i]))
for li in poly.loop_indices:
co = me.vertices[me.loops[li].vertex_index].co
if ax == 0:
u, v = co.y, co.z
elif ax == 1:
u, v = co.x, co.z
else:
u, v = co.x, co.y
uv.data[li].uv = ((u + 0.25) * 2.0, (v + 0.0) * 2.0)
# ------------------------------------------------------------------ armature
arm_data = bpy.data.armatures.new("Armature")
arm = bpy.data.objects.new("Armature", arm_data)
bpy.context.collection.objects.link(arm)
bpy.context.view_layer.objects.active = arm
bpy.ops.object.mode_set(mode="EDIT")
eb = arm_data.edit_bones
def osso(nome, head, tail, pai=None):
b = eb.new(nome)
b.head = Vector(head)
b.tail = Vector(tail)
if pai is not None:
b.parent = eb[pai]
b.use_connect = False
return b
osso("Root", (0, 0, 0.0), (0, 0, 0.12))
osso("Corpo", (0, 0, 0.14), (0, 0, 1.0), "Root")
osso("Camera", (0, 0.12, 1.04), (0, 0.12, 1.16), "Corpo")
for nome, (x, y) in RODAS.items():
osso(nome, (x - 0.03, y, 0.03), (x + 0.03, y, 0.03), "Corpo")
bpy.ops.object.mode_set(mode="OBJECT")
# ------------------------------------------------------------------ skin
robo.parent = arm
robo.matrix_parent_inverse = arm.matrix_world.inverted()
mod = robo.modifiers.new("Armature", "ARMATURE")
mod.object = arm
mod.use_vertex_groups = True
# ------------------------------------------------------------------ exporta
os.makedirs(os.path.dirname(OUT), exist_ok=True)
bpy.ops.object.select_all(action="SELECT")
bpy.ops.export_scene.gltf(
filepath=OUT,
export_format="GLB",
export_apply=False,
export_skins=True,
export_animations=True,
use_selection=False,
)
print("GLB exportado:", OUT)
print("ossos:", [b.name for b in arm_data.bones])
print("grupos:", [g.name for g in robo.vertex_groups])
print("uvs:", [l.name for l in me.uv_layers])