File size: 34,147 Bytes
3aa3a0a
 
 
 
 
 
 
 
 
6d2ee9d
51e073a
3aa3a0a
 
 
 
 
 
 
d761d43
 
 
 
3aa3a0a
 
 
 
 
 
39c1427
3aa3a0a
 
 
 
 
 
 
 
 
e943f55
3aa3a0a
 
 
 
bd36a99
e943f55
6d2ee9d
3aa3a0a
 
 
 
 
 
 
 
 
 
d761d43
 
 
 
 
3aa3a0a
 
 
 
3b79049
3aa3a0a
 
 
4e3f5c3
3aa3a0a
 
b4c308a
d761d43
e943f55
 
3aa3a0a
 
 
 
 
51e87f9
5a497aa
 
 
3aa3a0a
 
 
 
 
39c1427
3aa3a0a
 
 
 
a92ab69
51e87f9
3aa3a0a
 
 
 
 
 
 
 
 
 
 
96b1240
3aa3a0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e943f55
3aa3a0a
3dc2c42
e943f55
3dc2c42
e943f55
 
 
3dc2c42
d761d43
 
3dc2c42
e943f55
 
bd36a99
 
e943f55
bd36a99
d761d43
3aa3a0a
bd36a99
3aa3a0a
 
 
d761d43
 
 
 
 
3aa3a0a
 
5a497aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3aa3a0a
1eee5db
d761d43
3aa3a0a
1eee5db
ea3ce45
3aa3a0a
 
 
e943f55
3aa3a0a
 
 
 
ea3ce45
3aa3a0a
e943f55
3aa3a0a
 
 
 
 
 
e943f55
3aa3a0a
 
e943f55
3aa3a0a
 
e943f55
3aa3a0a
 
e943f55
3aa3a0a
720a28a
e943f55
 
3aa3a0a
 
 
 
 
 
 
5a497aa
3aa3a0a
 
e943f55
 
3aa3a0a
 
 
 
 
 
bd36a99
3aa3a0a
 
3dc2c42
bd36a99
3aa3a0a
 
 
 
bd36a99
 
 
d761d43
3aa3a0a
 
 
 
 
 
4e3f5c3
5a497aa
4e3f5c3
5a497aa
 
 
 
 
 
 
4e3f5c3
 
 
 
39c1427
4e3f5c3
 
 
 
39c1427
 
 
 
 
 
5a497aa
3aa3a0a
 
 
 
 
bd36a99
 
 
d761d43
3aa3a0a
 
 
 
 
 
 
 
 
 
e943f55
3aa3a0a
 
5a497aa
3aa3a0a
 
77e1539
 
3aa3a0a
 
e943f55
77e1539
 
 
e943f55
 
 
3aa3a0a
77e1539
 
 
 
 
 
3b79049
77e1539
d761d43
51e87f9
3a8a149
d761d43
77e1539
 
 
 
 
d761d43
77e1539
 
 
 
 
d761d43
77e1539
 
 
 
 
 
51e87f9
77e1539
 
 
 
 
 
 
 
 
 
 
d761d43
77e1539
 
a8c1c80
 
 
 
 
 
77e1539
 
d761d43
a8c1c80
 
 
77e1539
a8c1c80
 
77e1539
6d2ee9d
77e1539
3a8a149
77e1539
e943f55
77e1539
 
3b79049
6d2ee9d
e943f55
77e1539
 
 
3b79049
e943f55
 
51e87f9
 
e943f55
 
 
77e1539
e943f55
3aa3a0a
77e1539
e943f55
 
 
 
3aa3a0a
51e87f9
77e1539
 
 
e943f55
 
77e1539
e943f55
 
d761d43
77e1539
6d2ee9d
d761d43
e943f55
6d2ee9d
 
77e1539
3b79049
d761d43
3b79049
 
 
77e1539
51e073a
d761d43
e943f55
51e073a
 
6d2ee9d
 
 
 
e943f55
6d2ee9d
e943f55
3aa3a0a
 
5a497aa
3aa3a0a
 
 
ba39a0f
3aa3a0a
ba39a0f
ea3ce45
ba39a0f
 
 
 
 
ea3ce45
ba39a0f
a92ab69
ba39a0f
 
 
 
 
 
 
 
5a497aa
ba39a0f
 
 
ea3ce45
ba39a0f
5a497aa
ba39a0f
 
 
 
5a497aa
 
ba39a0f
 
 
 
5a497aa
ba39a0f
 
 
 
 
 
 
 
 
1eee5db
 
51e87f9
1eee5db
 
a92ab69
77e1539
e943f55
1eee5db
 
77e1539
3b79049
a92ab69
77e1539
a92ab69
77e1539
a92ab69
 
 
e943f55
 
c13a92e
b4c308a
e943f55
1eee5db
e943f55
 
77e1539
 
a92ab69
e943f55
a92ab69
 
e943f55
 
 
a92ab69
e943f55
 
 
 
77e1539
e943f55
 
 
77e1539
e943f55
 
 
 
 
 
77e1539
 
e943f55
 
1eee5db
e943f55
 
 
 
 
 
77e1539
e943f55
 
