andrefbfreitas commited on
Commit
3b79049
·
verified ·
1 Parent(s): e943f55
Files changed (1) hide show
  1. app.py +94 -37
app.py CHANGED
@@ -27,7 +27,7 @@ from OCC.Core.StlAPI import StlAPI_Writer
27
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
28
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
29
 
30
- st.set_page_config(page_title="CastingSim V39", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
@@ -60,6 +60,7 @@ if 'sens' not in st.session_state: st.session_state.sens = 4.0
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
62
  if 'off_z' not in st.session_state: st.session_state.off_z = 0.0
 
63
  if 'rot_x' not in st.session_state: st.session_state.rot_x = 0
64
  if 'rot_y' not in st.session_state: st.session_state.rot_y = 0
65
  if 'rot_z' not in st.session_state: st.session_state.rot_z = 0
@@ -72,6 +73,7 @@ if 'diam_vaz' not in st.session_state: st.session_state.diam_vaz = 20.0
72
 
73
  if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
74
  if 'b64_rechupe_x10' not in st.session_state: st.session_state.b64_rechupe_x10 = ""
 
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
@@ -85,7 +87,7 @@ def compilar_pdf():
85
  pdf = FPDF()
86
  pdf.add_page()
87
  pdf.set_font("Arial", 'B', 16)
88
- pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V39", 0, 1, 'C')
89
  pdf.ln(5)
90
 
91
  pdf.set_font("Arial", 'B', 12)
@@ -181,7 +183,7 @@ def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe,
181
  relatorio.append(f"🐢 **Fluxo Laminar (Reynolds = {reynolds:.0f}):** Escoamento limpo e seguro.")
182
 
183
  if max_risco_rechupe > 0.8:
184
- relatorio.append("🚨 **ALERTA DE RECHUPE:** Estrangulamento severo nos cantos internos detectado. Aumente o derramador.")
185
  else:
186
  relatorio.append("✅ **Alimentação Saudável:** Gradiente térmico direcional preservado.")
187
 
@@ -193,7 +195,7 @@ if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
193
  st.progress(progresso_visual)
194
 
195
  if st.session_state.step not in [3.5, 4.5]:
196
- st.title("🛡️ CastingSim V39: Resfriamento de Fourier & Malha Otimizada")
197
  st.markdown("---")
198
 
199
  # ==========================================
@@ -271,6 +273,7 @@ elif st.session_state.step == 3:
271
  ry = st.slider("Rotação Y", 0, 360, value=int(st.session_state.rot_y))
272
  rz = st.slider("Rotação Z", 0, 360, value=int(st.session_state.rot_z))
273
  st.write("**Centro do Derramador (mm)**")
 
274
  ox = st.number_input("Eixo X", value=float(st.session_state.off_x), step=1.0)
275
  oy = st.number_input("Eixo Y", value=float(st.session_state.off_y), step=1.0)
276
  oz = st.number_input("Eixo Z", value=float(st.session_state.off_z), step=1.0)
@@ -300,7 +303,7 @@ elif st.session_state.step == 3:
300
  st.session_state.step = 3.5; st.rerun()
301
 
302
  # ==========================================
303
- # ETAPA 3.5: NÚCLEO FÍSICO COM FOURIER E REAPROVEITAMENTO
304
  # ==========================================
305
  elif st.session_state.step == 3.5:
306
  st.title("⏳ Processando Solver FEM & Fourier...")
@@ -313,13 +316,16 @@ elif st.session_state.step == 3.5:
313
  mesh_pesada.rotate_y(st.session_state.rot_y, inplace=True)
314
  mesh_pesada.rotate_z(st.session_state.rot_z, inplace=True)
315
 
 
 
 
 
 
 
316
  if st.session_state.sub_div > 0:
317
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
318
 
319
  pts = mesh_pesada.points
320
- px, py, pz = st.session_state.off_x, st.session_state.off_y, st.session_state.off_z
321
- p_riser_real = np.array([px, py, pz])
322
- R_vaz = st.session_state.diam_vaz / 2.0
323
 
324
  # Cinemática (Preenchimento)
325
  y_coords = pts[:, 1]
@@ -332,19 +338,25 @@ elif st.session_state.step == 3.5:
332
  calor_dinamico = (campo_fluido - np.min(campo_fluido)) / (np.max(campo_fluido) - np.min(campo_fluido) + 1e-6)
333
  mesh_pesada['Preenchimento'] = calor_dinamico
334
 
335
- progress_bar.progress(40, text="Termodinâmica Base (Rechupe)...")
336
  dist_ao_centro = np.linalg.norm(pts - mesh_pesada.center, axis=1)
337
  massa_termica = 1.0 - (dist_ao_centro / (np.max(dist_ao_centro) + 1e-6))
338
- mesh_pesada['MassaTermica'] = massa_termica # Guarda para o resfriamento
339
 
340
  curv_negativa = np.clip(-mesh_pesada.curvature(curv_type='mean'), 0, None)
341
  curv_norm = np.where(curv_negativa > np.percentile(curv_negativa, 85), curv_negativa, 0) / (np.max(curv_negativa) + 1e-6)
342
- isolamento = np.linalg.norm(pts - p_riser_real, axis=1) / (np.max(np.linalg.norm(pts - p_riser_real, axis=1)) + 1e-6)
343
 
 
344
  risco_bruto = np.clip((massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2), 0, 1)
345
  mesh_pesada['Heat'] = np.log1p(risco_bruto * 40.0) / np.log1p(40.0)
 
 
346
  mesh_pesada['Risco'] = np.clip(((massa_termica ** 3) + (curv_norm * 5.0)) * (isolamento ** 2) * 10.0, 0, 1)
347
 
 
 
 
348
  # MESTRE FUNDIDOR E TEMPOS
349
  mod_cm = (st.session_state.vol_mm3 / pv.read(st.session_state.path_stl).area) / 10
350
  num_reynolds = (st.session_state.vel_vaz * ((mod_cm * 2) / 100.0)) / 1.3e-6
@@ -356,21 +368,21 @@ elif st.session_state.step == 3.5:
356
  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)
