andrefbfreitas commited on
Commit
d761d43
·
verified ·
1 Parent(s): 3b79049
Files changed (1) hide show
  1. app.py +101 -130
app.py CHANGED
@@ -16,18 +16,17 @@ try:
16
  except ImportError:
17
  HAS_FPDF = False
18
 
19
- # Kernel CAD
 
 
 
20
  from OCC.Core.STEPControl import STEPControl_Reader
21
  from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
22
  from OCC.Core.BRepGProp import brepgprop
23
  from OCC.Core.GProp import GProp_GProps
24
  from OCC.Core.StlAPI import StlAPI_Writer
25
 
26
- # --- SETUP DE INFRAESTRUTURA ---
27
- os.environ['PYVISTA_OFF_SCREEN'] = 'true'
28
- os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
29
-
30
- st.set_page_config(page_title="CastingSim V40", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
@@ -55,7 +54,11 @@ if 'sub_div' not in st.session_state: st.session_state.sub_div = 1
55
  if 'liga' not in st.session_state: st.session_state.liga = "SAE 305"
56
  if 't_vaz' not in st.session_state: st.session_state.t_vaz = 720
57
  if 't_molde' not in st.session_state: st.session_state.t_molde = 300
58
- if 'sens' not in st.session_state: st.session_state.sens = 4.0
 
 
 
 
59
 
60
  if 'off_x' not in st.session_state: st.session_state.off_x = 0.0
61
  if 'off_y' not in st.session_state: st.session_state.off_y = 0.0
@@ -64,16 +67,11 @@ if 'p_riser_real' not in st.session_state: st.session_state.p_riser_real = [0.0,
64
  if 'rot_x' not in st.session_state: st.session_state.rot_x = 0
65
  if 'rot_y' not in st.session_state: st.session_state.rot_y = 0
66
  if 'rot_z' not in st.session_state: st.session_state.rot_z = 0
67
-
68
- if 'mat_molde' not in st.session_state: st.session_state.mat_molde = "Aço 1045"
69
- if 'tinta_ceramica' not in st.session_state: st.session_state.tinta_ceramica = True
70
- if 'espessura_tinta' not in st.session_state: st.session_state.espessura_tinta = 5.0
71
- if 'vel_vaz' not in st.session_state: st.session_state.vel_vaz = 1.0
72
- if 'diam_vaz' not in st.session_state: st.session_state.diam_vaz = 20.0
73
 
74
  if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
75
  if 'b64_rechupe_x10' not in st.session_state: st.session_state.b64_rechupe_x10 = ""
76
- if 'b64_solidificacao' not in st.session_state: st.session_state.b64_solidificacao = "" # NOVO
77
  if 'frames_filling' not in st.session_state: st.session_state.frames_filling = []
78
  if 'frames_cooling' not in st.session_state: st.session_state.frames_cooling = []
79
  if 't_sol_minutos' not in st.session_state: st.session_state.t_sol_minutos = 0
@@ -81,40 +79,35 @@ if 't_sol_segundos' not in st.session_state: st.session_state.t_sol_segundos = 0
81
  if 'relatorio_ia' not in st.session_state: st.session_state.relatorio_ia = ""
82
  if 'relatorio_pdf' not in st.session_state: st.session_state.relatorio_pdf = None
83
 
84
- # --- GERADOR DE RELATÓRIO PDF ---
85
  def compilar_pdf():
86
  if not HAS_FPDF: return None
87
  pdf = FPDF()
88
  pdf.add_page()
89
  pdf.set_font("Arial", 'B', 16)
90
- pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V40", 0, 1, 'C')
91
  pdf.ln(5)
92
-
93
  pdf.set_font("Arial", 'B', 12)
94
  pdf.cell(0, 10, "1. Parametros de Processo", 0, 1)
95
  pdf.set_font("Arial", '', 11)
96
  pdf.cell(0, 6, f"Liga: {st.session_state.liga} | Velocidade Vazamento: {st.session_state.vel_vaz} m/s | Derramador Ø: {st.session_state.diam_vaz} mm", 0, 1)
 
97
  pdf.cell(0, 6, f"Molde: Coquilha de {st.session_state.mat_molde}", 0, 1)
98
  if st.session_state.tinta_ceramica:
99
  pdf.cell(0, 6, f"Revestimento: Tinta Ceramica (Espessura: {st.session_state.espessura_tinta} mm)", 0, 1)
100
  pdf.cell(0, 6, f"Temps: Vazamento {st.session_state.t_vaz} C | Coquilha {st.session_state.t_molde} C", 0, 1)
101
  pdf.ln(5)
102
-
103
  pdf.set_font("Arial", 'B', 12)
104
  pdf.cell(0, 10, "2. Resultados Metrologicos", 0, 1)
105
  pdf.set_font("Arial", '', 11)
106
  pdf.cell(0, 6, f"Tempo de Solidificacao: {st.session_state.t_sol_minutos} min e {st.session_state.t_sol_segundos} s", 0, 1)
107
  pdf.ln(5)
108
-
109
  pdf.set_font("Arial", 'B', 12)
110
  pdf.cell(0, 10, "3. Diagnostico IA (Mestre Fundidor)", 0, 1)
111
  pdf.set_font("Arial", '', 11)
112
  texto_limpo = st.session_state.relatorio_ia.replace("*", "").replace("🌪️", ">").replace("🌊", ">").replace("🚨", ">").replace("⚡", ">").replace("✅", ">").replace("⏳", ">").replace("🐢", ">")
113
  pdf.multi_cell(0, 6, texto_limpo)
114
-
115
  return pdf.output(dest='S').encode('latin-1')
116
 
117
- # --- NÚCLEO FÍSICO COM TELEMETRIA ---
118
  def gerar_hash(file_bytes, lin_def, ang_def):
119
  m = hashlib.md5()
120
  m.update(file_bytes)
@@ -127,75 +120,54 @@ def processar_malha_com_telemetria(file_bytes, lin_def, ang_def):
127
  temp_dir = tempfile.mkdtemp()
128
  path_in = os.path.join(temp_dir, "peca.step")
129
  with open(path_in, "wb") as f: f.write(file_bytes)
130
-
131
  reader = STEPControl_Reader()
132
  reader.ReadFile(path_in)
133
  reader.TransferRoots()
134
  shape = reader.OneShape()
135
  prog_bar.progress(20, text="📐 20% - Extraindo geometria B-Rep...")
136
-
137
  props = GProp_GProps()
138
  brepgprop.VolumeProperties(shape, props)
139
  vol_mm3 = props.Mass()
140
-
141
  prog_bar.progress(60, text=f"🕸️ 60% - Tesselação CAD Base...")
142
  mesh_gen = BRepMesh_IncrementalMesh(shape, lin_def, False, ang_def, True)
143
  mesh_gen.Perform()
144
-
145
  path_stl = os.path.join(temp_dir, "malha_alta.stl")
146
  StlAPI_Writer().Write(shape, path_stl)
147
-
148
  mesh_alta = pv.read(path_stl)
149
  path_proxy = os.path.join(temp_dir, "malha_proxy.stl")
150
-
151
  try:
152
  if mesh_alta.n_faces > 3000:
153
  fator = 1.0 - (3000.0 / mesh_alta.n_faces)
154
  fator = np.clip(fator, 0.10, 0.95)
155
  mesh_proxy = mesh_alta.decimate(fator)
156
- else:
157
- mesh_proxy = mesh_alta
158
- except:
159
- mesh_proxy = mesh_alta
160
-
161
  mesh_proxy.save(path_proxy)
162
-
163
  mesh_proxy_visual = mesh_proxy.copy()
164
  mesh_proxy_visual.points /= 1000.0
165
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
166
  plotter = pv.Plotter(off_screen=True)
167
  plotter.add_mesh(mesh_proxy_visual, color="#cccccc", lighting=False)
168
  plotter.export_gltf(tmp.name)
169
- with open(tmp.name, "rb") as f:
170
- b64_final = base64.b64encode(f.read()).decode()
171
-
172
  prog_bar.empty()
173
  return path_stl, path_proxy, vol_mm3, b64_final
174
 
175
- # --- MOTOR DE IA ---
176
  def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe, reynolds, velocidade):
177
  relatorio = []
178
- if reynolds > 5000:
179
- relatorio.append(f"🌪️ **Turbulência Crítica (Reynolds = {reynolds:.0f}):** Risco de aprisionamento de gás.")
180
- elif reynolds > 2000:
181
- relatorio.append(f"🌊 **Fluxo Transiente (Reynolds = {reynolds:.0f}):** Velocidade típica para coquilhas.")
182
- else:
183
- relatorio.append(f"🐢 **Fluxo Laminar (Reynolds = {reynolds:.0f}):** Escoamento limpo e seguro.")
184
-
185
- if max_risco_rechupe > 0.8:
186
- relatorio.append("🚨 **ALERTA DE RECHUPE:** Estrangulamento severo nos cantos internos detectado. Aumente o derramador ou reveja os raios.")
187
- else:
188
- relatorio.append("✅ **Alimentação Saudável:** Gradiente térmico direcional preservado.")
189
-
190
  return "\n\n".join(relatorio)
191
 
192
  # --- INTERFACE ---
193
  if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
194
- progresso_visual = min(st.session_state.step, 4) / 4
195
- st.progress(progresso_visual)
196
 
197
  if st.session_state.step not in [3.5, 4.5]:
198
- st.title("🛡️ CastingSim V40: Derramador Físico & Mapeamento Turbo")
199
  st.markdown("---")
200
 
201
  # ==========================================
@@ -220,7 +192,6 @@ elif st.session_state.step == 2:
220
  with c_molde3:
221
  if st.session_state.tinta_ceramica:
222
  st.session_state.espessura_tinta = st.number_input("Espessura Tinta (mm)", value=st.session_state.espessura_tinta, step=0.5)
223
-
224
  st.markdown("---")
225
  c_fluido1, c_fluido2, c_fluido3 = st.columns(3)
226
  with c_fluido1: st.session_state.liga = st.selectbox("Liga de Alumínio", ["SAE 305", "SAE 306", "SAE 329"], index=0)
@@ -228,7 +199,6 @@ elif st.session_state.step == 2:
228
  with c_fluido3:
229
  st.session_state.vel_vaz = st.number_input("Vel. Vazamento (m/s)", value=st.session_state.vel_vaz, step=0.1)
230
  st.session_state.diam_vaz = st.number_input("Ø Derramador (mm)", value=st.session_state.diam_vaz, step=1.0)
231
-
232
  c_b1, c_b2 = st.columns([1, 8])
233
  with c_b1:
234
  if st.button("⬅️ Voltar"): st.session_state.step = 1; st.rerun()
@@ -236,7 +206,7 @@ elif st.session_state.step == 2:
236
  if st.button("Avançar para Geometria ➡️", type="primary"): st.session_state.step = 3; st.rerun()
237
 
238
  # ==========================================
239
- # ETAPA 3
240
  # ==========================================
241
  elif st.session_state.step == 3:
242
  st.header("3. Inspeção e Ponto de Vazamento")
@@ -259,9 +229,7 @@ elif st.session_state.step == 3:
259
  mesh_leitura = pv.read(st.session_state.path_proxy_stl)
260
  c = mesh_leitura.center
261
  b = mesh_leitura.bounds
262
- st.session_state.off_x = float(c[0])
263
- st.session_state.off_y = float(c[1])
264
- st.session_state.off_z = float(b[5])
265
  st.session_state.coord_iniciada = True
266
 
267
  col_form, col_view = st.columns([1, 2])
@@ -269,15 +237,19 @@ elif st.session_state.step == 3:
269
  with col_form:
270
  st.markdown("---")
271
  with st.form("ajustes_cad", clear_on_submit=False):
272
- rx = st.slider("Rotação X", 0, 360, value=int(st.session_state.rot_x))
273
- ry = st.slider("Rotação Y", 0, 360, value=int(st.session_state.rot_y))
274
- rz = st.slider("Rotação Z", 0, 360, value=int(st.session_state.rot_z))
 
 
 
275
  st.write("**Centro do Derramador (mm)**")
276
- st.caption("Centralize o Ponto Azul no furo do cubo.")
277
  ox = st.number_input("Eixo X", value=float(st.session_state.off_x), step=1.0)
278
  oy = st.number_input("Eixo Y", value=float(st.session_state.off_y), step=1.0)
279
  oz = st.number_input("Eixo Z", value=float(st.session_state.off_z), step=1.0)
280
- if st.form_submit_button("🔄 Atualizar"):
 
 
281
  st.session_state.rot_x, st.session_state.rot_y, st.session_state.rot_z = rx, ry, rz
282
  st.session_state.off_x, st.session_state.off_y, st.session_state.off_z = ox, oy, oz
283
  st.rerun()
@@ -289,7 +261,7 @@ elif st.session_state.step == 3:
289
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_proxy}"
290
  orientation="{st.session_state.rot_x}deg {st.session_state.rot_y}deg {st.session_state.rot_z}deg"