1eee5db
 
 
e943f55
1eee5db
e943f55
 
1eee5db
 
51e87f9
1eee5db
 
e943f55
1eee5db
e943f55
 
 
 
65d245f
e943f55
65d245f
e943f55
 
b4c308a
65d245f
3b79049
e943f55
65d245f
 
 
 
 
 
 
 
 
e943f55
65d245f
 
 
 
 
 
 
d761d43
65d245f
d761d43
e943f55
65d245f
 
 
 
 
 
 
 
 
 
e943f55
65d245f
 
 
 
 
 
b4c308a
e943f55
1eee5db
 
 
e943f55
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
import os
import streamlit as st
import streamlit.components.v1 as components
import pyvista as pv
import numpy as np
import tempfile
import base64
import time
import hashlib
import traceback
import gc

try:
    from fpdf import FPDF
    HAS_FPDF = True
except ImportError:
    HAS_FPDF = False

# --- SETUP DE INFRAESTRUTURA ---
os.environ['PYVISTA_OFF_SCREEN'] = 'true'
os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'

from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
from OCC.Core.BRepGProp import brepgprop
from OCC.Core.GProp import GProp_GProps
from OCC.Core.StlAPI import StlAPI_Writer

st.set_page_config(page_title="CastingSim V49", layout="wide")

st.markdown("""
    <style>
    .stApp { animation: fadeIn 0.4s ease-in-out; }
    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    </style>
""", unsafe_allow_html=True)

# ==========================================
# INICIALIZAÇÃO DE ESTADOS
# ==========================================
if 'step' not in st.session_state: st.session_state.step = 1
if 'cache_hash' not in st.session_state: st.session_state.cache_hash = ""
if 'path_stl' not in st.session_state: st.session_state.path_stl = None
if 'path_proxy_stl' not in st.session_state: st.session_state.path_proxy_stl = None 
if 'path_resultados_proxy' not in st.session_state: st.session_state.path_resultados_proxy = None 
if 'b64_proxy' not in st.session_state: st.session_state.b64_proxy = "" 
if 'vol_mm3' not in st.session_state: st.session_state.vol_mm3 = 0.0
if 'coord_iniciada' not in st.session_state: st.session_state.coord_iniciada = False

if 'lin_def' not in st.session_state: st.session_state.lin_def = 0.1
if 'ang_def' not in st.session_state: st.session_state.ang_def = 0.1
if 'sub_div' not in st.session_state: st.session_state.sub_div = 1 

if 'liga' not in st.session_state: st.session_state.liga = "SAE 305"
if 't_vaz' not in st.session_state: st.session_state.t_vaz = 720
if 't_molde' not in st.session_state: st.session_state.t_molde = 300 
if 'mat_molde' not in st.session_state: st.session_state.mat_molde = "Aço 1045"
if 'tinta_ceramica' not in st.session_state: st.session_state.tinta_ceramica = True
if 'espessura_tinta' not in st.session_state: st.session_state.espessura_tinta = 5.0 
if 'vel_vaz' not in st.session_state: st.session_state.vel_vaz = 1.0 
if 'diam_vaz' not in st.session_state: st.session_state.diam_vaz = 20.0 

if 'off_x' not in st.session_state: st.session_state.off_x = 0.0
if 'off_y' not in st.session_state: st.session_state.off_y = 0.0
if 'off_z' not in st.session_state: st.session_state.off_z = 0.0
if 'p_riser_real' not in st.session_state: st.session_state.p_riser_real = [0.0, 0.0, 0.0]
if 'rot_x' not in st.session_state: st.session_state.rot_x = 0
if 'rot_y' not in st.session_state: st.session_state.rot_y = 0
if 'rot_z' not in st.session_state: st.session_state.rot_z = 0
if 'eixo_vaz' not in st.session_state: st.session_state.eixo_vaz = "Z" 

if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
if 'b64_rechupe_x10' not in st.session_state: st.session_state.b64_rechupe_x10 = ""
if 'b64_solidificacao' not in st.session_state: st.session_state.b64_solidificacao = "" 
if 'frames_filling' not in st.session_state: st.session_state.frames_filling = [] 
if 'frames_cooling' not in st.session_state: st.session_state.frames_cooling = [] 
if 't_sol_minutos' not in st.session_state: st.session_state.t_sol_minutos = 0
if 't_sol_segundos' not in st.session_state: st.session_state.t_sol_segundos = 0
if 'relatorio_ia' not in st.session_state: st.session_state.relatorio_ia = ""
if 'relatorio_pdf' not in st.session_state: st.session_state.relatorio_pdf = None

# --- FUNÇÕES AUXILIARES ---
def atualizar_eixo():
    st.session_state.eixo_vaz = st.session_state.eixo_sel_key