357
  st.session_state.relatorio_pdf = compilar_pdf()
358
 
359
- # --- A GRANDE OTIMIZAÇÃO V39 ---
360
  progress_bar.progress(70, text="Transferindo Conhecimento Matemático para Malha Otimizada...")
361
  mesh_proxy = pv.read(st.session_state.path_proxy_stl)
362
  mesh_proxy.rotate_x(st.session_state.rot_x, inplace=True)
363
  mesh_proxy.rotate_y(st.session_state.rot_y, inplace=True)
364
  mesh_proxy.rotate_z(st.session_state.rot_z, inplace=True)
365
 
366
- # Transfere os tensores da pesada para a leve (Isso salva a vida da Tela 5)
367
  mesh_resultados_proxy = mesh_proxy.sample(mesh_pesada)
368
  temp_dir = tempfile.mkdtemp()
369
  path_resultados = os.path.join(temp_dir, "resultados_proxy.vtk")
370
  mesh_resultados_proxy.save(path_resultados)
371
  st.session_state.path_resultados_proxy = path_resultados
372
 
373
- progress_bar.progress(90, text="Gerando Hologramas Estáticos...")
 
374
  # Exporta Heat Base
375
  m_heat = mesh_resultados_proxy.copy()
376
  m_heat.points /= 1000.0
@@ -380,7 +392,16 @@ elif st.session_state.step == 3.5:
380
  pl.export_gltf(tmp.name)
381
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
382
 
383
- # Exporta Rechupe x10 a partir da malha pesada (para manter qualidade do defeito visual)
 
 
 
 
 
 
 
 
 
384
  m_rec = mesh_pesada.copy()
385
  m_rec.compute_normals(inplace=True)
386
  m_def = m_rec.warp_by_scalar(scalars='Risco', factor=-10.0)