291
  style="width: 100%; height: 480px; background-color: #f4f6f9;" camera-controls>
292
- <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: #00BFFF; width: 16px; height: 16px; border-radius: 50%; border: 2px solid white; box-shadow: 0 0 12px #00BFFF;"></button>
293
  </model-viewer>
294
  """
295
  components.html(html, height=500)
@@ -303,20 +275,18 @@ elif st.session_state.step == 3:
303
  st.session_state.step = 3.5; st.rerun()
304
 
305
  # ==========================================
306
- # ETAPA 3.5: NÚCLEO FÍSICO MULTICAMADAS
307
  # ==========================================
308
  elif st.session_state.step == 3.5:
309
  st.title("⏳ Processando Solver FEM & Fourier...")
310
  progress_bar = st.progress(0, text="Calculando Tensores no Modelo Pesado...")
311
 
312
  try:
313
- # Lendo Pesada
314
  mesh_pesada = pv.read(st.session_state.path_stl)
315
  mesh_pesada.rotate_x(st.session_state.rot_x, inplace=True)
316
  mesh_pesada.rotate_y(st.session_state.rot_y, inplace=True)
317
  mesh_pesada.rotate_z(st.session_state.rot_z, inplace=True)
318
 
319
- # O Ponto Azul define o centro real de queda (não há mais Snap no vazio)
320
  px, py, pz = st.session_state.off_x, st.session_state.off_y, st.session_state.off_z
321
  st.session_state.p_riser_real = [px, py, pz]
322
  p_riser_arr = np.array([px, py, pz])
@@ -326,15 +296,25 @@ elif st.session_state.step == 3.5:
326
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
327
 
328
  pts = mesh_pesada.points
 
329
 
330
- # Cinemática (Preenchimento)
331
- y_coords = pts[:, 1]
332
- y_norm = (y_coords - np.min(y_coords)) / (np.max(y_coords) - np.min(y_coords) + 1e-6)
333
- r_coords = np.sqrt((pts[:, 0] - px)**2 + (pts[:, 2] - pz)**2)
 
 
 
 
 
 
 
 
334
  r_eff = np.maximum(0, r_coords - R_vaz)
335
  r_norm = r_eff / (np.max(r_eff) + 1e-6)
 
336
  turbulencia = np.random.normal(0, 0.08, size=mesh_pesada.n_points)
337
- campo_fluido = (y_norm * 0.65) + (r_norm * 0.35) + turbulencia
338
  calor_dinamico = (campo_fluido - np.min(campo_fluido)) / (np.max(campo_fluido) - np.min(campo_fluido) + 1e-6)
339
  mesh_pesada['Preenchimento'] = calor_dinamico
340
 
@@ -347,17 +327,11 @@ elif st.session_state.step == 3.5:
347
  curv_norm = np.where(curv_negativa > np.percentile(curv_negativa, 85), curv_negativa, 0) / (np.max(curv_negativa) + 1e-6)
348
  isolamento = np.linalg.norm(pts - p_riser_arr, axis=1) / (np.max(np.linalg.norm(pts - p_riser_arr, axis=1)) + 1e-6)
349
 
350
- # 1. HEAT (Gradiente Térmico Simples)
351
  risco_bruto = np.clip((massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2), 0, 1)
352
  mesh_pesada['Heat'] = np.log1p(risco_bruto * 40.0) / np.log1p(40.0)
353
-
354
- # 2. RECHUPE
355
  mesh_pesada['Risco'] = np.clip(((massa_termica ** 3) + (curv_norm * 5.0)) * (isolamento ** 2) * 10.0, 0, 1)
356
-
357
- # 3. SOLIDIFICAÇÃO (Massa Térmica pesa muito, demora a esfriar)
358
  mesh_pesada['Solidificacao'] = np.clip((massa_termica * 0.7) + (calor_dinamico * 0.3), 0, 1)
359
 
360
- # MESTRE FUNDIDOR E TEMPOS
361
  mod_cm = (st.session_state.vol_mm3 / pv.read(st.session_state.path_stl).area) / 10
362
  num_reynolds = (st.session_state.vel_vaz * ((mod_cm * 2) / 100.0)) / 1.3e-6
363
  base_b = 100 if st.session_state.mat_molde == "Aço 1045" else 120
@@ -368,7 +342,6 @@ elif st.session_state.step == 3.5:
368
  st.session_state.relatorio_ia = gerar_diagnostico_ia(mod_cm, t_sol_segundos_totais, st.session_state.t_vaz, st.session_state.t_molde, float(np.max(mesh_pesada['Risco'])), num_reynolds, st.session_state.vel_vaz)
369
  st.session_state.relatorio_pdf = compilar_pdf()
370
 
371
- # --- A GRANDE OTIMIZAÇÃO V39 MANTIDA ---
372
  progress_bar.progress(70, text="Transferindo Conhecimento Matemático para Malha Otimizada...")
373
  mesh_proxy = pv.read(st.session_state.path_proxy_stl)
374
  mesh_proxy.rotate_x(st.session_state.rot_x, inplace=True)
@@ -381,34 +354,22 @@ elif st.session_state.step == 3.5:
381
  mesh_resultados_proxy.save(path_resultados)
382
  st.session_state.path_resultados_proxy = path_resultados
383
 
384
- progress_bar.progress(85, text="Gerando Hologramas Estáticos (Preenchimento, Rechupe e Solidificação)...")
385
-
386
- # Exporta Heat Base
387
- m_heat = mesh_resultados_proxy.copy()
388
- m_heat.points /= 1000.0
389
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
390
- pl = pv.Plotter(off_screen=True)
391
- pl.add_mesh(m_heat, scalars='Heat', cmap="hot", smooth_shading=True)
392
  pl.export_gltf(tmp.name)
393
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
394
 
395
- # Exporta Solidificação (Colormap TURBO)
396
- m_solid = mesh_resultados_proxy.copy()
397
- m_solid.points /= 1000.0
398
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
399
- pl = pv.Plotter(off_screen=True)
400
- pl.add_mesh(m_solid, scalars='Solidificacao', cmap="turbo", smooth_shading=True)
401
  pl.export_gltf(tmp.name)
402
  with open(tmp.name, "rb") as f: st.session_state.b64_solidificacao = base64.b64encode(f.read()).decode()
403
 
404
- # Exporta Rechupe x10 a partir da malha pesada (para qualidade visual do defeito)
405
- m_rec = mesh_pesada.copy()
406
- m_rec.compute_normals(inplace=True)
407
- m_def = m_rec.warp_by_scalar(scalars='Risco', factor=-10.0)
408
- m_def.points /= 1000.0
409
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
410
- pl = pv.Plotter(off_screen=True)
411
- pl.add_mesh(m_def, scalars='Risco', cmap="hot", smooth_shading=True)
412
  pl.export_gltf(tmp.name)
413
  with open(tmp.name, "rb") as f: st.session_state.b64_rechupe_x10 = base64.b64encode(f.read()).decode()
414
 
@@ -421,7 +382,7 @@ elif st.session_state.step == 3.5:
421
  if st.button("⬅️ Voltar"): st.session_state.step = 3; st.rerun()
422
 
423
  # ==========================================
424
- # ETAPA 4: LAUDO (COM TELA DE SOLIDIFICAÇÃO ADICIONADA)
425
  # ==========================================
426
  elif st.session_state.step == 4:
427
  st.header("4. Simulação: Laudo da Qualidade")
@@ -430,11 +391,10 @@ elif st.session_state.step == 4:
430
  with col_tempo:
431
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {st.session_state.t_sol_minutos} min {st.session_state.t_sol_segundos} s**")
432
  with col_video:
433
- if st.button("🎬 Painel de Extração Temporal", help="Gera os frames na malha otimizada", use_container_width=True):
434
  st.session_state.step = 4.5
435
  st.rerun()
436
 
437
- # 3 COLUNAS PARA A TRINDADE DA ANÁLISE
438
  col_v1, col_v2, col_v3 = st.columns(3)
439
  p_m = [st.session_state.p_riser_real[0]/1000.0, st.session_state.p_riser_real[1]/1000.0, st.session_state.p_riser_real[2]/1000.0]
440
 
@@ -442,13 +402,13 @@ elif st.session_state.step == 4:
442
  st.write("🔥 **1. Preenchimento Térmico**")
443
  html_termico = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
444
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_termico}" style="width: 100%; height: 320px; background-color: #1e1e1e;" camera-controls shadow-intensity="1">
445
- <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: #00BFFF; width: 14px; height: 14px; border-radius: 50%;"></button>
446
  </model-viewer>"""