def compilar_pdf():
    if not HAS_FPDF: return None
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", 'B', 16)
    pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V49", 0, 1, 'C')
    pdf.ln(5)
    pdf.set_font("Arial", 'B', 12)
    pdf.cell(0, 10, "1. Parametros de Processo", 0, 1)
    pdf.set_font("Arial", '', 11)
    pdf.cell(0, 6, f"Liga: {st.session_state.liga} | Vel. Vazamento: {st.session_state.vel_vaz} m/s | Derramador Ø: {st.session_state.diam_vaz} mm", 0, 1)
    pdf.cell(0, 6, f"Eixo de Gravidade Visual (Solver): {st.session_state.eixo_vaz}", 0, 1)
    pdf.cell(0, 6, f"Molde: Coquilha de {st.session_state.mat_molde}", 0, 1)
    if st.session_state.tinta_ceramica:
        pdf.cell(0, 6, f"Revestimento: Tinta Ceramica (Espessura: {st.session_state.espessura_tinta} mm)", 0, 1)
    pdf.cell(0, 6, f"Temps: Vazamento {st.session_state.t_vaz} C | Coquilha {st.session_state.t_molde} C", 0, 1)
    pdf.ln(5)
    pdf.set_font("Arial", 'B', 12)
    pdf.cell(0, 10, "2. Resultados Metrologicos", 0, 1)
    pdf.set_font("Arial", '', 11)
    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)
    pdf.ln(5)
    pdf.set_font("Arial", 'B', 12)
    pdf.cell(0, 10, "3. Diagnostico IA (Mestre Fundidor)", 0, 1)
    pdf.set_font("Arial", '', 11)
    texto_limpo = st.session_state.relatorio_ia.replace("*", "").replace("🌪️", ">").replace("🌊", ">").replace("🚨", ">").replace("⚡", ">").replace("✅", ">").replace("⏳", ">").replace("🐢", ">")
    pdf.multi_cell(0, 6, texto_limpo)
    return pdf.output(dest='S').encode('latin-1')

def gerar_hash(file_bytes, lin_def, ang_def):
    m = hashlib.md5()
    m.update(file_bytes)
    m.update(str(lin_def).encode('utf-8'))
    m.update(str(ang_def).encode('utf-8'))
    return m.hexdigest()

def processar_malha_com_telemetria(file_bytes, lin_def, ang_def):
    prog_bar = st.progress(0, text="⚙️ 0% - Iniciando leitura do arquivo STEP...")
    temp_dir = tempfile.mkdtemp()
    path_in = os.path.join(temp_dir, "peca.step")
    with open(path_in, "wb") as f: f.write(file_bytes)
    reader = STEPControl_Reader()
    reader.ReadFile(path_in)
    reader.TransferRoots()
    shape = reader.OneShape()
    prog_bar.progress(20, text="📐 20% - Extraindo geometria B-Rep...")
    props = GProp_GProps()
    brepgprop.VolumeProperties(shape, props)
    vol_mm3 = props.Mass()
    prog_bar.progress(60, text=f"🕸️ 60% - Tesselação CAD Base...")
    mesh_gen = BRepMesh_IncrementalMesh(shape, lin_def, False, ang_def, True)
    mesh_gen.Perform()
    path_stl = os.path.join(temp_dir, "malha_alta.stl")
    StlAPI_Writer().Write(shape, path_stl)
    mesh_alta = pv.read(path_stl)
    path_proxy = os.path.join(temp_dir, "malha_proxy.stl")
    try:
        if mesh_alta.n_faces > 3000:
            fator = 1.0 - (3000.0 / mesh_alta.n_faces)
            fator = np.clip(fator, 0.10, 0.95) 
            mesh_proxy = mesh_alta.decimate(fator)
        else: mesh_proxy = mesh_alta
    except: mesh_proxy = mesh_alta 
    mesh_proxy.save(path_proxy)
    mesh_proxy_visual = mesh_proxy.copy()
    mesh_proxy_visual.points /= 1000.0
    with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
        plotter = pv.Plotter(off_screen=True)
        plotter.add_mesh(mesh_proxy_visual, color="#cccccc", lighting=False)
        plotter.export_gltf(tmp.name)
        with open(tmp.name, "rb") as f: b64_final = base64.b64encode(f.read()).decode()
    prog_bar.empty() 
    return path_stl, path_proxy, vol_mm3, b64_final

def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe, reynolds, velocidade):
    relatorio = []
    if reynolds > 5000: relatorio.append(f"🌪️ **Turbulência Crítica (Reynolds = {reynolds:.0f}):** Risco de aprisionamento de gás.")
    elif reynolds > 2000: relatorio.append(f"🌊 **Fluxo Transiente (Reynolds = {reynolds:.0f}):** Velocidade típica para coquilhas.")
    else: relatorio.append(f"🐢 **Fluxo Laminar (Reynolds = {reynolds:.0f}):** Escoamento limpo e seguro.")
    if max_risco_rechupe > 0.8: relatorio.append("🚨 **ALERTA DE RECHUPE:** Estrangulamento severo nos cantos internos detectado. Ajuste o derramador.")
    else: relatorio.append("✅ **Alimentação Saudável:** Gradiente térmico direcional preservado.")
    return "\n\n".join(relatorio)