@@ -400,7 +421,7 @@ elif st.session_state.step == 3.5:
400
  if st.button("⬅️ Voltar"): st.session_state.step = 3; st.rerun()
401
 
402
  # ==========================================
403
- # ETAPA 4: LAUDO
404
  # ==========================================
405
  elif st.session_state.step == 4:
406
  st.header("4. Simulação: Laudo da Qualidade")
@@ -413,45 +434,82 @@ elif st.session_state.step == 4:
413
  st.session_state.step = 4.5
414
  st.rerun()
415
 
 
416
  col_v1, col_v2, col_v3 = st.columns(3)
417
- p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
418
 
419
  with col_v1:
420
- st.write("🔥 **Mapa Térmico Base**")
421
  html_termico = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
422
- <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_termico}" style="width: 100%; height: 350px; background-color: #1e1e1e;" camera-controls shadow-intensity="1">
423
  <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>
424
  </model-viewer>"""
425
- components.html(html_termico, height=400)
426
 
427
  with col_v2:
428
- st.write("⚠️ **Rechupe (Deformação x10)**")
429
- components.html(f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
430
- <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_rechupe_x10}" style="width: 100%; height: 350px; background-color: #1e1e1e;" camera-controls shadow-intensity="1"></model-viewer>""", height=400)
 
 
431
 
432
  with col_v3:
 
 
 
 
 
 
 
433
  st.subheader("🤖 Diagnóstico IA")
434
  st.markdown(st.session_state.relatorio_ia)
 
 
 
435
  if HAS_FPDF and st.session_state.relatorio_pdf:
436
  st.download_button("📄 Baixar Laudo (.PDF)", st.session_state.relatorio_pdf, "Laudo_CastingSim.pdf", "application/pdf", type="primary", use_container_width=True)
437
-
438
- if st.button("⬅️ Voltar"): st.session_state.step = 3; st.rerun()
439
 
440
  # ==========================================
441
- # ETAPA 4.5: RENDER FARM OTIMIZADO (PREENCHIMENTO E FOURIER)
442
  # ==========================================
443
  elif st.session_state.step == 4.5:
444
- st.title("🎬 Extração em Malha Otimizada")
445
- st.info("Utilizando malha proxy para evitar o corte da conexão. Gerando Escomento + Resfriamento de Fourier.")
446
  prog = st.progress(0)
447
 
448
  try:
449
- # LER MALHA PROXY COM TUDO JÁ CALCULADO!
450
  mesh_proxy = pv.read(st.session_state.path_resultados_proxy)
451
  mesh_molde = pv.read(st.session_state.path_proxy_stl)
452
- 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)
453
- mesh_molde.points /= 1000.0
 
 
 
 
 
 
 
 
 
 
454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  st.session_state.frames_filling = []
456
  st.session_state.frames_cooling = []
457
  temp_dir = tempfile.mkdtemp()
@@ -461,7 +519,9 @@ elif st.session_state.step == 4.5:
461
  for i in range(1, passos + 1):
462
  lim = (1.0 / passos) * i
463
  if lim <= 0: lim = 1e-6
464
- f_mesh = mesh_proxy.threshold([0, lim], scalars='Preenchimento')
 
 
465
  pl = pv.Plotter(off_screen=True)
466
  pl.add_mesh(mesh_molde, color='white', opacity=0.1, style='wireframe')
467
  if f_mesh.n_points > 0:
@@ -471,18 +531,16 @@ elif st.session_state.step == 4.5:
471
  pl.export_gltf(path)
472
  st.session_state.frames_filling.append(path)
473
  pl.close()
474
- prog.progress(int((i/passos)*40), text="[1/2] Forjando Animação de Enchimento...")
475
 
476
  # 2. GERAR VÍDEO DE RESFRIAMENTO TÉRMICO (LEI DE FOURIER) (10 Frames)
477
  t_v = st.session_state.t_vaz
478
  t_m = st.session_state.t_molde
479
  massa = mesh_proxy['MassaTermica']
480
- # Constante temporal baseada na espessura
481
  tau = (massa + 0.1) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1) / 3.0
