1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
# -*- coding: utf-8 -*-
"""GALTON - 500 bolitas de acero contra 12 filas de clavos.
Reparto del trabajo:
* Blender disena el tablero (clavos, tolva, compuerta, casilleros, bolitas)
y lo exporta a glTF: el nombre de cada objeto le dice a Godot que es.
* Godot (Jolt) simula los rebotes, a 240 Hz, y devuelve la pose de cada
bolita a 30 fps (godot/sim.gd).
* Blender vuelve a leer esas poses y renderiza con los materiales de verdad.
MODO=sim blender -b -P blender/galton.py # exporta y corre Godot
blender -b -P blender/galton.py # renderiza
"""
import math, os, random, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
from base import *
NOMBRE = "galton"
N_BOLAS = 500
RB = 0.012 # radio de la bolita
DX = 0.12 # paso entre clavos
DY = DX * math.sqrt(3) / 2
RP = 0.015 # radio del clavo
FILAS = 12
NB = FILAS + 1 # casilleros
W2 = NB * DX / 2 # medio ancho interior
ALTO_CAS = 0.65 # alto de los separadores
Z_ULT = ALTO_CAS + 0.07 # ultima fila de clavos
Z_FILA = [Z_ULT + (FILAS - 1 - i) * DY for i in range(FILAS)]
Z_SAL = Z_FILA[0] + 0.10 # boca de la tolva
BOCA = float(os.environ.get("T_BOCA", 0.04)) # media boca
TOLVA_X, TOLVA_H, TOLVA_V = 0.33, 0.48, 0.62
PROF = 0.08 # profundidad del canal (Y)
GRAV = float(os.environ.get("T_G", 12.0))
PRE = 2.5 # segundos de fisica antes del frame 1: las bolitas se asientan
BEAT_UNA = 1 # cae una sola bolita
BEAT_SUELTA = 3 # se abre la compuerta
REB = float(os.environ.get("T_REB", 0.10))
AMORT = float(os.environ.get("T_AM", 6.0))
def x_clavos(i):
off = 0.5 if (FILAS - 1 - i) % 2 == 0 else 0.0
xs = []
j = -10
while True:
x = (j + off) * DX
j += 1
if x > W2 - 0.04:
break
if x >= -W2 + 0.04:
xs.append(x)
return xs
# --- diseno -------------------------------------------------------------------
def construir():
sc = escena(muestras=int(os.environ.get("MUESTRAS", 24)))
mundo_estudio(fuerza=0.6)
M = {
"laton": metal("laton", "#D9A441", rug=0.22),
"acero": metal("acero", "#E4E8EE", rug=0.10),
"chapa": metal("chapa", "#A9B2BF", rug=0.30),
"panel": material("panel", "#070B14", rug=0.75),
"madera": madera("madera"),
"base": madera("base", claro="#7A5230", oscuro="#3A2211", escala=3.0),
}
fis = [] # lo que va a Godot
# clavos: cilindros a lo largo de Y, del panel del fondo al vidrio
for i, z in enumerate(Z_FILA):
for k, x in enumerate(x_clavos(i)):
c = cilindro(f"fijo_clavo_{i:02d}_{k:02d}", RP, PROF, M["laton"], lados=24)
c.rotation_euler = (math.pi / 2, 0, 0)
c.location = (x, 0, z)
fis.append(c)
# separadores de los casilleros y paredes
for k in range(NB + 1):
x = (k - NB / 2) * DX
ext = k in (0, NB)
grosor = 0.02 if ext else 0.006
alto = (Z_SAL + 0.02) if ext else ALTO_CAS
xo = x + (-grosor / 2 if k == 0 else grosor / 2 if k == NB else 0)
fis.append(caja(f"caja_sep_{k:02d}", (grosor, PROF, alto), (xo, 0, alto / 2),
M["chapa"]))
fis.append(caja("caja_piso", (2 * W2 + 0.04, PROF, 0.02), (0, 0, -0.01), M["chapa"]))
# tolva: dos planos a 60 grados y un tramo vertical
dx_t, dz_t = TOLVA_X - BOCA, TOLVA_H
largo = math.hypot(dx_t, dz_t)
ang = math.atan2(dz_t, dx_t)
for s in (-1, 1):
cx = s * (BOCA + dx_t / 2)
cz = Z_SAL + dz_t / 2
# el espesor va hacia afuera de la tolva
nx, nz = s * math.sin(ang), -math.cos(ang)
w = caja(f"caja_tolva_{'i' if s < 0 else 'd'}", (largo, PROF, 0.016),
(cx + nx * 0.008, 0, cz + nz * 0.008), M["chapa"])
w.rotation_euler = (0, -s * ang, 0)
fis.append(w)
v = caja(f"caja_tolva_v{'i' if s < 0 else 'd'}", (0.016, PROF, TOLVA_V),
(s * (TOLVA_X + 0.008), 0, Z_SAL + TOLVA_H + TOLVA_V / 2), M["chapa"])
fis.append(v)
compuerta = caja("compuerta_0", (2 * BOCA + 0.04, PROF, 0.012),
(0, 0, Z_SAL - 0.008), M["chapa"])
fis.append(compuerta)
# bolitas: una grilla arriba de la tolva; caen y se acomodan antes del frame 1
me_bola = esfera("bola_malla", RB, M["acero"], seg=20, anillos=12).data
bpy.data.objects.remove(bpy.data.objects["bola_malla"])
bolas = []
rnd = random.Random(7)
paso = 2 * RB * 1.08
por_fila = int((2 * (TOLVA_X - 0.02)) / paso)
sola = objeto("bola_000", me_bola, None) # la que cae sola, retenida bajo la compuerta
sola.location = (0.004, 0, Z_SAL - 0.032)
bolas.append(sola)
for n in range(1, N_BOLAS):
fila, col = divmod(n - 1, por_fila)
x = (col - (por_fila - 1) / 2) * paso + (paso / 2 if fila % 2 else 0) * 0.5
x += rnd.uniform(-0.002, 0.002)
z = Z_SAL + TOLVA_H + 0.03 + fila * paso * 0.95
ob = objeto(f"bola_{n:03d}", me_bola, None)
ob.location = (x, 0, z)
bolas.append(ob)
fis += bolas
# --- lo que es solo visual ---
panel = caja("panel", (2 * W2 + 0.10, 0.02, Z_SAL + TOLVA_H + TOLVA_V + 0.10),
(0, PROF / 2 + 0.01, (Z_SAL + TOLVA_H + TOLVA_V) / 2), M["panel"])
for s in (-1, 1):
caja(f"marco_{s}", (0.07, PROF + 0.06, Z_SAL + 0.12),
(s * (W2 + 0.055), 0.0, (Z_SAL + 0.12) / 2 - 0.02), M["madera"])
caja("base", (2 * W2 + 0.40, 0.36, 0.10), (0, 0.05, -0.07), M["base"])
caja("pie", (2 * W2 + 0.60, 0.50, 0.04), (0, 0.05, -0.14), M["base"])
return dict(fis=fis, bolas=bolas, M=M, compuerta=compuerta)
def simular(T, obj):
f_suelta = T.rango(BEAT_SUELTA)[0]
f_una = T.rango(BEAT_UNA)[0] + 8
cfg = {
"congelados": ["bola_000"],
"duracion": PRE + T.n_frames / FPS + 0.2,
"gravedad": GRAV,
"reglas": {
"bola_": {"friccion": 0.10, "rebote": REB, "densidad": 7800, "ccd": True,
"plano": True, "amortiguar": AMORT, "dormir": False},
"fijo_": {"friccion": 0.10, "rebote": REB},
"caja_": {"friccion": 0.25, "rebote": 0.20},
"compuerta_": {"friccion": 0.25, "rebote": 0.0},
},
"eventos": [{"t": PRE + (f_una - 1) / FPS, "accion": "soltar", "prefijo": "bola_000"},
{"t": PRE + (f_suelta - 1) / FPS, "accion": "quitar", "prefijo": "compuerta_"}],
}
correr_godot(exportar_fisica(NOMBRE, obj["fis"], cfg))
# --- trazos para explicar -----------------------------------------------------
def camino(movs):
"""Polilinea de un camino por la grilla: movs = lista de -1/+1."""
pts = [(0.0, -0.05, Z_SAL - 0.02)]
x = 0.0
for i, m in enumerate(movs):
pts.append((x, -0.05, Z_FILA[i] + RP + RB))
x += m * DX / 2
pts.append((x, -0.05, 0.35))
return pts
def recortar(pts, u):
"""Primeros u (0..1) del largo de la polilinea."""
L = [0.0]
for a, b in zip(pts, pts[1:]):
L.append(L[-1] + math.dist(a, b))
obj_L = u * L[-1]
out = [pts[0]]
for i in range(1, len(pts)):
if L[i] <= obj_L:
out.append(pts[i])
else:
a, b = pts[i - 1], pts[i]
s = (obj_L - L[i - 1]) / max(1e-9, L[i] - L[i - 1])
out.append(tuple(a[k] + (b[k] - a[k]) * s for k in range(3)))
break
while len(out) < len(pts):
out.append(out[-1])
return out
def main():
T = Tiempo(NOMBRE)
obj = construir()
if os.environ.get("MODO") == "sim":
simular(T, obj)
return
idx, D = cargar_sim(NOMBRE)
pre = int(round(PRE * FPS))
bolas = obj["bolas"]
ib = [idx[b.name] for b in bolas]
import numpy as np
xs_fin = D[-1, ib, 0]
zs_fin = D[-1, ib, 2]
cas = np.clip(np.round(xs_fin / DX).astype(int) + FILAS // 2, 0, NB - 1)
cuenta = np.bincount
|