447
  components.html(html_termico, height=360)
448
 
449
  with col_v2:
450
  st.write("🌈 **2. Mapa de Solidificação (Turbo)**")
451
- st.caption("Frio (Azul) = Congela Rápido | Quente (Vermelho) = Congela Lento")
452
  html_solid = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
453
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_solidificacao}" style="width: 100%; height: 320px; background-color: #1e1e1e;" camera-controls shadow-intensity="1"></model-viewer>"""
454
  components.html(html_solid, height=360)
@@ -464,7 +424,6 @@ elif st.session_state.step == 4:
464
  st.subheader("🤖 Diagnóstico IA")
465
  st.markdown(st.session_state.relatorio_ia)
466
  with c_btn:
467
- st.write("")
468
  st.write("")
469
  if HAS_FPDF and st.session_state.relatorio_pdf:
470
  st.download_button("📄 Baixar Laudo (.PDF)", st.session_state.relatorio_pdf, "Laudo_CastingSim.pdf", "application/pdf", type="primary", use_container_width=True)
@@ -472,41 +431,60 @@ elif st.session_state.step == 4:
472
  st.session_state.step = 3; st.rerun()
473
 
474
  # ==========================================
475
- # ETAPA 4.5: RENDER FARM (INJETANDO O CILINDRO VIRTUAL)
476
  # ==========================================