482
 
483
  for i in range(passos):
484
  t_instante = (i / (passos - 1)) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1)
485
- # Equação de Fourier Decadente
486
  T_t = t_m + (t_v - t_m) * np.exp(-t_instante / tau)
487
  heat_norm = (T_t - t_m) / (t_v - t_m + 1e-6)
488
 
@@ -491,7 +549,6 @@ elif st.session_state.step == 4.5:
491
  m_cool.points /= 1000.0
492
 
493
  pl = pv.Plotter(off_screen=True)
494
- # Para visualização térmica, não renderizamos a casca do molde
495
  pl.add_mesh(m_cool, scalars='TempAtual', cmap="turbo", smooth_shading=True, clim=[0, 1])
496
  path = os.path.join(temp_dir, f"cool_{i}.glb")
497
  pl.export_gltf(path)
@@ -527,7 +584,7 @@ elif st.session_state.step == 5:
527
 
528
  frames_js_array = ",\n".join([f'"{b64}"' for b64 in frames_b64])
529
 
530
- css_thumb = "#00BFFF" if "Preenchimento" in modo else "#ff00ff"
531
 
532
  html_player = f"""
533
  <html>
 
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>
 
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
62
  if 'off_z' not in st.session_state: st.session_state.off_z = 0.0
63
+ if 'p_riser_real' not in st.session_state: st.session_state.p_riser_real = [0.0, 0.0, 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
 
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
 
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)
 
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
 
 
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
  # ==========================================
 
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)
 
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...")
 
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])
323
+ R_vaz = st.session_state.diam_vaz / 2.0
324
+
325
  if st.session_state.sub_div > 0:
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]
 
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
 
341
+ progress_bar.progress(40, text="Calculando Direcionalidade Térmica...")
342
  dist_ao_centro = np.linalg.norm(pts - mesh_pesada.center, axis=1)
343
  massa_termica = 1.0 - (dist_ao_centro / (np.max(dist_ao_centro) + 1e-6))
344
+ mesh_pesada['MassaTermica'] = massa_termica
345
 
346
  curv_negativa = np.clip(-mesh_pesada.curvature(curv_type='mean'), 0, None)
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
 
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)
375
  mesh_proxy.rotate_y(st.session_state.rot_y, inplace=True)
376
  mesh_proxy.rotate_z(st.session_state.rot_z, inplace=True)
377
 
 
378
  mesh_resultados_proxy = mesh_proxy.sample(mesh_pesada)
379
  temp_dir = tempfile.mkdtemp()
380
  path_resultados = os.path.join(temp_dir, "resultados_proxy.vtk")
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
 
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)
 
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")
 
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
 
441
  with col_v1:
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)
455
 
456
  with col_v3:
457
+ st.write("⚠️ **3. Rechupe (Deformação x10)**")
458
+ components.html(f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
459
+ <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_rechupe_x10}" style="width: 100%; height: 320px; background-color: #1e1e1e;" camera-controls shadow-intensity="1"></model-viewer>""", height=360)
460
+
461
+ st.markdown("---")
462
+ c_ia, c_btn = st.columns([3, 1])
463
+ with c_ia:
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)
471
+ if st.button("⬅️ Voltar para Geometria", use_container_width=True):
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
513
  st.session_state.frames_filling = []
514
  st.session_state.frames_cooling = []
515
  temp_dir = tempfile.mkdtemp()
 
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:
 
531
  pl.export_gltf(path)
532
  st.session_state.frames_filling.append(path)
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']
 
540
  tau = (massa + 0.1) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1) / 3.0
541
 
542
  for i in range(passos):
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
 
 
549
  m_cool.points /= 1000.0
550
 
551
  pl = pv.Plotter(off_screen=True)
 
552
  pl.add_mesh(m_cool, scalars='TempAtual', cmap="turbo", smooth_shading=True, clim=[0, 1])
553
  path = os.path.join(temp_dir, f"cool_{i}.glb")
554
  pl.export_gltf(path)
 
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"""
590
  <html>