Tudo: Primeiro commit

This commit is contained in:
mguinhos committed 2026-09-30 21:10:51 -03:00
commit 06a90928dc
4633 files changed
+6327263

No files matched your search

@@ -0,0 +1,192 @@
# -*- coding: utf-8 -*-
"""Desenhos em traço (Freestyle) para as pranchas da blueprint.
blender -b -P blueprint_blender.py -- <vista> <saida.png>
vistas: frente, lado, topo, iso, explodida, interno
Ortográficas com 1 px = 1 mm (escala exata) e JSON com pontos-âncora
projetados (px) para cotas e balões: <saida>.json
"""
import bpy, math, os, sys, json
from mathutils import Vector, Euler
from bpy_extras.object_utils import world_to_camera_view
ROOT = os.path.expanduser("~/robo_movel/render")
argv = sys.argv[sys.argv.index("--") + 1:]
VIEW, OUTP = argv[0], argv[1]
CACHE = os.path.join(ROOT, "robo_bp_import.blend") # malha leve p/ traço
bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene
with bpy.data.libraries.load(CACHE, link=False) as (src, dst):
dst.objects = src.objects
for o in dst.objects:
scn.collection.objects.link(o)
objs = list(dst.objects)
# ---------------------------------------------------------------- material chapado branco
white = bpy.data.materials.new("Branco")
white.use_nodes = True
nt = white.node_tree
for n in list(nt.nodes):
nt.nodes.remove(n)
em = nt.nodes.new("ShaderNodeEmission")
em.inputs["Color"].default_value = (1, 1, 1, 1)
out = nt.nodes.new("ShaderNodeOutputMaterial")
nt.links.new(em.outputs[0], out.inputs[0])
for o in objs:
o.data.materials.clear()
o.data.materials.append(white)
def bbox_world(o):
pts = [o.matrix_world @ Vector(c) for c in o.bound_box]
return (min(p.x for p in pts), max(p.x for p in pts), min(p.y for p in pts), max(p.y for p in pts),
min(p.z for p in pts), max(p.z for p in pts))
def inside_box(o):
x0, x1, y0, y1, z0, z1 = bbox_world(o)
return x0 > -0.2425 and x1 < 0.2425 and y0 > -0.2425 and y1 < 0.2425 and z0 > 0.0683 and z1 < 0.1385
def hide(o):
o.hide_render = True
o.hide_viewport = True
# ---------------------------------------------------------------- visibilidade por vista
if VIEW in ("frente", "lado", "topo", "iso", "explodida"):
for o in objs:
if inside_box(o):
hide(o)
if VIEW == "interno":
for o in objs:
x0, x1, y0, y1, z0, z1 = bbox_world(o)
if z0 > 0.137 or o.name.startswith(("Tampo", "Prat_", "Barra_", "M8arrL_t", "M8porca_t", "M8nyl_t")):
hide(o)
# ---------------------------------------------------------------- explodida
EXPL = []
if VIEW == "explodida":
def move(prefixes, d):
for o in objs:
if o.name.startswith(prefixes):
o.location += Vector(d)
move(("Prat_Topo",), (0, 0, 0.30))
move(("Prat_Meio",), (0, 0, 0.16))
move(("Tampo", "M8arrL_t_", "M8porca_t_", "M8arrL_t2_", "M8nyl_t2_"), (0, 0, 0.09))
move(("Barra_",), (0, 0, 0.0))
for s, sx in (("D", 1), ("E", -1)):
move(tuple("%s_%s" % (p, s) for p in ("Roda",)), (0.13 * sx, 0, -0.02))
move(tuple("%s_%s" % (p, s) for p in ("Motor", "Suporte", "M3x6_mot", "M4x25", "Calco", "Cabo")), (0, 0, -0.11))
bpy.context.view_layer.update()
# ---------------------------------------------------------------- render (Eevee + Freestyle)
scn.render.engine = "BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items.keys() else "BLENDER_EEVEE"
scn.view_settings.view_transform = "Standard"
world = bpy.data.worlds.new("W")
scn.world = world
world.use_nodes = True
world.node_tree.nodes["Background"].inputs["Color"].default_value = (1, 1, 1, 1)
scn.render.film_transparent = False
scn.render.use_freestyle = True
scn.render.line_thickness_mode = "ABSOLUTE"
scn.render.line_thickness = 1.3
vl = scn.view_layers[0]
vl.use_freestyle = True
fs = vl.freestyle_settings
fs.crease_angle = math.radians(140)
ls = fs.linesets[0] if fs.linesets else fs.linesets.new("L")
ls.select_by_visibility = True
ls.visibility = "VISIBLE"
ls.select_silhouette = True
ls.select_border = True
ls.select_crease = True
ls.select_external_contour = True
if ls.linestyle is None:
ls.linestyle = bpy.data.linestyles.new("Traço")
ls.linestyle.color = (0.05, 0.05, 0.07)
ls.linestyle.thickness = 1.3
scn.render.image_settings.file_format = "PNG"
scn.render.image_settings.color_mode = "RGB"
cam_d = bpy.data.cameras.new("C")
cam_d.type = "ORTHO"
cam = bpy.data.objects.new("C", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
# 1 px = 1 mm nas ortográficas
def ortho(w_mm, h_mm, loc, rot, center):
scn.render.resolution_x, scn.render.resolution_y = int(w_mm), int(h_mm)
scn.render.resolution_percentage = 100
cam_d.ortho_scale = max(w_mm, h_mm) / 1000.0
cam.location = Vector(loc) + Vector(center)
cam.rotation_euler = Euler(rot, "XYZ")
C = Vector((0, 0, 0.53))
if VIEW == "frente": # olhando da frente (+Y) para trás
ortho(700, 1200, (0, 3, 0), (math.radians(90), 0, math.radians(180)), C)
elif VIEW == "lado": # lado direito (+X)
ortho(700, 1200, (3, 0, 0), (math.radians(90), 0, math.radians(90)), C)
elif VIEW == "topo":
ortho(700, 700, (0, 0, 3), (0, 0, 0), Vector((0, 0, 0)))
elif VIEW == "interno":
ortho(560, 560, (0, 0, 3), (0, 0, 0), Vector((0, 0, 0)))
scn.render.resolution_percentage = 400 # 4 px/mm (desenho detalhado)
scn.render.line_thickness = 1.0
else: # iso / explodida
scn.render.resolution_x, scn.render.resolution_y = (2000, 2600) if VIEW == "explodida" else (1600, 2000)
scn.render.resolution_percentage = 100
cam_d.ortho_scale = 1.95 if VIEW == "explodida" else 1.45
target = Vector((0, 0, 0.62 if VIEW == "explodida" else 0.53))
az, el = math.radians(145), math.radians(28)
cam.location = target + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) * 6
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
scn.render.filepath = OUTP
bpy.context.view_layer.update()
# pontos-âncora projetados (para cotas/balões)
def proj(p):
v = world_to_camera_view(scn, cam, Vector(p))
rx = scn.render.resolution_x * scn.render.resolution_percentage / 100
ry = scn.render.resolution_y * scn.render.resolution_percentage / 100
return [v.x * rx, (1 - v.y) * ry]
def center_of(prefixes):
pts = []
for o in objs:
if o.name.startswith(prefixes) and not o.hide_render:
x0, x1, y0, y1, z0, z1 = bbox_world(o)
pts.append(Vector(((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)))
if not pts:
return None
return sum(pts, Vector()) / len(pts)
anchors = {}
for key, pref in {
"base": ("Parede_Frontal",), "tampo": ("Tampo",), "prat_meio": ("Prat_Meio_Placa",), "prat_topo": ("Prat_Topo_Placa",),
"barra": ("Barra_EF",), "borboleta": ("Prat_Topo_borb_EF",), "roda": ("Roda_EF",), "motor": ("Motor_EF",),
"suporte": ("Suporte_EF",), "calco": ("Calco_EF",), "porca_base": ("M8nyl_b_EF",), "borda": ("Prat_Meio_Borda_F",),
"nervura": ("Prat_Topo_Nervura_X",), "cam": ("ESP32CAM",), "chave": ("Chave",), "arduino": ("CNCShield",),
"pb1": ("Protoboard_1",), "pb2": ("Protoboard_2",), "bateria": ("Bateria",), "lm": ("LM2596",),
"wago": ("Wago_pos",), "xt60": ("XT60",), "fusivel": ("PortaFusivel",), "motor_int": ("Motor_DT",),
}.items():
c = center_of(pref)
if c is not None:
anchors[key] = proj(c)
# pontos geométricos para cotas
for key, p in {"z0": (0, 0.25, 0), "z_tampo": (0, 0.25, 0.14138), "z_meio": (0, 0.25, 0.580), "z_topo": (0, 0.25, 1.020),
"z_max": (0, 0.25, 1.060), "x_min": (-0.25, 0.25, 0), "x_max": (0.25, 0.25, 0),
"roda_f": (0.2317, 0.185, 0.03), "roda_t": (0.2317, -0.185, 0.03), "roda_e": (-0.2317, 0.185, 0.03)}.items():
anchors[key] = proj(p)
json.dump({"view": VIEW, "res": [scn.render.resolution_x * scn.render.resolution_percentage // 100,
scn.render.resolution_y * scn.render.resolution_percentage // 100],
"anchors": anchors}, open(OUTP + ".json", "w"), indent=1)
bpy.ops.render.render(write_still=True)
print("salvo", OUTP)
+264
View File
@@ -0,0 +1,264 @@
# -*- coding: utf-8 -*-
"""Cena Blender do robô (rodar: blender -b -P cena_blender.py -- <modo> <saida> [opções])
modos:
campus : robô sobre o caminho da foto unicap_22 (fundo transparente + shadow catcher)
estudio : robô isolado, iluminação de estúdio, fundo transparente (para slides)
"""
import bpy, bmesh, math, os, sys, json
from mathutils import Vector, Euler
ROOT = os.path.expanduser("~/robo_movel/render")
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
MODE = argv[0] if argv else "campus"
OUTP = argv[1] if len(argv) > 1 else os.path.join(ROOT, "teste.png")
OPTS = dict(a.split("=") for a in argv[2:])
RES = float(OPTS.get("res", "0.25"))
SPP = int(OPTS.get("spp", "64"))
# ------------------------------------------------------------------ cena limpa
bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene
scn.unit_settings.system = "METRIC"
# ------------------------------------------------------------------ importa robô (cache .blend)
CACHE = os.path.join(ROOT, "robo_import.blend")
def import_robot():
if os.path.exists(CACHE):
with bpy.data.libraries.load(CACHE, link=False) as (src, dst):
dst.objects = src.objects
col = bpy.data.collections.new("Robo")
scn.collection.children.link(col)
for o in dst.objects:
col.objects.link(o)
return list(dst.objects)
bpy.ops.wm.obj_import(filepath=os.path.join(ROOT, "robo.obj"), up_axis="Z", forward_axis="Y")
objs = [o for o in scn.objects if o.type == "MESH"]
for o in objs:
bm = bmesh.new()
bm.from_mesh(o.data)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
bm.to_mesh(o.data)
bm.free()
me = o.data
if hasattr(me, "set_sharp_from_angle"):
me.shade_smooth()
me.set_sharp_from_angle(angle=math.radians(35))
# salva cache (só os objetos do robô)
bpy.data.libraries.write(CACHE, set(objs), fake_user=True)
return objs
objs = import_robot()
# ------------------------------------------------------------------ materiais
def principled(name, color, rough=0.45, metal=0.0, spec=0.5, alpha=1.0, coat=0.0, transm=0.0):
m = bpy.data.materials.get("R_" + name) or bpy.data.materials.new("R_" + name)
m.use_nodes = True
nt = m.node_tree
b = nt.nodes.get("Principled BSDF")
b.inputs["Base Color"].default_value = (*color, 1)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
if "Coat Weight" in b.inputs:
b.inputs["Coat Weight"].default_value = coat
if "Transmission Weight" in b.inputs:
b.inputs["Transmission Weight"].default_value = transm
b.inputs["Alpha"].default_value = alpha
return m, nt, b
def srgb(c):
return tuple(((x + 0.055) / 1.055) ** 2.4 if x > 0.04045 else x / 12.92 for x in c)
def mdf_material():
m, nt, b = principled("mdf", srgb((0.74, 0.58, 0.40)), rough=0.72)
tc = nt.nodes.new("ShaderNodeTexCoord")
noise = nt.nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = 180.0
noise.inputs["Detail"].default_value = 8.0
ramp = nt.nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (*srgb((0.52, 0.36, 0.22)), 1)
ramp.color_ramp.elements[1].color = (*srgb((0.66, 0.48, 0.31)), 1)
nt.links.new(tc.outputs["Object"], noise.inputs["Vector"])
nt.links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
nt.links.new(ramp.outputs["Color"], b.inputs["Base Color"])
bump = nt.nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = 0.08
nt.links.new(noise.outputs["Fac"], bump.inputs["Height"])
nt.links.new(bump.outputs["Normal"], b.inputs["Normal"])
return m
MATS = {
"mdf": mdf_material,
"preto": lambda: principled("preto", (0.012, 0.012, 0.013), 0.42)[0],
"grafite": lambda: principled("grafite", (0.03, 0.03, 0.035), 0.5)[0],
"borracha": lambda: principled("borracha", (0.035, 0.035, 0.04), 0.85)[0],
"aco": lambda: principled("aco", (0.55, 0.56, 0.58), 0.28, 1.0)[0],
"zincado": lambda: principled("zincado", (0.40, 0.41, 0.43), 0.5, 1.0)[0],
"aluminio": lambda: principled("aluminio", (0.80, 0.81, 0.83), 0.22, 1.0)[0],
"aco_preto": lambda: principled("aco_preto", (0.035, 0.035, 0.04), 0.35, 0.85)[0],
"latao": lambda: principled("latao", (0.78, 0.60, 0.25), 0.3, 1.0)[0],
"ouro": lambda: principled("ouro", (0.90, 0.68, 0.25), 0.25, 1.0)[0],
"cobre": lambda: principled("cobre", (0.85, 0.45, 0.25), 0.3, 1.0)[0],
"pcb_azul": lambda: principled("pcb_azul", srgb((0.03, 0.22, 0.55)), 0.3, coat=0.4)[0],
"pcb_verm": lambda: principled("pcb_verm", srgb((0.72, 0.06, 0.05)), 0.3, coat=0.4)[0],
"pcb_preto": lambda: principled("pcb_preto", (0.01, 0.01, 0.012), 0.3, coat=0.4)[0],
"pcb_verde": lambda: principled("pcb_verde", srgb((0.05, 0.33, 0.14)), 0.3, coat=0.4)[0],
}
def mat_for(name, kd, d):
base = name.replace("_transp", "")
if base in MATS:
m = MATS[base]() if callable(MATS[base]) else MATS[base]
MATS[base] = m
return m
m, nt, b = principled(name, srgb(kd), 0.4)
if name.endswith("_transp"):
b.inputs["Alpha"].default_value = max(0.25, d)
if "Transmission Weight" in b.inputs:
b.inputs["Transmission Weight"].default_value = 0.6
return m
kd = {}
mtl = os.path.join(ROOT, "robo.mtl")
cur = None
for line in open(mtl):
s = line.split()
if not s:
continue
if s[0] == "newmtl":
cur = s[1]
kd[cur] = [(0.5, 0.5, 0.5), 1.0]
elif s[0] == "Kd":
kd[cur][0] = tuple(map(float, s[1:4]))
elif s[0] == "d":
kd[cur][1] = float(s[1])
for o in objs:
for slot in o.material_slots:
if slot.material is None:
continue
nm = slot.material.name.split(".")[0]
if nm.startswith("R_"):
continue
c, dd = kd.get(nm, [(0.5, 0.5, 0.5), 1.0])
slot.material = mat_for(nm, c, dd)
import collections
print("MATERIAIS_EM_USO", collections.Counter(s.material.name for o in objs for s in o.material_slots if s.material).most_common(8))
# ------------------------------------------------------------------ render
scn.render.engine = "CYCLES"
prefs = bpy.context.preferences.addons["cycles"].preferences
for dev in ("OPTIX", "CUDA"):
try:
prefs.compute_device_type = dev
prefs.get_devices()
for dv in prefs.devices:
dv.use = True
scn.cycles.device = "GPU"
print("dispositivo", dev)
break
except Exception as ex:
print("sem", dev, ex)
scn.cycles.samples = SPP
scn.cycles.use_denoising = True
scn.render.film_transparent = True
scn.view_settings.view_transform = "AgX"
scn.view_settings.look = "AgX - Medium High Contrast"
scn.view_settings.exposure = float(OPTS.get("exp", "0"))
scn.render.image_settings.file_format = "PNG"
scn.render.image_settings.color_mode = "RGBA"
# robô: centro da base na origem
rob = bpy.data.objects.new("RoboRoot", None)
scn.collection.objects.link(rob)
for o in objs:
o.parent = rob
world = bpy.data.worlds.new("Mundo")
scn.world = world
world.use_nodes = True
wn = world.node_tree
bg = wn.nodes.get("Background")
sky = wn.nodes.new("ShaderNodeTexSky")
try:
sky.sky_type = "NISHITA"
except Exception:
pass
sky.sun_elevation = math.radians(55)
if hasattr(sky, "sun_disc"):
sky.sun_disc = False # o sol vem da lâmpada SUN (evita luz dobrada)
sky.sun_rotation = math.radians(float(OPTS.get("sunrot", "210")))
wn.links.new(sky.outputs["Color"], bg.inputs["Color"])
bg.inputs["Strength"].default_value = float(OPTS.get("sky", "0.12"))
if MODE == "campus":
W, H = 4160, 2773
scn.render.resolution_x, scn.render.resolution_y = W, H
scn.render.resolution_percentage = int(RES * 100)
cam_d = bpy.data.cameras.new("Cam")
cam_d.sensor_fit = "HORIZONTAL"
cam_d.sensor_width = 36.0
cam_d.lens = float(OPTS.get("lens", "30"))
cam = bpy.data.objects.new("Cam", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
cam.location = (0, 0, float(OPTS.get("camh", "1.45")))
cam.rotation_euler = Euler((math.radians(90 + float(OPTS.get("tilt", "5.5"))), 0, 0), "XYZ")
# robô no caminho: distância e deslocamento lateral
rob.location = (float(OPTS.get("rx", "-0.25")), float(OPTS.get("ry", "6.0")), 0)
rob.rotation_euler = (0, 0, math.radians(float(OPTS.get("rrot", "155")))) # frente (câmera) virada p/ a câmera
# régua opcional: blocos 20 x 10 cm (piso intertravado) ao lado do robô
if OPTS.get("regua"):
for k in range(int(OPTS.get("regua"))):
bpy.ops.mesh.primitive_cube_add(size=1)
b = bpy.context.active_object
b.scale = (0.10, 0.20, 0.004)
b.location = (rob.location.x + 0.45 + (k % 2) * 0.105, rob.location.y - 0.3 + (k // 2) * 0.205, 0.002)
b.data.materials.append(principled("regua%d" % (k % 2), (0.9, 0.1, 0.1) if k % 2 else (0.1, 0.1, 0.9), 0.5)[0])
# plano coletor de sombra
bpy.ops.mesh.primitive_plane_add(size=40, location=(0, 10, 0))
gp = bpy.context.active_object
gp.is_shadow_catcher = True
gp.data.materials.append(principled("chao", (0.45, 0.43, 0.40), 0.9)[0])
# sol suave (dia nublado claro)
sun_d = bpy.data.lights.new("Sol", "SUN")
sun_d.energy = float(OPTS.get("sun", "2.2"))
sun_d.angle = math.radians(float(OPTS.get("sunang", "25")))
sun = bpy.data.objects.new("Sol", sun_d)
scn.collection.objects.link(sun)
sun.rotation_euler = Euler((math.radians(35), 0, math.radians(float(OPTS.get("sunrot", "210")))), "XYZ")
else:
scn.render.resolution_x, scn.render.resolution_y = int(OPTS.get("w", "2000")), int(OPTS.get("h", "2400"))
scn.render.resolution_percentage = int(RES * 100)
cam_d = bpy.data.cameras.new("Cam")
cam_d.lens = float(OPTS.get("lens", "85"))
cam = bpy.data.objects.new("Cam", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
target = Vector((0, 0, 0.52))
az, el, dist = math.radians(float(OPTS.get("az", "142"))), math.radians(float(OPTS.get("el", "20"))), float(OPTS.get("dist", "5.2"))
cam.location = target + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) * dist
d = target - cam.location
cam.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
# chão: coletor de sombra (sombra suave no PNG transparente)
bpy.ops.mesh.primitive_plane_add(size=20, location=(0, 0, 0))
gp = bpy.context.active_object
gp.is_shadow_catcher = True
for nm, e, loc, size in (("Key", 900, (-2.5, -2.8, 3.2), 2.5), ("Fill", 300, (3.0, -1.5, 1.8), 3.0), ("Rim", 600, (0.5, 3.2, 2.8), 2.0)):
ld = bpy.data.lights.new(nm, "AREA")
ld.energy = e * float(OPTS.get("lux", "1.0"))
ld.size = size
lo = bpy.data.objects.new(nm, ld)
scn.collection.objects.link(lo)
lo.location = loc
lo.rotation_euler = (Vector((0, 0, 0.5)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
scn.render.filepath = OUTP
bpy.ops.render.render(write_still=True)
print("salvo", OUTP)
+7
View File
@@ -0,0 +1,7 @@
"""Compõe render RGBA (com sombra do shadow catcher) sobre a foto de fundo."""
import sys
from PIL import Image
fg, bgp, out = sys.argv[1:4]
f = Image.open(fg).convert("RGBA")
b = Image.open(bgp).convert("RGBA").resize(f.size, Image.LANCZOS)
Image.alpha_composite(b, f).convert("RGB").save(out, quality=95)
@@ -0,0 +1,11 @@
import bpy, bmesh, os
bpy.ops.wm.read_factory_settings(use_empty=True)
R = os.path.expanduser("~/robo_movel/render")
bpy.ops.wm.obj_import(filepath=os.path.join(R, "robo_bp.obj"), up_axis="Z", forward_axis="Y")
objs = [o for o in bpy.context.scene.objects if o.type == "MESH"]
for o in objs:
bm = bmesh.new(); bm.from_mesh(o.data)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
bm.to_mesh(o.data); bm.free()
bpy.data.libraries.write(os.path.join(R, "robo_bp_import.blend"), set(objs), fake_user=True)
print("ok", len(objs), sum(len(o.data.vertices) for o in objs))
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
cd ~/robo_movel/render
blender -b -P cena_blender.py -- campus final/campus_rgba.png res=1.0 spp=256 sun=1.5 sunang=50 sky=0.2 exp=-0.2 camh=2.15 tilt=7.8 lens=30 ry=9.0 rx=-1.2 2>&1 | grep -E "salvo|Traceback|Error"
python3 compoe.py final/campus_rgba.png fundos/unicap_22.jpg final/robo_unicap_biblioteca.jpg
python3 - <<'PY'
from PIL import Image
import numpy as np
c = Image.open('final/robo_unicap_biblioteca.jpg'); w, h = c.size
a = np.array(Image.open('final/campus_rgba.png'))[:, :, 3]
ys, xs = np.where(a > 200)
cx = (xs.min() + xs.max()) // 2
ch = int((ys.max() - ys.min()) / 0.42); cw = int(ch * 16 / 9)
x0 = max(0, min(w - cw, cx - cw // 2)); y1 = min(h, ys.max() + int(ch * 0.10)); y0 = y1 - ch
c.crop((x0, y0, x0 + cw, y1)).save('final/robo_unicap_16x9.jpg', quality=95)
print("corte", cw, ch)
PY
blender -b -P cena_blender.py -- estudio final/robo_estudio.png res=1.0 spp=256 lux=0.18 2>&1 | grep -E "salvo|Traceback|Error"
echo FIM
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
"""Ilustrações passo a passo do manual (traço Freestyle, peças novas em laranja).
blender -b -P passos_blender.py -- <pasta_saida> [passo ...]"""
import bpy, math, os, sys
from mathutils import Vector, Euler
R = os.path.expanduser("~/robo_movel/render")
argv = sys.argv[sys.argv.index("--") + 1:]
OUT = argv[0]
ONLY = set(argv[1:])
os.makedirs(OUT, exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene
with bpy.data.libraries.load(os.path.join(R, "robo_bp_import.blend"), link=False) as (src, dst):
dst.objects = src.objects
for o in dst.objects:
scn.collection.objects.link(o)
bpy.ops.wm.obj_import(filepath=os.path.join(R, "robo_fios.obj"), up_axis="Z", forward_axis="Y")
objs = [o for o in scn.objects if o.type == "MESH"]
HOME = {o.name: o.location.copy() for o in objs}
def emit(name, rgb):
m = bpy.data.materials.new(name)
m.use_nodes = True
nt = m.node_tree
for n in list(nt.nodes):
nt.nodes.remove(n)
e = nt.nodes.new("ShaderNodeEmission")
e.inputs["Color"].default_value = (*rgb, 1)
o = nt.nodes.new("ShaderNodeOutputMaterial")
nt.links.new(e.outputs[0], o.inputs[0])
return m
M_OLD = emit("velho", (1, 1, 1))
M_NEW = emit("novo", (1.0, 0.62, 0.38))
# ------------------------------------------------------------------ grupos (na ordem de montagem)
def pref(*p):
return lambda n: n.startswith(p)
G = [
("base", pref("Base", "Nervura_"), (0, 0, 0.05)),
("paredes", pref("Parede_"), "radial"),
("cam_sup", pref("Suporte_Cam_"), (0, 0, 0.05)),
("calcos", pref("Calco_", "Suporte_DF", "Suporte_DT", "Suporte_EF", "Suporte_ET", "M4x25_", "M4arr_", "M4porca_"), (0, 0, -0.07)),
("motores", pref("Motor_", "M3x6_mot_"), "motor"),
("rodas", pref("Roda_"), "roda"),
("barras", pref("Barra_", "M8nyl_b_", "M8arrL_b_", "M8arrL_b2_", "M8porca_b2_"), (0, 0, 0.18)),
("arduino", pref("Esp_uno", "M3x8_uno", "M3x6_uno", "ArduinoUNO"), (0, 0, 0.05)),
("shield", pref("CNCShield"), (0, 0, 0.045)),
("drivers", pref("A4988_"), (0, 0, 0.035)),
("placas", pref("Protoboard_", "ESP32CAM", "Abracadeira"), (0, 0, 0.05)),
("energia", pref("Bateria", "Cinta", "LM2596", "Esp_lm", "M3x6_lm", "M3x8_lm", "Chave", "Wago_", "XT60", "PortaFusivel"), (0, 0, 0.05)),
("cabos_mot", pref("Cabo_"), (0, 0, 0.0)),
("fiacao", lambda n: not n.startswith(("Cabo_",)) and n.split("__")[0] in FIOS, (0, 0, 0.0)),
("tampo", pref("Tampo", "M8arrL_t_", "M8porca_t_", "M8arrL_t2_", "M8nyl_t2_"), (0, 0, 0.12)),
("prat", pref("Prat_"), (0, 0, 0.14)),
]
# objetos vindos do OBJ de fios: os que não estavam no .blend leve
FIOS = {o.name for o in objs if o.name not in {x.name for x in dst.objects}}
# fios são tubos muito densos: simplifica (no traço não faz diferença)
for o in objs:
if o.name in FIOS and len(o.data.vertices) > 500:
md = o.modifiers.new("dec", "DECIMATE")
md.ratio = 0.15
bpy.context.view_layer.objects.active = o
bpy.ops.object.modifier_apply(modifier="dec")
def group_of(n):
for i, (k, f, _) in enumerate(G):
if f(n):
return i
return None
GI = {o.name: group_of(o.name) for o in objs}
# câmera por passo: (tipo, alvo z, escala, elevação)
CAM = {"base": ("iso", 0.10, 0.85, 32), "paredes": ("iso", 0.10, 0.85, 32), "cam_sup": ("frente", 0.10, 0.70, 30),
"calcos": ("baixo", 0.07, 0.9, -28), "motores": ("baixo", 0.05, 0.9, -24), "rodas": ("iso", 0.07, 0.9, 20),
"barras": ("iso", 0.62, 1.75, 22), "arduino": ("int", 0.10, 0.34, 55), "shield": ("int", 0.10, 0.30, 50),
"drivers": ("int", 0.10, 0.28, 55), "placas": ("int", 0.10, 0.72, 62), "energia": ("int", 0.10, 0.72, 62),
"cabos_mot": ("int", 0.10, 0.80, 58), "fiacao": ("int", 0.10, 0.80, 62), "tampo": ("iso", 0.20, 0.95, 30),
"prat": ("iso", 0.66, 1.95, 22)}
HIDE_FOR_INT = pref("Barra_", "M8")
def offset_for(o, spec, s=1.0):
if isinstance(spec, tuple):
return Vector(spec) * s
c = sum((o.matrix_world @ Vector(v) for v in o.bound_box), Vector()) / 8
if spec == "radial":
d = Vector((c.x, c.y, 0))
return (Vector((1 if d.x > 0 else -1, 0, 0)) if abs(d.x) > abs(d.y) else Vector((0, 1 if d.y > 0 else -1, 0))) * 0.07 * s
if spec == "motor":
return Vector((-0.07 if c.x > 0 else 0.07, 0, 0)) * s
if spec == "roda":
return Vector((0.08 if c.x > 0 else -0.08, 0, 0)) * s
return Vector()
# ------------------------------------------------------------------ render
scn.render.engine = "BLENDER_EEVEE"
scn.view_settings.view_transform = "Standard"
w = bpy.data.worlds.new("W")
scn.world = w
w.use_nodes = True
w.node_tree.nodes["Background"].inputs["Color"].default_value = (1, 1, 1, 1)
scn.render.use_freestyle = True
scn.render.line_thickness_mode = "ABSOLUTE"
scn.render.line_thickness = 1.4
fs = scn.view_layers[0].freestyle_settings
fs.crease_angle = math.radians(140)
ls = fs.linesets[0] if fs.linesets else fs.linesets.new("L")
if ls.linestyle is None:
ls.linestyle = bpy.data.linestyles.new("T")
ls.linestyle.color = (0.05, 0.05, 0.07)
for a in ("select_silhouette", "select_border", "select_crease", "select_external_contour"):
setattr(ls, a, True)
scn.render.resolution_x, scn.render.resolution_y = 1600, 1200
scn.render.image_settings.file_format = "PNG"
cam_d = bpy.data.cameras.new("C")
cam_d.type = "ORTHO"
cam = bpy.data.objects.new("C", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
for k, (key, f, spec) in enumerate(G):
if ONLY and key not in ONLY:
continue
kind, tz, scale, el = CAM[key]
for o in objs:
gi = GI[o.name]
o.location = HOME[o.name]
vis = gi is not None and gi <= k
if kind == "int" and (o.name.startswith(("Tampo", "Prat_")) or HIDE_FOR_INT(o.name)):
vis = False
if key in ("tampo", "prat") and o.name in FIOS and not o.name.startswith(("Cabo_", "Chave")):
vis = False # fiação fica dentro da caixa fechada
o.hide_render = not vis
o.data.materials.clear()
o.data.materials.append(M_NEW if gi == k else M_OLD)
if gi == k:
o.location = HOME[o.name] + offset_for(o, spec)
bpy.context.view_layer.update()
cam_d.ortho_scale = scale
if kind == "frente":
target, az = Vector((0, 0.12, tz)), math.radians(160)
elif kind == "int" and key in ("arduino", "shield", "drivers"):
target, az = Vector((0, -0.20, tz)), math.radians(150)
else:
target, az = Vector((0, 0, tz)), math.radians(145)
e = math.radians(el)
cam.location = target + Vector((math.sin(az) * math.cos(e), -math.cos(az) * math.cos(e), math.sin(e))) * 6
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
scn.render.filepath = os.path.join(OUT, "passo_%02d_%s.png" % (k + 1, key))
bpy.ops.render.render(write_still=True)
print("salvo", scn.render.filepath, flush=True)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Renderiza cada componente separado (projeto/render/componentes/*.obj) com o minirender.
# Uso: render_componentes.sh [pasta_saida] [opções extras do minirender]
set -euo pipefail
AQUI="$(cd "$(dirname "$0")" && pwd)"
PROJ="$(cd "$AQUI/../../.." && pwd)"
SAIDA="${1:-$PROJ/documentacao/requisitos/res/png/componentes}"
shift || true
"$PROJ/.venv/bin/python" "$AQUI/minirender.py" render "$PROJ"/projeto/render/componentes/*.obj \
-v iso --size 640 --ssaa 3 --outdir "$SAIDA" -o "{nome}.png" \
--shader "aco,aco_preto,zincado,aluminio,latao,ouro,cobre=$AQUI/shaders/metal.py" \
--shader "mdf*=$AQUI/shaders/mdf.py" \
--shader "pcb_*=$AQUI/shaders/pcb.py" \
"$@"
+40
View File
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
"""MDF cortado a laser: fibras em ruído 3D nas faces e borda queimada (escura) nas faces de corte.
A face de corte é detectada pela espessura: o eixo mais fino da caixa de cada objeto.
Parâmetros: mdf_fibra (frequência das fibras em 1/unidade, padrão 900), mdf_queima (0..1, padrão 0,75)."""
import numpy as np
from minirender import lambert, blinn, mistura
_EIXO = {}
def eixo_fino(m):
if id(m) not in _EIXO:
eixos = np.zeros(len(m.objs), np.int64)
for o in range(len(m.objs)):
f = m.F[m.FO == o]
if len(f):
v = m.V[f.reshape(-1)]
eixos[o] = int(np.argmin(v.max(0) - v.min(0)))
_EIXO[id(m)] = eixos
return _EIXO[id(m)]
def shade(s):
freq = float(s.params.get("mdf_fibra", 900.0))
queima = float(s.params.get("mdf_queima", 0.75))
n1 = s.ruido(s.P * np.array([1.0, 1.0, 1.0]), freq)
n2 = s.ruido(s.P, freq * 7.3)
var = 0.82 + 0.22 * n1 + 0.10 * n2
a = s.albedo * var[:, None]
if s.malha is not None:
eixo = eixo_fino(s.malha)[s.objeto]
ng = np.abs(s.Ng[np.arange(len(s)), eixo])
borda = ng < 0.5
tom = np.array([0.10, 0.055, 0.03]) * (0.8 + 0.4 * n2[:, None])
a = np.where(borda[:, None], mistura(a, tom, queima), a)
cor = a * mistura(s.chao, s.ceu, s.N[:, 2] * 0.5 + 0.5)
for luz in s.luzes:
sh = np.asarray(luz.sombra)[..., None] if np.ndim(luz.sombra) else luz.sombra
cor = cor + (a * lambert(s.N, luz.dir)[:, None] + 0.02 * blinn(s.N, luz.dir, s.V, 12.0)[:, None]) * luz.cor * sh
return cor
@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
"""Metal (aço, zincado, alumínio, latão...): o albedo vira a cor do reflexo (f0).
Parâmetros: metal_rugosidade (0 espelho .. 1 fosco, padrão 0,35)."""
import numpy as np
from minirender import blinn, fresnel, mistura, reflete
def shade(s):
rug = float(s.params.get("metal_rugosidade", 0.35))
f0 = s.albedo
N, V = s.N, s.V
F = fresnel(N, V, f0)
env = s.ambiente(reflete(N, V))
env = mistura(env, np.full_like(env, env.mean(1, keepdims=True).mean()), rug * 0.6) # borra o ambiente
cor = F * env * 0.85 + f0 * 0.10 * mistura(s.chao, s.ceu, N[:, 2] * 0.5 + 0.5)
brilho = 8 + (1 - rug) ** 2 * 400
for luz in s.luzes:
sh = np.asarray(luz.sombra)[..., None] if np.ndim(luz.sombra) else luz.sombra
cor = cor + f0 * blinn(N, luz.dir, V, brilho)[:, None] * luz.cor * sh * 0.8 \
+ f0 * 0.15 * np.clip(N @ luz.dir, 0, None)[:, None] * luz.cor * sh
return cor
+19
View File
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
"""Placa de circuito: máscara de solda difusa com verniz brilhante por cima (clearcoat).
Parâmetros: pcb_verniz (intensidade do verniz, padrão 1)."""
import numpy as np
from minirender import lambert, blinn, fresnel, mistura, reflete
def shade(s):
k = float(s.params.get("pcb_verniz", 1.0))
a = s.albedo
N, V = s.N, s.V
cor = a * mistura(s.chao, s.ceu, N[:, 2] * 0.5 + 0.5)
F = fresnel(N, V, 0.05)[:, None]
cor = cor + F * s.ambiente(reflete(N, V)) * k
for luz in s.luzes:
sh = np.asarray(luz.sombra)[..., None] if np.ndim(luz.sombra) else luz.sombra
cor = cor + (a * lambert(N, luz.dir)[:, None] * (1 - F * 0.5)
+ 0.25 * k * blinn(N, luz.dir, V, 180.0)[:, None]) * luz.cor * sh
return cor