477
  elif st.session_state.step == 4.5:
478
  st.title("🎬 Extração Cinemática com Derramador Físico")
479
- st.info("Acoplando cilindro de vazamento na malha de simulação temporal...")
480
  prog = st.progress(0)
481
 
482
  try:
483
  mesh_proxy = pv.read(st.session_state.path_resultados_proxy)
484
  mesh_molde = pv.read(st.session_state.path_proxy_stl)
485
- mesh_molde.rotate_x(st.session_state.rot_x, inplace=True)
486
- mesh_molde.rotate_y(st.session_state.rot_y, inplace=True)
487
- mesh_molde.rotate_z(st.session_state.rot_z, inplace=True)
488
 
489
- # O PULO DO GATO VISUAL V40: Criar o Derramador Fisicamente
490
  px, py, pz = st.session_state.p_riser_real
491
- y_bounds = mesh_proxy.bounds[2:4] # ymin, ymax
492
- altura_sprue = (y_bounds[1] - y_bounds[0]) * 1.5
493
- centro_y = y_bounds[0] + (altura_sprue / 2.0)
494
 
495
- cilindro = pv.Cylinder(center=(px, centro_y, pz), direction=(0,1,0), radius=st.session_state.diam_vaz/2.0, height=altura_sprue)
496
- cilindro = cilindro.triangulate()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
- # Funde o cilindro na malha apenas para a animação do fluido!
499
  mesh_animacao = mesh_proxy.merge(cilindro)
500
 
501
- # Recalcula a heurística de queda especificamente para a malha fundida
502
  pts_anim = mesh_animacao.points
503
- y_anim = pts_anim[:, 1]
504
- y_norm = (y_anim - np.min(y_anim)) / (np.max(y_anim) - np.min(y_anim) + 1e-6)
505
- r_coords = np.sqrt((pts_anim[:, 0] - px)**2 + (pts_anim[:, 2] - pz)**2)
 
 
 
 
 
 
 
 
506
  r_eff = np.maximum(0, r_coords - (st.session_state.diam_vaz/2.0))
507
  r_norm = r_eff / (np.max(r_eff) + 1e-6)
508
  turbulencia = np.random.normal(0, 0.08, size=mesh_animacao.n_points)
509
- campo = (y_norm * 0.65) + (r_norm * 0.35) + turbulencia
510
  mesh_animacao['Preenchimento_Anim'] = (campo - np.min(campo)) / (np.max(campo) - np.min(campo) + 1e-6)
511
 
512
  mesh_molde.points /= 1000.0
@@ -514,14 +492,11 @@ elif st.session_state.step == 4.5:
514
  st.session_state.frames_cooling = []
515
  temp_dir = tempfile.mkdtemp()
516
 
517
- # 1. GERAR VÍDEO DE PREENCHIMENTO (10 Frames)
518
  passos = 10
519
  for i in range(1, passos + 1):
520
  lim = (1.0 / passos) * i
521
  if lim <= 0: lim = 1e-6
522
-
523
  f_mesh = mesh_animacao.threshold([0, lim], scalars='Preenchimento_Anim')
524
-
525
  pl = pv.Plotter(off_screen=True)
526
  pl.add_mesh(mesh_molde, color='white', opacity=0.1, style='wireframe')
527
  if f_mesh.n_points > 0:
@@ -533,7 +508,6 @@ elif st.session_state.step == 4.5:
533
  pl.close()
534
  prog.progress(int((i/passos)*40), text="[1/2] Forjando Animação de Enchimento pelo Derramador...")
535
 
536
- # 2. GERAR VÍDEO DE RESFRIAMENTO TÉRMICO (LEI DE FOURIER) (10 Frames)
537
  t_v = st.session_state.t_vaz
538
  t_m = st.session_state.t_molde
539
  massa = mesh_proxy['MassaTermica']
@@ -543,7 +517,6 @@ elif st.session_state.step == 4.5:
543
  t_instante = (i / (passos - 1)) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1)
544
  T_t = t_m + (t_v - t_m) * np.exp(-t_instante / tau)
545
  heat_norm = (T_t - t_m) / (t_v - t_m + 1e-6)
546
-
547
  m_cool = mesh_proxy.copy()
548
  m_cool['TempAtual'] = heat_norm
549
  m_cool.points /= 1000.0
@@ -572,7 +545,6 @@ elif st.session_state.step == 5:
572
  st.header("5. Telemetria Cinemática")
573
 
574
  modo = st.radio("Selecione o Módulo de Visualização:", ["🌊 Cinemática de Preenchimento", "❄️ Termodinâmica de Resfriamento (Fourier)"], horizontal=True)
575
-
576
  caminhos_alvo = st.session_state.frames_filling if "Preenchimento" in modo else st.session_state.frames_cooling
577
 
578
  if len(caminhos_alvo) > 0:
@@ -583,7 +555,6 @@ elif st.session_state.step == 5:
583
  except: pass
584
 
585
  frames_js_array = ",\n".join([f'"{b64}"' for b64 in frames_b64])
586
-
587
  css_thumb = "#ff4500" if "Preenchimento" in modo else "#00BFFF"
588
 