# --- GERADOR DE TEMPLATE DE LOADING ---
def gerar_html_viewer(b64_data, cor_destaque, texto_loading, hotspot=None):
    hotspot_html = ""
    if hotspot:
        hotspot_html = f'<button slot="hotspot-1" data-position="{hotspot[0]} {hotspot[1]} {hotspot[2]}" style="background-color: #00BFFF; width: 14px; height: 14px; border-radius: 50%; box-shadow: 0 0 10px #00BFFF; border: 2px solid white;"></button>'
    
    return f"""
    <html>
    <head>
        <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
        <style>
            body {{ margin: 0; background-color: #1e1e1e; overflow: hidden; font-family: sans-serif; position: relative; }}
            #loader {{ position: absolute; top:0; left:0; width:100%; height:100%; background:#1e1e1e; color:{cor_destaque}; display:flex; align-items:center; justify-content:center; flex-direction:column; z-index:10; transition: opacity 0.5s ease-out; }}
            .spinner {{ border: 4px solid #333; border-top: 4px solid {cor_destaque}; border-radius: 50%; width: 36px; height: 36px; animation: spin 1s linear infinite; margin-bottom: 12px; }}
            @keyframes spin {{ 0% {{ transform: rotate(0deg); }} 100% {{ transform: rotate(360deg); }} }}
            model-viewer {{ width: 100%; height: 320px; }}
        </style>
    </head>
    <body>
        <div id="loader">
            <div class="spinner"></div>
            <div style="font-weight: bold; font-size: 13px; text-align: center;">{texto_loading}</div>
        </div>
        <model-viewer id="mv" src="data:model/gltf-binary;base64,{b64_data}" camera-controls shadow-intensity="1">
            {hotspot_html}
        </model-viewer>
        <script>
            document.getElementById('mv').addEventListener('load', () => {{
                const loader = document.getElementById('loader');
                loader.style.opacity = '0';
                setTimeout(() => loader.style.display = 'none', 500);
            }});
        </script>
    </body>
    </html>
    """

# --- INTERFACE ---
if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
    st.progress(min(st.session_state.step, 4) / 4)

if st.session_state.step not in [3.5, 4.5]:
    st.title("🛡️ CastingSim V49")
    st.markdown("---")

# ==========================================
# ETAPAS 1 e 2
# ==========================================
if st.session_state.step == 1:
    st.header("1. Refino Metrológico (Controle de Malha)")
    c1, c2, c3 = st.columns(3)
    with c1: st.session_state.lin_def = st.number_input("Deflexão Linear (mm)", 0.0005, 1.0, value=st.session_state.lin_def, format="%.4f", step=0.0001)
    with c2: st.session_state.ang_def = st.slider("Deflexão Angular (Rad)", 0.05, 1.0, value=st.session_state.ang_def)
    with c3: st.session_state.sub_div = st.slider("Refino Solver (Subdivisão)", 0, 3, value=st.session_state.sub_div)
    if st.button("Avançar para Parâmetros ➡️", type="primary"): st.session_state.step = 2; st.rerun()

elif st.session_state.step == 2:
    st.header("2. Termodinâmica e Mecânica dos Fluidos")
    c_molde1, c_molde2, c_molde3 = st.columns(3)
    with c_molde1:
        st.session_state.mat_molde = st.selectbox("Material da Coquilha", ["Aço 1045", "Ferro Nodular"], index=0)
        st.session_state.t_molde = st.number_input("Temp. Coquilha (°C)", value=st.session_state.t_molde)
    with c_molde2:
        st.session_state.tinta_ceramica = st.checkbox("Uso de Tinta Cerâmica", value=st.session_state.tinta_ceramica)
    with c_molde3:
        if st.session_state.tinta_ceramica:
            st.session_state.espessura_tinta = st.number_input("Espessura Tinta (mm)", value=st.session_state.espessura_tinta, step=0.5)
    st.markdown("---")
    c_fluido1, c_fluido2, c_fluido3 = st.columns(3)
    with c_fluido1: st.session_state.liga = st.selectbox("Liga de Alumínio", ["SAE 305", "SAE 306", "SAE 329"], index=0)
    with c_fluido2: st.session_state.t_vaz = st.number_input("Temp. Vazamento (°C)", value=st.session_state.t_vaz)
    with c_fluido3: 
        st.session_state.vel_vaz = st.number_input("Vel. Vazamento (m/s)", value=st.session_state.vel_vaz, step=0.1)
        st.session_state.diam_vaz = st.number_input("Ø Derramador (mm)", value=st.session_state.diam_vaz, step=1.0) 
    c_b1, c_b2 = st.columns([1, 8])
    with c_b1:
        if st.button("⬅️ Voltar"): st.session_state.step = 1; st.rerun()
    with c_b2:
        if st.button("Avançar para Geometria ➡️", type="primary"): st.session_state.step = 3; st.rerun()

# ==========================================
# ETAPA 3
# ==========================================
elif st.session_state.step == 3:
    st.header("3. Inspeção e Ponto de Vazamento")
    arquivo = st.file_uploader("Upload STEP", type=['step', 'stp'])

    if arquivo:
        file_bytes = arquivo.getvalue()
        current_hash = gerar_hash(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
        
        if st.session_state.cache_hash != current_hash:
            path_stl, path_proxy_stl, vol_mm3, b64_final = processar_malha_com_telemetria(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
            st.session_state.cache_hash = current_hash
            st.session_state.path_stl = path_stl
            st.session_state.path_proxy_stl = path_proxy_stl
            st.session_state.b64_proxy = b64_final 
            st.session_state.vol_mm3 = vol_mm3
            st.session_state.coord_iniciada = False 
        
        if not st.session_state.coord_iniciada:
            mesh_leitura = pv.read(st.session_state.path_proxy_stl)
            c = mesh_leitura.center
            b = mesh_leitura.bounds
            st.session_state.off_x, st.session_state.off_y, st.session_state.off_z = float(c[0]), float(c[1]), float(b[5])
            st.session_state.coord_iniciada = True

        col_form, col_view = st.columns([1, 2])
        
        with col_form:
            st.markdown("---")
            st.write("**Controle de Gravidade Visual Absoluta**")
            st.caption("Selecione o eixo que aponta para CIMA na sua visualização atual.")
            
            eixo_sel = st.selectbox(
                "Eixo Vertical (Gravidade Invertida)", 
                ["X", "Y", "Z"], 
                index=["X", "Y", "Z"].index(st.session_state.eixo_vaz),
                key="eixo_sel_key",
                on_change=atualizar_eixo
            )
            st.markdown("---")
            rx = st.slider("Rotação Visual X (Tombo)", 0, 360, value=int(st.session_state.rot_x))
            ry = st.slider("Rotação Visual Y (Tombo)", 0, 360, value=int(st.session_state.rot_y))
            rz = st.slider("Rotação Visual Z (Tombo)", 0, 360, value=int(st.session_state.rot_z))
            st.write("**Centro Local do Furo (mm)**")
            ox = st.number_input("Eixo X", value=float(st.session_state.off_x), step=1.0)
            oy = st.number_input("Eixo Y", value=float(st.session_state.off_y), step=1.0)
            oz = st.number_input("Eixo Z", value=float(st.session_state.off_z), step=1.0)
            
            # A MÁGICA DA V49: Atualização direta das variáveis do Streamlit
            st.session_state.rot_x, st.session_state.rot_y, st.session_state.rot_z = rx, ry, rz
            st.session_state.off_x, st.session_state.off_y, st.session_state.off_z = ox, oy, oz
            
            # Botão agora é um st.button clássico
            if st.button("🔄 Atualizar Visualização"):
                st.rerun()

        with col_view:
            p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
            html = f"""
                <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
                <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_proxy}" 
                              orientation="{st.session_state.rot_x}deg {st.session_state.rot_y}deg {st.session_state.rot_z}deg"
                              style="width: 100%; height: 480px; background-color: #f4f6f9;" camera-controls>
                    <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>
                </model-viewer>
            """
            components.html(html, height=500)

    c_b1, c_b2 = st.columns([1, 8])
    with c_b1:
        if st.button("⬅️ Voltar"): st.session_state.step = 2; st.rerun()
    with c_b2:
        if arquivo:
            if st.button("🔥 RODAR SOLVER FEM ➡️", type="primary"): 
                st.session_state.step = 3.5; st.rerun()

# ==========================================
# ETAPA 3.5: SOLVER FÍSICO E MATRIZ
# ==========================================
elif st.session_state.step == 3.5:
    st.title("⏳ Processando Matriz Euleriana & Fusão de Malha...")
    progress_bar = st.progress(0, text="Calculando Rotações Absolutas...")
    
    try:
        mesh_pesada = pv.read(st.session_state.path_stl)
        if st.session_state.sub_div > 0:
            mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
            
        mesh_pesada.rotate_x(st.session_state.rot_x, inplace=True)
        mesh_pesada.rotate_y(st.session_state.rot_y, inplace=True)
        mesh_pesada.rotate_z(st.session_state.rot_z, inplace=True)
        
        ponto_matriz = pv.PolyData([[st.session_state.off_x, st.session_state.off_y, st.session_state.off_z]])
        ponto_matriz.rotate_x(st.session_state.rot_x, inplace=True)
        ponto_matriz.rotate_y(st.session_state.rot_y, inplace=True)
        ponto_matriz.rotate_z(st.session_state.rot_z, inplace=True)
        px_rot, py_rot, pz_rot = ponto_matriz.points[0]
        st.session_state.p_riser_real = [px_rot, py_rot, pz_rot]
        
        R_vaz = st.session_state.diam_vaz / 2.0
        eixo = st.session_state.eixo_vaz
        bounds = mesh_pesada.bounds
        
        if eixo == 'Y':
            dir_vec = (0, 1, 0)
            topo = bounds[3] + 50.0  
            base = py_rot            
            altura = abs(topo - base)
            center = (px_rot, (topo + base)/2.0, pz_rot)
        elif eixo == 'Z':
            dir_vec = (0, 0, 1)
            topo = bounds[5] + 50.0
            base = pz_rot
            altura = abs(topo - base)
            center = (px_rot, py_rot, (topo + base)/2.0)
        elif eixo == 'X':
            dir_vec = (1, 0, 0)
            topo = bounds[1] + 50.0
            base = px_rot
            altura = abs(topo - base)
            center = ((topo + base)/2.0, py_rot, pz_rot)

        cilindro = pv.Cylinder(center=center, direction=dir_vec, radius=R_vaz, height=altura, resolution=100).triangulate()
        if st.session_state.sub_div > 0:
            cilindro = cilindro.subdivide(st.session_state.sub_div, subfilter='linear')
            
        mesh_unified = mesh_pesada.merge(cilindro)
        
        progress_bar.progress(40, text="Resolvendo Cinemática de Navier-Stokes...")
        pts = mesh_unified.points
        
        if eixo == 'Y': h_anim, r_coords = pts[:, 1], np.sqrt((pts[:, 0] - px_rot)**2 + (pts[:, 2] - pz_rot)**2)
        elif eixo == 'Z': h_anim, r_coords = pts[:, 2], np.sqrt((pts[:, 0] - px_rot)**2 + (pts[:, 1] - py_rot)**2)
        elif eixo == 'X': h_anim, r_coords = pts[:, 0], np.sqrt((pts[:, 1] - py_rot)**2 + (pts[:, 2] - pz_rot)**2)

        h_topo = np.max(h_anim)
        h_base = np.min(h_anim)
        H_total = h_topo - h_base

        campo = np.zeros(len(pts))
        mask_sprue = r_coords <= R_vaz
        mask_mold = ~mask_sprue

        campo[mask_sprue] = h_topo - h_anim[mask_sprue]
        campo[mask_mold] = H_total + (h_anim[mask_mold] - h_base) * 1.5 + (r_coords[mask_mold] - R_vaz) * 0.8
        
        turbulencia = np.random.normal(0, 0.05 * H_total, size=len(pts))
        campo += turbulencia
        campo_norm = (campo - np.min(campo)) / (np.max(campo) - np.min(campo) + 1e-6)
        mesh_unified['Preenchimento'] = campo_norm
        
        calor_dinamico = 1.0 - campo_norm 
        dist_ao_centro = np.linalg.norm(pts - mesh_unified.center, axis=1)
        massa_termica = 1.0 - (dist_ao_centro / (np.max(dist_ao_centro) + 1e-6))
        mesh_unified['MassaTermica'] = massa_termica 
        
        curv_negativa = np.clip(-mesh_unified.curvature(curv_type='mean'), 0, None)
        curv_norm = np.where(curv_negativa > np.percentile(curv_negativa, 85), curv_negativa, 0) / (np.max(curv_negativa) + 1e-6)
        
        p_riser_arr = np.array([px_rot, py_rot, pz_rot])
        isolamento = np.linalg.norm(pts - p_riser_arr, axis=1) / (np.max(np.linalg.norm(pts - p_riser_arr, axis=1)) + 1e-6)
        
        risco_bruto = np.clip((massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2), 0, 1)
        mesh_unified['Heat'] = np.log1p(risco_bruto * 40.0) / np.log1p(40.0)
        mesh_unified['Risco'] = np.clip(((massa_termica ** 3) + (curv_norm * 5.0)) * (isolamento ** 2) * 10.0, 0, 1)
        mesh_unified['Solidificacao'] = np.clip((massa_termica * 0.7) + (calor_dinamico * 0.3), 0, 1)

        mod_cm = (st.session_state.vol_mm3 / pv.read(st.session_state.path_stl).area) / 10 
        num_reynolds = (st.session_state.vel_vaz * ((mod_cm * 2) / 100.0)) / 1.3e-6
        base_b = 150 if st.session_state.mat_molde == "Aço 1045" else 180
        if st.session_state.tinta_ceramica: base_b += (st.session_state.espessura_tinta * 80) 
        t_sol_segundos_totais = (base_b * (1 + (0.002 * max(st.session_state.t_vaz - 660, 1)))) * (mod_cm ** 2)
        st.session_state.t_sol_minutos = int(t_sol_segundos_totais // 60)
        st.session_state.t_sol_segundos = int(t_sol_segundos_totais % 60)
        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_unified['Risco'])), num_reynolds, st.session_state.vel_vaz)
        st.session_state.relatorio_pdf = compilar_pdf()

        progress_bar.progress(70, text="Forjando Proxy Visual com Baixa Latência...")
        mesh_proxy = pv.read(st.session_state.path_proxy_stl)
        mesh_proxy.rotate_x(st.session_state.rot_x, inplace=True)
        mesh_proxy.rotate_y(st.session_state.rot_y, inplace=True)
        mesh_proxy.rotate_z(st.session_state.rot_z, inplace=True)
        
        proxy_cilindro = pv.Cylinder(center=center, direction=dir_vec, radius=R_vaz, height=altura, resolution=50).triangulate()
        proxy_unified = mesh_proxy.merge(proxy_cilindro)
        
        proxy_resultados = proxy_unified.sample(mesh_unified)
        temp_dir = tempfile.mkdtemp()
        path_resultados = os.path.join(temp_dir, "resultados_proxy.vtk")
        proxy_resultados.save(path_resultados)
        st.session_state.path_resultados_proxy = path_resultados

        progress_bar.progress(85, text="Gerando Hologramas Estáticos...")
        m_heat = proxy_resultados.copy(); m_heat.points /= 1000.0
        with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
            pl = pv.Plotter(off_screen=True); pl.add_mesh(m_heat, scalars='Heat', cmap="hot", smooth_shading=True)
            pl.export_gltf(tmp.name)
            with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()

        m_solid = proxy_resultados.copy(); m_solid.points /= 1000.0
        with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
            pl = pv.Plotter(off_screen=True); pl.add_mesh(m_solid, scalars='Solidificacao', cmap="turbo", smooth_shading=True)
            pl.export_gltf(tmp.name)
            with open(tmp.name, "rb") as f: st.session_state.b64_solidificacao = base64.b64encode(f.read()).decode()

        m_rec = mesh_unified.copy(); m_rec.compute_normals(inplace=True); m_def = m_rec.warp_by_scalar(scalars='Risco', factor=-10.0); m_def.points /= 1000.0
        with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
            pl = pv.Plotter(off_screen=True); pl.add_mesh(m_def, scalars='Risco', cmap="hot", smooth_shading=True)
            pl.export_gltf(tmp.name)
            with open(tmp.name, "rb") as f: st.session_state.b64_rechupe_x10 = base64.b64encode(f.read()).decode()

        st.session_state.step = 4
        st.rerun()

    except Exception as e:
        st.error(f"💥 FALHA MATEMÁTICA: {e}")
        st.code(traceback.format_exc())
        if st.button("⬅️ Voltar"): st.session_state.step = 3; st.rerun()