589
  html_player = f"""
@@ -603,9 +574,9 @@ elif st.session_state.step == 5:
603
  <body>
604
  <model-viewer id="mv" src="data:model/gltf-binary;base64,{frames_b64[0]}" camera-controls shadow-intensity="1"></model-viewer>
605
  <div class="controls">
606
- <span style="font-weight: bold;">T=0</span>
607
  <input type="range" min="1" max="{len(frames_b64)}" value="1" class="slider" id="frameSlider">
608
- <span style="font-weight: bold;">T=Final</span>
609
  <div class="status" id="frame-counter">Quadro: 1 / {len(frames_b64)}</div>
610
  </div>
611
  <script>
 
16
  except ImportError:
17
  HAS_FPDF = False
18
 
19
+ # --- SETUP DE INFRAESTRUTURA ---
20
+ os.environ['PYVISTA_OFF_SCREEN'] = 'true'
21
+ os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
22
+
23
  from OCC.Core.STEPControl import STEPControl_Reader
24
  from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
25
  from OCC.Core.BRepGProp import brepgprop
26
  from OCC.Core.GProp import GProp_GProps
27
  from OCC.Core.StlAPI import StlAPI_Writer
28
 
29
+ st.set_page_config(page_title="CastingSim V41", layout="wide")
 
 
 
 
30
 
31
  st.markdown("""
32
  <style>
 
54
  if 'liga' not in st.session_state: st.session_state.liga = "SAE 305"
55
  if 't_vaz' not in st.session_state: st.session_state.t_vaz = 720
56
  if 't_molde' not in st.session_state: st.session_state.t_molde = 300
57
+ if 'mat_molde' not in st.session_state: st.session_state.mat_molde = "Aço 1045"
58
+ if 'tinta_ceramica' not in st.session_state: st.session_state.tinta_ceramica = True
59
+ if 'espessura_tinta' not in st.session_state: st.session_state.espessura_tinta = 5.0
60
+ if 'vel_vaz' not in st.session_state: st.session_state.vel_vaz = 1.0
61
+ if 'diam_vaz' not in st.session_state: st.session_state.diam_vaz = 20.0
62
 
63
  if 'off_x' not in st.session_state: st.session_state.off_x = 0.0
64
  if 'off_y' not in st.session_state: st.session_state.off_y = 0.0
 
67
  if 'rot_x' not in st.session_state: st.session_state.rot_x = 0
68
  if 'rot_y' not in st.session_state: st.session_state.rot_y = 0
69
  if 'rot_z' not in st.session_state: st.session_state.rot_z = 0
70
+ if 'eixo_vaz' not in st.session_state: st.session_state.eixo_vaz = "Y" # NOVO: Controlador de Gravidade
 
 
 
 
 
71
 
72
  if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
73
  if 'b64_rechupe_x10' not in st.session_state: st.session_state.b64_rechupe_x10 = ""
74
+ if 'b64_solidificacao' not in st.session_state: st.session_state.b64_solidificacao = ""
75
  if 'frames_filling' not in st.session_state: st.session_state.frames_filling = []
76
  if 'frames_cooling' not in st.session_state: st.session_state.frames_cooling = []
77
  if 't_sol_minutos' not in st.session_state: st.session_state.t_sol_minutos = 0
 
79
  if 'relatorio_ia' not in st.session_state: st.session_state.relatorio_ia = ""
80
  if 'relatorio_pdf' not in st.session_state: st.session_state.relatorio_pdf = None
81
 
 
82
  def compilar_pdf():
83
  if not HAS_FPDF: return None
84
  pdf = FPDF()
85
  pdf.add_page()
86
  pdf.set_font("Arial", 'B', 16)
87
+ pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V41", 0, 1, 'C')
88
  pdf.ln(5)
 
89
  pdf.set_font("Arial", 'B', 12)
90
  pdf.cell(0, 10, "1. Parametros de Processo", 0, 1)
91
  pdf.set_font("Arial", '', 11)
92
  pdf.cell(0, 6, f"Liga: {st.session_state.liga} | Velocidade Vazamento: {st.session_state.vel_vaz} m/s | Derramador Ø: {st.session_state.diam_vaz} mm", 0, 1)
93
+ pdf.cell(0, 6, f"Eixo de Gravidade Ativo: {st.session_state.eixo_vaz}", 0, 1)
94
  pdf.cell(0, 6, f"Molde: Coquilha de {st.session_state.mat_molde}", 0, 1)
95
  if st.session_state.tinta_ceramica:
96
  pdf.cell(0, 6, f"Revestimento: Tinta Ceramica (Espessura: {st.session_state.espessura_tinta} mm)", 0, 1)
97
  pdf.cell(0, 6, f"Temps: Vazamento {st.session_state.t_vaz} C | Coquilha {st.session_state.t_molde} C", 0, 1)
98
  pdf.ln(5)
 
99
  pdf.set_font("Arial", 'B', 12)
100
  pdf.cell(0, 10, "2. Resultados Metrologicos", 0, 1)
101
  pdf.set_font("Arial", '', 11)
102
  pdf.cell(0, 6, f"Tempo de Solidificacao: {st.session_state.t_sol_minutos} min e {st.session_state.t_sol_segundos} s", 0, 1)
103
  pdf.ln(5)
 
104
  pdf.set_font("Arial", 'B', 12)
105
  pdf.cell(0, 10, "3. Diagnostico IA (Mestre Fundidor)", 0, 1)
106
  pdf.set_font("Arial", '', 11)
107
  texto_limpo = st.session_state.relatorio_ia.replace("*", "").replace("🌪️", ">").replace("🌊", ">").replace("🚨", ">").replace("⚡", ">").replace("✅", ">").replace("⏳", ">").replace("🐢", ">")
108
  pdf.multi_cell(0, 6, texto_limpo)
 
109
  return pdf.output(dest='S').encode('latin-1')
110
 
 
111
  def gerar_hash(file_bytes, lin_def, ang_def):
112
  m = hashlib.md5()
113
  m.update(file_bytes)
 
120
  temp_dir = tempfile.mkdtemp()
121
  path_in = os.path.join(temp_dir, "peca.step")
122
  with open(path_in, "wb") as f: f.write(file_bytes)
 
123
  reader = STEPControl_Reader()
124
  reader.ReadFile(path_in)
125
  reader.TransferRoots()
126
  shape = reader.OneShape()
127
  prog_bar.progress(20, text="📐 20% - Extraindo geometria B-Rep...")
 
128
  props = GProp_GProps()
129
  brepgprop.VolumeProperties(shape, props)
130
  vol_mm3 = props.Mass()
 
131
  prog_bar.progress(60, text=f"🕸️ 60% - Tesselação CAD Base...")
132
  mesh_gen = BRepMesh_IncrementalMesh(shape, lin_def, False, ang_def, True)
133
  mesh_gen.Perform()
 
134
  path_stl = os.path.join(temp_dir, "malha_alta.stl")
135
  StlAPI_Writer().Write(shape, path_stl)
 
136
  mesh_alta = pv.read(path_stl)
137
  path_proxy = os.path.join(temp_dir, "malha_proxy.stl")
 
138
  try:
139
  if mesh_alta.n_faces > 3000:
140
  fator = 1.0 - (3000.0 / mesh_alta.n_faces)
141
  fator = np.clip(fator, 0.10, 0.95)
142
  mesh_proxy = mesh_alta.decimate(fator)
143
+ else: mesh_proxy = mesh_alta
144
+ except: mesh_proxy = mesh_alta
 
 
 
145
  mesh_proxy.save(path_proxy)
 
146
  mesh_proxy_visual = mesh_proxy.copy()
147
  mesh_proxy_visual.points /= 1000.0
148
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
149
  plotter = pv.Plotter(off_screen=True)
150
  plotter.add_mesh(mesh_proxy_visual, color="#cccccc", lighting=False)
151
  plotter.export_gltf(tmp.name)
152
+ with open(tmp.name, "rb") as f: b64_final = base64.b64encode(f.read()).decode()
 
 
153
  prog_bar.empty()
154
  return path_stl, path_proxy, vol_mm3, b64_final
155
 
 
156
  def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe, reynolds, velocidade):
157
  relatorio = []
158
+ if reynolds > 5000: relatorio.append(f"🌪️ **Turbulência Crítica (Reynolds = {reynolds:.0f}):** Risco de aprisionamento de gás.")
159
+ elif reynolds > 2000: relatorio.append(f"🌊 **Fluxo Transiente (Reynolds = {reynolds:.0f}):** Velocidade típica para coquilhas.")
160
+ else: relatorio.append(f"🐢 **Fluxo Laminar (Reynolds = {reynolds:.0f}):** Escoamento limpo e seguro.")
161
+ if max_risco_rechupe > 0.8: relatorio.append("🚨 **ALERTA DE RECHUPE:** Estrangulamento severo nos cantos internos detectado. Ajuste o derramador.")
162
+ else: relatorio.append("✅ **Alimentação Saudável:** Gradiente térmico direcional preservado.")
 
 
 
 
 
 
 
163
  return "\n\n".join(relatorio)
164
 
165
  # --- INTERFACE ---
166
  if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
167
+ st.progress(min(st.session_state.step, 4) / 4)
 
168
 
169
  if st.session_state.step not in [3.5, 4.5]:
170
+ st.title("🛡️ CastingSim V41: Alinhamento Vetorial de Gravidade")
171
  st.markdown("---")
172
 
173
  # ==========================================
 
192
  with c_molde3:
193
  if st.session_state.tinta_ceramica:
194
  st.session_state.espessura_tinta = st.number_input("Espessura Tinta (mm)", value=st.session_state.espessura_tinta, step=0.5)
 
195
  st.markdown("---")
196
  c_fluido1, c_fluido2, c_fluido3 = st.columns(3)
197
  with c_fluido1: st.session_state.liga = st.selectbox("Liga de Alumínio", ["SAE 305", "SAE 306", "SAE 329"], index=0)
 
199
  with c_fluido3:
200
  st.session_state.vel_vaz = st.number_input("Vel. Vazamento (m/s)", value=st.session_state.vel_vaz, step=0.1)
201
  st.session_state.diam_vaz = st.number_input("Ø Derramador (mm)", value=st.session_state.diam_vaz, step=1.0)
 
202
  c_b1, c_b2 = st.columns([1, 8])
203
  with c_b1:
204
  if st.button("⬅️ Voltar"): st.session_state.step = 1; st.rerun()
 
206
  if st.button("Avançar para Geometria ➡️", type="primary"): st.session_state.step = 3; st.rerun()
207
 
208
  # ==========================================
209
+ # ETAPA 3: A REVOLUÇÃO DO EIXO
210
  # ==========================================
211
  elif st.session_state.step == 3:
212
  st.header("3. Inspeção e Ponto de Vazamento")
 
229
  mesh_leitura = pv.read(st.session_state.path_proxy_stl)
230
  c = mesh_leitura.center
231
  b = mesh_leitura.bounds
232
+ st.session_state.off_x, st.session_state.off_y, st.session_state.off_z = float(c[0]), float(c[1]), float(b[5])
 
 
233
  st.session_state.coord_iniciada = True
234
 
235
  col_form, col_view = st.columns([1, 2])
 
237
  with col_form:
238
  st.markdown("---")
239
  with st.form("ajustes_cad", clear_on_submit=False):
240
+ # O SELETOR QUE SALVA VIDAS
241
+ eixo_sel = st.selectbox("Eixo de Gravidade (Alinhamento do Furo)", ["X", "Y", "Z"], index=["X", "Y", "Z"].index(st.session_state.eixo_vaz))
242
+ st.markdown("---")
243
+ rx = st.slider("Rotação Visual X", 0, 360, value=int(st.session_state.rot_x))
244
+ ry = st.slider("Rotação Visual Y", 0, 360, value=int(st.session_state.rot_y))
245
+ rz = st.slider("Rotação Visual Z", 0, 360, value=int(st.session_state.rot_z))
246
  st.write("**Centro do Derramador (mm)**")
 
247
  ox = st.number_input("Eixo X", value=float(st.session_state.off_x), step=1.0)
248
  oy = st.number_input("Eixo Y", value=float(st.session_state.off_y), step=1.0)
249
  oz = st.number_input("Eixo Z", value=float(st.session_state.off_z), step=1.0)
250
+
251
+ if st.form_submit_button("🔄 Atualizar Visualização"):
252
+ st.session_state.eixo_vaz = eixo_sel
253
  st.session_state.rot_x, st.session_state.rot_y, st.session_state.rot_z = rx, ry, rz
254
  st.session_state.off_x, st.session_state.off_y, st.session_state.off_z = ox, oy, oz
255
  st.rerun()
 
261
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_proxy}"
262
  orientation="{st.session_state.rot_x}deg {st.session_state.rot_y}deg {st.session_state.rot_z}deg"
263
  style="width: 100%; height: 480px; background-color: #f4f6f9;" camera-controls>
264
+ <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: #00BFFF; width: 16px; height: 16px; border-radius: 50%; box-shadow: 0 0 12px #00BFFF; border: 2px solid white;"></button>
265
  </model-viewer>