# ==========================================
# ETAPA 4: LAUDO (COM HOLOGRAMA DE LOADING V48)
# ==========================================
elif st.session_state.step == 4:
    
    tela4_container = st.empty()
    
    with tela4_container.container():
        st.header("4. Simulação")
        
        col_tempo, col_video = st.columns([3, 1])
        with col_tempo:
            st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {st.session_state.t_sol_minutos} min {st.session_state.t_sol_segundos} s**")
        with col_video:
            if st.button("🎬 Painel de Extração Temporal", help="Abre o cinema", use_container_width=True):
                tela4_container.empty()
                time.sleep(0.2)
                st.session_state.step = 4.5
                st.rerun()
        
        col_v1, col_v2, col_v3 = st.columns(3)
        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]

        with col_v1:
            st.write("🔥 **1. Preenchimento Térmico**")
            html_termico = gerar_html_viewer(st.session_state.b64_termico, "#ff4500", "Renderizando Mapa Térmico...", hotspot=p_m)
            components.html(html_termico, height=360)

        with col_v2:
            st.write("🌈 **2. Mapa de Solidificação**")
            st.caption("Frio (Azul) = Congela Rápido | Quente (Vermelho) = Lento")
            html_solid = gerar_html_viewer(st.session_state.b64_solidificacao, "#00BFFF", "Calculando Gradientes...")
            components.html(html_solid, height=360)

        with col_v3:
            st.write("⚠️ **3. Rechupe (Deformação x10)**")
            html_rechupe = gerar_html_viewer(st.session_state.b64_rechupe_x10, "#ffcc00", "Montando Malha de Alta Resolução...<br><span style='font-size: 11px; color: #888;'>Isso leva alguns segundos</span>")
            components.html(html_rechupe, height=360)

        st.markdown("---")
        c_ia, c_btn = st.columns([3, 1])
        with c_ia:
            st.subheader("🤖 Diagnóstico IA")
            st.markdown(st.session_state.relatorio_ia)
        with c_btn:
            st.write("")
            if HAS_FPDF and st.session_state.relatorio_pdf:
                st.download_button("📄 Baixar Laudo (.PDF)", st.session_state.relatorio_pdf, "Laudo_CastingSim.pdf", "application/pdf", type="primary", use_container_width=True)
            if st.button("⬅️ Voltar para Geometria", use_container_width=True): 
                tela4_container.empty()
                time.sleep(0.1)
                st.session_state.step = 3; st.rerun()