266
  """
267
  components.html(html, height=500)
 
275
  st.session_state.step = 3.5; st.rerun()
276
 
277
  # ==========================================
278
+ # ETAPA 3.5: NÚCLEO FÍSICO COM EIXO DINÂMICO
279
  # ==========================================
280
  elif st.session_state.step == 3.5:
281
  st.title("⏳ Processando Solver FEM & Fourier...")
282
  progress_bar = st.progress(0, text="Calculando Tensores no Modelo Pesado...")
283
 
284
  try:
 
285
  mesh_pesada = pv.read(st.session_state.path_stl)
286
  mesh_pesada.rotate_x(st.session_state.rot_x, inplace=True)
287
  mesh_pesada.rotate_y(st.session_state.rot_y, inplace=True)
288
  mesh_pesada.rotate_z(st.session_state.rot_z, inplace=True)
289
 
 
290
  px, py, pz = st.session_state.off_x, st.session_state.off_y, st.session_state.off_z
291
  st.session_state.p_riser_real = [px, py, pz]
292
  p_riser_arr = np.array([px, py, pz])
 
296
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
297
 
298
  pts = mesh_pesada.points
299
+ eixo = st.session_state.eixo_vaz
300
 
301
+ # A MÁGICA DA V41: O vetor de gravidade e o tensor cilíndrico adaptam-se ao eixo escolhido!
302
+ if eixo == 'Y':
303
+ grav_coords = pts[:, 1]
304
+ r_coords = np.sqrt((pts[:, 0] - px)**2 + (pts[:, 2] - pz)**2)
305
+ elif eixo == 'Z':
306
+ grav_coords = pts[:, 2]
307
+ r_coords = np.sqrt((pts[:, 0] - px)**2 + (pts[:, 1] - py)**2)
308
+ elif eixo == 'X':
309
+ grav_coords = pts[:, 0]
310
+ r_coords = np.sqrt((pts[:, 1] - py)**2 + (pts[:, 2] - pz)**2)
311
+
312
+ grav_norm = (grav_coords - np.min(grav_coords)) / (np.max(grav_coords) - np.min(grav_coords) + 1e-6)
313
  r_eff = np.maximum(0, r_coords - R_vaz)
314
  r_norm = r_eff / (np.max(r_eff) + 1e-6)
315
+
316
  turbulencia = np.random.normal(0, 0.08, size=mesh_pesada.n_points)
317
+ campo_fluido = (grav_norm * 0.65) + (r_norm * 0.35) + turbulencia
318
  calor_dinamico = (campo_fluido - np.min(campo_fluido)) / (np.max(campo_fluido) - np.min(campo_fluido) + 1e-6)
319
  mesh_pesada['Preenchimento'] = calor_dinamico
320
 
 
327
  curv_norm = np.where(curv_negativa > np.percentile(curv_negativa, 85), curv_negativa, 0) / (np.max(curv_negativa) + 1e-6)
328
  isolamento = np.linalg.norm(pts - p_riser_arr, axis=1) / (np.max(np.linalg.norm(pts - p_riser_arr, axis=1)) + 1e-6)
329
 
 
330
  risco_bruto = np.clip((massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2), 0, 1)
331
  mesh_pesada['Heat'] = np.log1p(risco_bruto * 40.0) / np.log1p(40.0)
 
 
332
  mesh_pesada['Risco'] = np.clip(((massa_termica ** 3) + (curv_norm * 5.0)) * (isolamento ** 2) * 10.0, 0, 1)
 
 
333
  mesh_pesada['Solidificacao'] = np.clip((massa_termica * 0.7) + (calor_dinamico * 0.3), 0, 1)
334
 
 
335
  mod_cm = (st.session_state.vol_mm3 / pv.read(st.session_state.path_stl).area) / 10
336
  num_reynolds = (st.session_state.vel_vaz * ((mod_cm * 2) / 100.0)) / 1.3e-6
337
  base_b = 100 if st.session_state.mat_molde == "Aço 1045" else 120
 
342
  st.session_state.relatorio_ia = gerar_diagnostico_ia(mod_cm, t_sol_segundos_totais, st.session_state.t_vaz, st.session_state.t_molde, float(np.max(mesh_pesada['Risco'])), num_reynolds, st.session_state.vel_vaz)
343
  st.session_state.relatorio_pdf = compilar_pdf()
344
 
 
345
  progress_bar.progress(70, text="Transferindo Conhecimento Matemático para Malha Otimizada...")
346
  mesh_proxy = pv.read(st.session_state.path_proxy_stl)
347
  mesh_proxy.rotate_x(st.session_state.rot_x, inplace=True)
 
354
  mesh_resultados_proxy.save(path_resultados)
355
  st.session_state.path_resultados_proxy = path_resultados
356
 
357
+ progress_bar.progress(85, text="Gerando Hologramas Estáticos...")
358
+ m_heat = mesh_resultados_proxy.copy(); m_heat.points /= 1000.0
 
 
 
359
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
360
+ pl = pv.Plotter(off_screen=True); pl.add_mesh(m_heat, scalars='Heat', cmap="hot", smooth_shading=True)
 
361
  pl.export_gltf(tmp.name)
362
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
363
 
364
+ m_solid = mesh_resultados_proxy.copy(); m_solid.points /= 1000.0
 
 
365
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
366
+ pl = pv.Plotter(off_screen=True); pl.add_mesh(m_solid, scalars='Solidificacao', cmap="turbo", smooth_shading=True)
 
367
  pl.export_gltf(tmp.name)
368
  with open(tmp.name, "rb") as f: st.session_state.b64_solidificacao = base64.b64encode(f.read()).decode()
369
 
370
+ m_rec = mesh_pesada.copy(); m_rec.compute_normals(inplace=True); m_def = m_rec.warp_by_scalar(scalars='Risco', factor=-10.0); m_def.points /= 1000.0
 
 
 
 
371
  with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
372
+ pl = pv.Plotter(off_screen=True); pl.add_mesh(m_def, scalars='Risco', cmap="hot", smooth_shading=True)
 
373
  pl.export_gltf(tmp.name)
374
  with open(tmp.name, "rb") as f: st.session_state.b64_rechupe_x10 = base64.b64encode(f.read()).decode()
375
 
 
382
  if st.button("⬅️ Voltar"): st.session_state.step = 3; st.rerun()
383
 
384
  # ==========================================
385
+ # ETAPA 4: LAUDO
386
  # ==========================================
387
  elif st.session_state.step == 4:
388
  st.header("4. Simulação: Laudo da Qualidade")
 
391
  with col_tempo:
392
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {st.session_state.t_sol_minutos} min {st.session_state.t_sol_segundos} s**")
393
  with col_video:
394
+ if st.button("🎬 Painel de Extração Temporal", help="Gera os frames animados", use_container_width=True):
395
  st.session_state.step = 4.5
396
  st.rerun()
397
 
 
398
  col_v1, col_v2, col_v3 = st.columns(3)
399
  p_m = [st.session_state.p_riser_real[0]/1000.0, st.session_state.p_riser_real[1]/1000.0, st.session_state.p_riser_real[2]/1000.0]
400
 
 
402
  st.write("🔥 **1. Preenchimento Térmico**")
403
  html_termico = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
404
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_termico}" style="width: 100%; height: 320px; background-color: #1e1e1e;" camera-controls shadow-intensity="1">
405
+ <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: #00BFFF; width: 14px; height: 14px; border-radius: 50%; box-shadow: 0 0 10px #00BFFF;"></button>
406
  </model-viewer>"""
407
  components.html(html_termico, height=360)
408
 
409
  with col_v2:
410
  st.write("🌈 **2. Mapa de Solidificação (Turbo)**")
411
+ st.caption("Frio (Azul) = Congela Rápido | Quente (Vermelho) = Lento")
412
  html_solid = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