# ==========================================
# ETAPA 4.5: EXTRAÇÃO TEMPORAL
# ==========================================
elif st.session_state.step == 4.5:
    gc.collect() 
    st.title("🎬 Renderizando Motor Temporal")
    prog = st.progress(0)
    
    try:
        mesh_animacao = pv.read(st.session_state.path_resultados_proxy)
        
        try:
            mold_ghost = mesh_animacao.decimate(0.95)
        except:
            mold_ghost = mesh_animacao.outline() 
            
        mold_ghost.points /= 1000.0
        
        st.session_state.frames_filling = []
        st.session_state.frames_cooling = []
        temp_dir = tempfile.mkdtemp()
        
        passos = 10
        for i in range(1, passos + 1):
            lim = (1.0 / passos) * i
            if lim <= 0: lim = 1e-6 
            
            f_mesh = mesh_animacao.threshold([0, lim], scalars='Preenchimento')
            
            pl = pv.Plotter(off_screen=True)
            pl.add_mesh(mold_ghost, color='white', opacity=0.1, style='wireframe')
            
            if f_mesh.n_points > 0:
                f_mesh.points /= 1000.0
                pl.add_mesh(f_mesh, color='#ff4500', metallic=True, smooth_shading=True)
                
            path = os.path.join(temp_dir, f"fill_{i}.glb")
            pl.export_gltf(path)
            st.session_state.frames_filling.append(path)
            pl.close()
            prog.progress(int((i/passos)*40), text="[1/2] Forjando Animação de Queda Absoluta...")

        t_v = st.session_state.t_vaz
        t_m = st.session_state.t_molde
        massa = mesh_animacao['MassaTermica']
        tau = (massa + 0.1) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1) / 3.0 
        
        for i in range(passos):
            t_instante = (i / (passos - 1)) * (st.session_state.t_sol_minutos * 60 + st.session_state.t_sol_segundos + 1)
            T_t = t_m + (t_v - t_m) * np.exp(-t_instante / tau)
            heat_norm = (T_t - t_m) / (t_v - t_m + 1e-6)
            
            m_cool = mesh_animacao.copy()
            m_cool['TempAtual'] = heat_norm
            m_cool.points /= 1000.0
            
            pl = pv.Plotter(off_screen=True)
            pl.add_mesh(m_cool, scalars='TempAtual', cmap="turbo", smooth_shading=True, clim=[0, 1])
            path = os.path.join(temp_dir, f"cool_{i}.glb")
            pl.export_gltf(path)
            st.session_state.frames_cooling.append(path)
            pl.close()
            prog.progress(40 + int(((i+1)/passos)*60), text="[2/2] Extraindo Frames Termodinâmicos...")

        prog.progress(100, text="Processamento finalizado!")
        time.sleep(0.5)
        st.session_state.step = 5
        st.rerun()

    except Exception as e:
        st.error(f"Erro na extração de vídeo: {e}")
        if st.button("Voltar"): st.session_state.step = 4; st.rerun()