413
  <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_solidificacao}" style="width: 100%; height: 320px; background-color: #1e1e1e;" camera-controls shadow-intensity="1"></model-viewer>"""
414
  components.html(html_solid, height=360)
 
424
  st.subheader("🤖 Diagnóstico IA")
425
  st.markdown(st.session_state.relatorio_ia)
426
  with c_btn:
 
427
  st.write("")
428
  if HAS_FPDF and st.session_state.relatorio_pdf:
429
  st.download_button("📄 Baixar Laudo (.PDF)", st.session_state.relatorio_pdf, "Laudo_CastingSim.pdf", "application/pdf", type="primary", use_container_width=True)
 
431
  st.session_state.step = 3; st.rerun()
432
 
433
  # ==========================================
434
+ # ETAPA 4.5: RENDER FARM COM CILINDRO DINÂMICO
435
  # ==========================================
436
  elif st.session_state.step == 4.5:
437
  st.title("🎬 Extração Cinemática com Derramador Físico")
 
438
  prog = st.progress(0)
439
 
440
  try:
441
  mesh_proxy = pv.read(st.session_state.path_resultados_proxy)
442
  mesh_molde = pv.read(st.session_state.path_proxy_stl)
443
+ mesh_molde.rotate_x(st.session_state.rot_x, inplace=True); mesh_molde.rotate_y(st.session_state.rot_y, inplace=True); mesh_molde.rotate_z(st.session_state.rot_z, inplace=True)
 
 
444
 
 
445
  px, py, pz = st.session_state.p_riser_real
446
+ eixo = st.session_state.eixo_vaz
447
+ bounds = mesh_proxy.bounds
 
448
 
449
+ # Orientando o Cilindro do Massalote com base no Eixo escolhido!
450
+ if eixo == 'Y':
451
+ grav_bounds = bounds[2:4]
452
+ dir_vec = (0, 1, 0)
453
+ altura_sprue = (grav_bounds[1] - grav_bounds[0]) * 1.5
454
+ centro_grav = grav_bounds[0] + (altura_sprue / 2.0)
455
+ center = (px, centro_grav, pz)
456
+ elif eixo == 'Z':
457
+ grav_bounds = bounds[4:6]
458
+ dir_vec = (0, 0, 1)
459
+ altura_sprue = (grav_bounds[1] - grav_bounds[0]) * 1.5
460
+ centro_grav = grav_bounds[0] + (altura_sprue / 2.0)
461
+ center = (px, py, centro_grav)
462
+ elif eixo == 'X':
463
+ grav_bounds = bounds[0:2]
464
+ dir_vec = (1, 0, 0)
465
+ altura_sprue = (grav_bounds[1] - grav_bounds[0]) * 1.5
466
+ centro_grav = grav_bounds[0] + (altura_sprue / 2.0)
467
+ center = (centro_grav, py, pz)
468
 
469
+ cilindro = pv.Cylinder(center=center, direction=dir_vec, radius=st.session_state.diam_vaz/2.0, height=altura_sprue).triangulate()
470
  mesh_animacao = mesh_proxy.merge(cilindro)
471
 
 
472
  pts_anim = mesh_animacao.points
473
+ if eixo == 'Y':
474
+ grav_anim = pts_anim[:, 1]
475
+ r_coords = np.sqrt((pts_anim[:, 0] - px)**2 + (pts_anim[:, 2] - pz)**2)
476
+ elif eixo == 'Z':
477
+ grav_anim = pts_anim[:, 2]
478
+ r_coords = np.sqrt((pts_anim[:, 0] - px)**2 + (pts_anim[:, 1] - py)**2)
479
+ elif eixo == 'X':
480
+ grav_anim = pts_anim[:, 0]
481
+ r_coords = np.sqrt((pts_anim[:, 1] - py)**2 + (pts_anim[:, 2] - pz)**2)
482
+
483
+ grav_norm = (grav_anim - np.min(grav_anim)) / (np.max(grav_anim) - np.min(grav_anim) + 1e-6)
484
  r_eff = np.maximum(0, r_coords - (st.session_state.diam_vaz/2.0))
485
  r_norm = r_eff / (np.max(r_eff) + 1e-6)
486
  turbulencia = np.random.normal(0, 0.08, size=mesh_animacao.n_points)
487
+ campo = (grav_norm * 0.65) + (r_norm * 0.35) + turbulencia
488
  mesh_animacao['Preenchimento_Anim'] = (campo - np.min(campo)) / (np.max(campo) - np.min(campo) + 1e-6)
489
 
490
  mesh_molde.points /= 1000.0
 
492
  st.session_state.frames_cooling = []
493
  temp_dir = tempfile.mkdtemp()
494
 
 
495
  passos = 10
496
  for i in range(1, passos + 1):
497
  lim = (1.0 / passos) * i
498
  if lim <= 0: lim = 1e-6
 
499
  f_mesh = mesh_animacao.threshold([0, lim], scalars='Preenchimento_Anim')
 
500
  pl = pv.Plotter(off_screen=True)
501
  pl.add_mesh(mesh_molde, color='white', opacity=0.1, style='wireframe')
502
  if f_mesh.n_points > 0:
 
508
  pl.close()
509
  prog.progress(int((i/passos)*40), text="[1/2] Forjando Animação de Enchimento pelo Derramador...")
510
 
 
511
  t_v = st.session_state.t_vaz
512
  t_m = st.session_state.t_molde
513
  massa = mesh_proxy['MassaTermica']
 
517
  t_instante = (i / (passos - 1)) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1)
518
  T_t = t_m + (t_v - t_m) * np.exp(-t_instante / tau)
519
  heat_norm = (T_t - t_m) / (t_v - t_m + 1e-6)
 
520
  m_cool = mesh_proxy.copy()
521
  m_cool['TempAtual'] = heat_norm
522
  m_cool.points /= 1000.0
 
545
  st.header("5. Telemetria Cinemática")
546
 
547
  modo = st.radio("Selecione o Módulo de Visualização:", ["🌊 Cinemática de Preenchimento", "❄️ Termodinâmica de Resfriamento (Fourier)"], horizontal=True)
 
548
  caminhos_alvo = st.session_state.frames_filling if "Preenchimento" in modo else st.session_state.frames_cooling
549
 
550
  if len(caminhos_alvo) > 0:
 
555
  except: pass
556
 
557
  frames_js_array = ",\n".join([f'"{b64}"' for b64 in frames_b64])
 
558
  css_thumb = "#ff4500" if "Preenchimento" in modo else "#00BFFF"
559
 
560
  html_player = f"""
 
574
  <body>
575
  <model-viewer id="mv" src="data:model/gltf-binary;base64,{frames_b64[0]}" camera-controls shadow-intensity="1"></model-viewer>
576
  <div class="controls">
577
+ <span style="font-weight: bold;">Início</span>
578
  <input type="range" min="1" max="{len(frames_b64)}" value="1" class="slider" id="frameSlider">
579
+ <span style="font-weight: bold;">Fim</span>
580
  <div class="status" id="frame-counter">Quadro: 1 / {len(frames_b64)}</div>
581
  </div>
582
  <script>