# ==========================================
# ETAPA 5: O CINEMA
# ==========================================
elif st.session_state.step == 5:
    st.header("5. Telemetria Cinemática")
    
    modo = st.radio("Selecione o Módulo de Visualização:", ["🌊 Cinemática de Preenchimento", "❄️ Termodinâmica de Resfriamento (Fourier)"], horizontal=True)
    caminhos_alvo = st.session_state.frames_filling if "Preenchimento" in modo else st.session_state.frames_cooling
    
    if len(caminhos_alvo) > 0:
        frames_b64 = []
        for p in caminhos_alvo:
            try:
                with open(p, "rb") as f: frames_b64.append(base64.b64encode(f.read()).decode())
            except: pass
                
        frames_js_array = ",\n".join([f'"{b64}"' for b64 in frames_b64])
        css_thumb = "#ff4500" if "Preenchimento" in modo else "#00BFFF"
        
        html_player = f"""
        <html>
        <head>
            <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
            <style>
                body {{ margin: 0; background-color: #f4f6f9; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; font-family: sans-serif; }}
                model-viewer {{ width: 100%; height: 85%; background-color: #1e1e1e; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.3); }}
                .controls {{ height: 15%; display: flex; align-items: center; justify-content: center; width: 100%; gap: 15px; padding: 10px; box-sizing: border-box; }}
                input[type=range] {{ -webkit-appearance: none; width: 60%; background: transparent; }}
                input[type=range]::-webkit-slider-thumb {{ -webkit-appearance: none; height: 24px; width: 24px; border-radius: 50%; background: {css_thumb}; cursor: pointer; margin-top: -8px; box-shadow: 0 0 8px {css_thumb}; }}
                input[type=range]::-webkit-slider-runnable-track {{ width: 100%; height: 8px; cursor: pointer; background: #cccccc; border-radius: 4px; }}
                .status {{ color: #1e1e1e; font-weight: bold; font-size: 16px; background-color: white; padding: 5px 15px; border-radius: 20px; border: 1px solid #ccc; }}
            </style>
        </head>
        <body>
            <model-viewer id="mv" src="data:model/gltf-binary;base64,{frames_b64[0]}" camera-controls shadow-intensity="1"></model-viewer>
            <div class="controls">
                <span style="font-weight: bold;">Início</span>
                <input type="range" min="1" max="{len(frames_b64)}" value="1" class="slider" id="frameSlider">
                <span style="font-weight: bold;">Fim</span>
                <div class="status" id="frame-counter">Quadro: 1 / {len(frames_b64)}</div>
            </div>
            <script>
                const frames = [{frames_js_array}];
                const mv = document.getElementById('mv');
                const slider = document.getElementById('frameSlider');
                const counter = document.getElementById('frame-counter');
                
                slider.oninput = function() {{
                    let idx = this.value - 1;
                    mv.src = "data:model/gltf-binary;base64," + frames[idx];
                    counter.innerText = "Quadro: " + this.value + " / " + frames.length;
                }}
            </script>
        </body>
        </html>
        """
        components.html(html_player, height=550)
    else:
        st.warning("Não há frames disponíveis.")
            
    st.write("")
    if st.button("⬅️ Voltar ao Laudo Principal (Etapa 4)", type="primary"):
        st.session_state.step = 4; st.rerun()