-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn47lab.py
More file actions
6049 lines (5299 loc) · 257 KB
/
Copy pathn47lab.py
File metadata and controls
6049 lines (5299 loc) · 257 KB
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
N47Lab v1.0.5-FULL
Versione completa con funzionalità CAD e CAM.
Copyright (c) 2026 N47Lab Team - Tutti i diritti riservati.
"""
import sys
import os
import math
import time
import numpy as np
import trimesh
import trimesh.boolean
import trimesh.smoothing
import shapely.geometry as sgeom
from shapely.geometry import Polygon as ShapelyPolygon
import multiprocessing
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple, Set
# Importazioni PyQt5 - DEVE ESSERE PRIMA DELLE DEFINIZIONI DI CLASSI
from PyQt5.QtCore import Qt, QTimer, QEvent, QSize, QPoint, QRect
from PyQt5.QtGui import QFont, QFontMetrics, QSurfaceFormat, QPainter, QColor, QPen, QKeySequence, QTextCharFormat, QTextCursor, QIcon, QPixmap, QPalette
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QSplitter, QGroupBox, QFormLayout,
QFileDialog, QMessageBox, QInputDialog, QToolBar, QStatusBar,
QShortcut, QListWidget, QListWidgetItem, QScrollArea, QOpenGLWidget,
QSpinBox, QDoubleSpinBox, QTreeWidget, QTreeWidgetItem, QSizePolicy, QAction,
QTextEdit, QTabWidget, QDialog, QDialogButtonBox, QFrame,
QMenu, QToolButton, QButtonGroup, QSlider, QCheckBox, QComboBox,
QPlainTextEdit
)
from OpenGL.GL import *
from OpenGL.GLU import *
# =============================================================================
# COSTANTI GLOBALI
# =============================================================================
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
APP_NAME = "N47Lab"
VERSION = "1.0.5-FULL"
# Colori per il tema azzurro pastello
BACKGROUND_COLOR = "#AEC8E0"
TEXT_COLOR = "#0C1E36"
BORDER_COLOR = "#2C5F8A"
BUTTON_COLOR = "#C8DCF0"
BUTTON_HOVER = "#CFFAFE"
BUTTON_PRESSED = "#94E6F2"
# Colori neutri per le forme
NEUTRAL_COLORS: List[List[float]] = [
[0.7, 0.7, 0.7, 1.0],
[0.4, 0.6, 0.8, 1.0],
[0.8, 0.5, 0.5, 1.0],
[0.5, 0.8, 0.5, 1.0],
[0.8, 0.8, 0.4, 1.0],
[0.6, 0.5, 0.8, 1.0],
[0.5, 0.8, 0.8, 1.0],
[0.8, 0.6, 0.4, 1.0],
[0.7, 0.4, 0.7, 1.0],
[0.4, 0.7, 0.6, 1.0],
[0.9, 0.6, 0.6, 1.0],
[0.6, 0.6, 0.9, 1.0]
]
SHAPE_LIBRARY: Dict[str, Dict[str, Any]] = {
"Cubo": {"type": "box", "params": {"larghezza": 20.0, "altezza": 20.0, "profondità": 20.0}},
"Cilindro": {"type": "cylinder", "params": {"raggio": 10.0, "altezza": 30.0, "sezioni": 64}},
"Sfera": {"type": "sphere", "params": {"raggio": 15.0, "suddivisioni": 4}},
"Cono": {"type": "cone", "params": {"raggio_base": 12.0, "altezza": 30.0, "sezioni": 64}},
"collare": {"type": "collare", "params": {"raggio_esterno": 20.0, "raggio_interno": 12.0, "altezza": 8.0}},
"Esagono": {"type": "hexagon", "params": {"raggio": 10.0, "altezza": 30.0}},
"Spirale": {"type": "spiral", "params": {"raggio": 15.0, "altezza": 30.0, "giri": 4, "spessore": 3.0}},
"Arco": {"type": "arc", "params": {"raggio_est": 20.0, "raggio_int": 16.0, "apertura": 90.0, "altezza": 8.0}},
"Scatola vuota": {"type": "hollow_box", "params": {"larghezza": 30.0, "altezza": 20.0, "profondità": 20.0, "spessore_muro": 2.0}}
}
# =============================================================================
# PROFILI STAMPANTI 3D
# =============================================================================
PRINTER_PROFILES = {
"Bambu Lab X1C": {
"brand": "Bambu Lab", "model": "X1 Carbon",
"build_volume": (256, 256, 256), "nozzle": [0.4, 0.6, 0.8],
"max_temp": 300, "bed_temp": 100,
"protocols": ["mqtt_ftps"],
"default_layer": 0.16, "default_infill": 15
},
"Bambu Lab P1S": {
"brand": "Bambu Lab", "model": "P1S",
"build_volume": (256, 256, 256), "nozzle": [0.4, 0.6, 0.8],
"max_temp": 300, "bed_temp": 100,
"protocols": ["mqtt_ftps"],
"default_layer": 0.20, "default_infill": 15
},
"Bambu Lab A1": {
"brand": "Bambu Lab", "model": "A1",
"build_volume": (256, 256, 256), "nozzle": [0.4, 0.6, 0.8],
"max_temp": 260, "bed_temp": 80,
"protocols": ["mqtt_ftps"],
"default_layer": 0.20, "default_infill": 15
},
"Bambu Lab A1 Mini": {
"brand": "Bambu Lab", "model": "A1 Mini",
"build_volume": (180, 180, 180), "nozzle": [0.4],
"max_temp": 260, "bed_temp": 80,
"protocols": ["mqtt_ftps"],
"default_layer": 0.20, "default_infill": 15
},
"Anycubic Kobra 3": {
"brand": "Anycubic", "model": "Kobra 3",
"build_volume": (250, 250, 260), "nozzle": [0.4],
"max_temp": 260, "bed_temp": 95,
"protocols": ["ftp", "smb", "octoprint", "anycubic_cloud", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Anycubic Kobra 2": {
"brand": "Anycubic", "model": "Kobra 2",
"build_volume": (220, 220, 250), "nozzle": [0.4],
"max_temp": 260, "bed_temp": 95,
"protocols": ["ftp", "smb", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Anycubic Vyper": {
"brand": "Anycubic", "model": "Vyper",
"build_volume": (245, 245, 260), "nozzle": [0.4],
"max_temp": 260, "bed_temp": 95,
"protocols": ["ftp", "smb", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Creality K1 Max": {
"brand": "Creality", "model": "K1 Max",
"build_volume": (300, 300, 300), "nozzle": [0.4],
"max_temp": 300, "bed_temp": 100,
"protocols": ["creality_http", "ftp", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Creality K1": {
"brand": "Creality", "model": "K1",
"build_volume": (220, 220, 250), "nozzle": [0.4],
"max_temp": 300, "bed_temp": 100,
"protocols": ["creality_http", "ftp", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Creality Ender 3 V3": {
"brand": "Creality", "model": "Ender 3 V3",
"build_volume": (220, 220, 250), "nozzle": [0.4],
"max_temp": 260, "bed_temp": 100,
"protocols": ["ftp", "smb", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
},
"Prusa i3 MK3S+": {
"brand": "Prusa", "model": "i3 MK3S+",
"build_volume": (250, 210, 210), "nozzle": [0.25, 0.4, 0.6],
"max_temp": 280, "bed_temp": 100,
"protocols": ["prusalink", "ftp", "octoprint", "file"],
"default_layer": 0.15, "default_infill": 15
},
"Prusa XL": {
"brand": "Prusa", "model": "XL",
"build_volume": (360, 360, 360), "nozzle": [0.4, 0.6],
"max_temp": 290, "bed_temp": 110,
"protocols": ["prusalink", "ftp", "octoprint", "file"],
"default_layer": 0.20, "default_infill": 15
}
}
# =============================================================================
# BLOCCO 1: CORE ENGINE (FUNZIONALITÀ CAD E CAM)
# =============================================================================
def _generate_blender_donut(R: float, r: float, major_segs: int, minor_segs: int) -> trimesh.Trimesh:
major_segs = max(8, int(major_segs))
minor_segs = max(4, int(minor_segs))
if R <= r + 0.1:
R = r + 0.2
u = np.linspace(0, 2 * np.pi, major_segs, endpoint=False)
v = np.linspace(0, 2 * np.pi, minor_segs, endpoint=False)
U, V = np.meshgrid(u, v, indexing='ij')
X = (R + r * np.cos(V)) * np.cos(U)
Y = (R + r * np.cos(V)) * np.sin(U)
Z = r * np.sin(V)
verts = np.stack([X, Y, Z], axis=-1).reshape(-1, 3)
i = np.arange(major_segs)
j = np.arange(minor_segs)
i_next = (i + 1) % major_segs
j_next = (j + 1) % minor_segs
I, J = np.meshgrid(i, j, indexing='ij')
I_next, J_next = np.meshgrid(i_next, j_next, indexing='ij')
v00 = I * minor_segs + J
v10 = I_next * minor_segs + J
v11 = I_next * minor_segs + J_next
v01 = I * minor_segs + J_next
faces_1 = np.stack([v00, v10, v11], axis=-1).reshape(-1, 3)
faces_2 = np.stack([v00, v11, v01], axis=-1).reshape(-1, 3)
faces = np.vstack([faces_1, faces_2])
mesh = trimesh.Trimesh(vertices=verts, faces=faces)
mesh.fix_normals()
return mesh
def _generate_blender_collare(outer_radius: float, inner_radius: float, height: float) -> trimesh.Trimesh:
n = 64
angles = np.linspace(0, 2 * np.pi, n, endpoint=False)
cos_a = np.cos(angles)
sin_a = np.sin(angles)
outer_xy = np.column_stack([outer_radius * cos_a, outer_radius * sin_a])
inner_xy = np.column_stack([inner_radius * cos_a, inner_radius * sin_a])
top = height
bot = 0.0
# Vertices: [top_outer(0..n-1), top_inner(0..n-1), bot_outer(0..n-1), bot_inner(0..n-1)]
to = np.column_stack([outer_xy, np.full(n, top)])
ti = np.column_stack([inner_xy, np.full(n, top)])
bo = np.column_stack([outer_xy, np.full(n, bot)])
bi = np.column_stack([inner_xy, np.full(n, bot)])
verts = np.vstack([to, ti, bo, bi])
faces = []
# Helper: add quad as two tris (v0,v1,v2) and (v0,v2,v3)
def add_quad(a, b, c, d):
faces.append((a, b, c))
faces.append((a, c, d))
for i in range(n):
j = (i + 1) % n
to_i, to_j = i, j
ti_i, ti_j = n + i, n + j
bo_i, bo_j = 2 * n + i, 2 * n + j
bi_i, bi_j = 3 * n + i, 3 * n + j
# Top face
add_quad(to_i, to_j, ti_j, ti_i)
# Bottom face (reversed winding for outward normal)
add_quad(bo_i, bi_i, bi_j, bo_j)
# Outer wall
add_quad(to_i, bo_i, bo_j, to_j)
# Inner wall
add_quad(ti_i, ti_j, bi_j, bi_i)
mesh = trimesh.Trimesh(vertices=verts, faces=faces)
mesh.fix_normals()
return mesh
def _generate_blender_cylinder(radius: float, height: float, sections: int) -> trimesh.Trimesh:
mesh = trimesh.creation.cylinder(radius=radius, height=height, sections=int(sections))
mesh.fix_normals()
return mesh
def _generate_blender_sphere(radius: float, subdivisions: int) -> trimesh.Trimesh:
mesh = trimesh.creation.icosphere(radius=radius, subdivisions=min(6, int(subdivisions)))
mesh.fix_normals()
return mesh
def _generate_blender_cone(radius: float, height: float, sections: int) -> trimesh.Trimesh:
mesh = trimesh.creation.cone(radius=radius, height=height, sections=int(sections))
mesh.fix_normals()
return mesh
def _generate_blender_box(width: float, height: float, depth: float) -> trimesh.Trimesh:
mesh = trimesh.creation.box(extents=[width, depth, height])
mesh.fix_normals()
return mesh
def _generate_blender_hexagon(radius: float, height: float) -> trimesh.Trimesh:
from shapely.geometry import Polygon as SPolygon
angles = [2 * math.pi * i / 6 for i in range(6)]
pts = [(radius * math.cos(a), radius * math.sin(a)) for a in angles]
mesh = trimesh.creation.extrude_polygon(SPolygon(pts), height=height)
mesh.fix_normals()
return mesh
def _generate_blender_spiral(radius: float, height: float, turns: int, thickness: float) -> trimesh.Trimesh:
turns = max(1, int(turns))
thickness = max(0.5, thickness)
r_tube = thickness / 2
segs = int(turns * 48)
ring_segs = max(12, int(thickness * 4))
verts = []
faces = []
def helix_point(t):
theta = t * 2 * np.pi * turns
x = radius * np.cos(theta)
y = radius * np.sin(theta)
z = t * height
return np.array([x, y, z]), theta
def frenet_frame(theta):
h_per_turn = height / max(1, turns)
T = np.array([-radius * np.sin(theta), radius * np.cos(theta), h_per_turn / (2 * np.pi)])
T = T / (np.linalg.norm(T) + 1e-12)
N = np.array([-np.cos(theta), -np.sin(theta), 0.0])
N = N / (np.linalg.norm(N) + 1e-12)
B = np.cross(T, N)
B = B / (np.linalg.norm(B) + 1e-12)
N = np.cross(B, T)
return T, N, B
for i in range(segs + 1):
t = i / segs
pt, theta = helix_point(t)
T, N, B = frenet_frame(theta)
for j in range(ring_segs):
phi = j / ring_segs * 2 * np.pi
rv = r_tube * (N * np.cos(phi) + B * np.sin(phi))
verts.append(pt + rv)
n_ring = ring_segs
for i in range(segs):
for j in range(ring_segs):
jn = (j + 1) % ring_segs
v00 = i * n_ring + j
v01 = i * n_ring + jn
v10 = (i + 1) * n_ring + j
v11 = (i + 1) * n_ring + jn
faces.append((v00, v10, v11))
faces.append((v00, v11, v01))
# End caps
offset = len(verts)
for t_val, sign in [(0.0, -1), (1.0, 1)]:
pt, theta = helix_point(t_val)
T, N, B = frenet_frame(theta)
cap_center = len(verts)
verts.append(pt)
for j in range(ring_segs):
phi = j / ring_segs * 2 * np.pi
rv = r_tube * (N * np.cos(phi) + B * np.sin(phi))
verts.append(pt + rv)
for j in range(ring_segs):
jn = (j + 1) % ring_segs
if sign == 1:
faces.append((cap_center, cap_center + jn + 1, cap_center + j + 1))
else:
faces.append((cap_center, cap_center + j + 1, cap_center + jn + 1))
verts = np.array(verts, dtype=np.float32)
faces = np.array(faces, dtype=np.uint32)
mesh = trimesh.Trimesh(vertices=verts, faces=faces)
mesh.fix_normals()
return mesh
def _generate_blender_arc(outer_r: float, inner_r: float, angle_deg: float, height: float) -> trimesh.Trimesh:
from shapely.geometry import Point
angle_deg = min(360, max(1, angle_deg))
angle_rad = math.radians(angle_deg)
outer = Point(0, 0).buffer(outer_r, resolution=64)
inner = Point(0, 0).buffer(inner_r, resolution=64)
ring = outer.difference(inner)
if angle_deg >= 360:
mesh = trimesh.creation.extrude_polygon(ring, height=height)
mesh.fix_normals()
return mesh
from shapely.affinity import rotate
from shapely.geometry import box as sbox
cut = sbox(-outer_r * 2, -outer_r * 2, 0, outer_r * 2)
cut = rotate(cut, -(90 - angle_deg / 2), origin=(0, 0), use_radians=False)
sector = ring.intersection(cut)
if sector.is_empty:
return _generate_blender_collare(outer_r, inner_r, height)
polys = [sector] if sector.geom_type == 'Polygon' else [g for g in sector.geoms if g.geom_type == 'Polygon']
all_verts, all_faces, offset = [], [], 0
for p in polys:
m = trimesh.creation.extrude_polygon(p, height=height)
if m and len(m.vertices) > 0:
all_verts.append(m.vertices)
all_faces.append(m.faces + offset)
offset += len(m.vertices)
if not all_verts:
return _generate_blender_collare(outer_r, inner_r, height)
mesh = trimesh.Trimesh(vertices=np.vstack(all_verts), faces=np.vstack(all_faces))
mesh.remove_unreferenced_vertices()
mesh.fix_normals()
return mesh
def _qpath_to_mesh(qpath, thickness):
from PyQt5.QtGui import QPainterPath
polys = qpath.toFillPolygons()
if not polys:
return trimesh.Trimesh()
all_polys, holes = [], []
for poly in polys:
if len(poly) < 3:
continue
pts = [(pt.x(), -pt.y()) for pt in poly]
if len(pts) < 3:
continue
area = 0.0
for i in range(len(pts)):
j = (i + 1) % len(pts)
area += pts[i][0] * pts[j][1] - pts[j][0] * pts[i][1]
if area < 0:
all_polys.append(pts)
else:
holes.append(pts)
if not all_polys:
return trimesh.Trimesh()
from shapely.ops import unary_union
shapely_solids = [ShapelyPolygon(pts) for pts in all_polys]
shapely_solids = [sp.buffer(0) for sp in shapely_solids if not sp.is_empty]
shapely_solids = [sp for sp in shapely_solids if sp.is_valid and not sp.is_empty]
if not shapely_solids:
return trimesh.Trimesh()
merged = unary_union(shapely_solids)
if merged.is_empty:
return trimesh.Trimesh()
if merged.geom_type == 'Polygon':
polys_to_extrude = [merged]
elif merged.geom_type == 'MultiPolygon':
polys_to_extrude = list(merged.geoms)
else:
return trimesh.Trimesh()
all_verts, all_faces, offset = [], [], 0
for poly in polys_to_extrude:
try:
ext_mesh = trimesh.creation.extrude_polygon(poly, height=thickness)
if ext_mesh and len(ext_mesh.vertices) > 0:
all_verts.append(ext_mesh.vertices)
all_faces.append(ext_mesh.faces + offset)
offset += len(ext_mesh.vertices)
except:
continue
if not all_verts:
return trimesh.Trimesh()
combined = trimesh.Trimesh(vertices=np.vstack(all_verts), faces=np.vstack(all_faces))
combined.remove_unreferenced_vertices()
return combined
def _generate_text_mesh(text, font_name, font_size, thickness, spacing):
from PyQt5.QtGui import QPainterPath, QFont, QFontMetricsF
from PyQt5.QtCore import QPointF
font = QFont(font_name, int(font_size))
font_metrics = QFontMetricsF(font)
if abs(spacing) > 0.001:
all_verts, all_faces, offset = [], [], 0
x_cursor = 0.0
for ch in text:
path = QPainterPath()
path.addText(QPointF(0, 0), font, ch)
ch_w = font_metrics.horizontalAdvance(ch) if hasattr(font_metrics, 'horizontalAdvance') else font_metrics.width(ch)
ch_mesh = _qpath_to_mesh(path, thickness)
if ch_mesh and len(ch_mesh.vertices) > 0:
ch_mesh.apply_translation([x_cursor, 0, 0])
all_verts.append(ch_mesh.vertices)
all_faces.append(ch_mesh.faces + offset)
offset += len(ch_mesh.vertices)
x_cursor += ch_w + spacing
if not all_verts:
return trimesh.Trimesh()
combined = trimesh.Trimesh(vertices=np.vstack(all_verts), faces=np.vstack(all_faces))
combined.remove_unreferenced_vertices()
return combined
else:
path = QPainterPath()
path.addText(QPointF(0, 0), font, text)
return _qpath_to_mesh(path, thickness)
def _generate_thread_on_shape(mesh: trimesh.Trimesh, turns: int = 8, thread_radius: float = 1.5, segments_per_turn: int = 24, circle_segments: int = 12) -> trimesh.Trimesh:
"""Genera un filetto elicoidale che segue la superficie della mesh."""
bounds = mesh.bounds
if bounds is None:
return trimesh.Trimesh()
size = bounds[1] - bounds[0]
verts = mesh.vertices
centroid = np.mean(verts, axis=0)
radii = np.linalg.norm(verts - centroid, axis=1)
r_mean = radii.mean()
# Determina la forma dal bounding box
is_sphere = max(size) / max(min(size), 1e-8) < 1.3 and abs(size[0] - size[1]) / max((size[0] + size[1]) / 2, 1e-8) < 0.2
if is_sphere:
R = r_mean
h = 0.0
else:
R = (size[0] + size[1]) / 4
h = size[2]
n = turns * segments_per_turn + 1
all_verts = []
all_faces = []
for i in range(n):
t = i / max(n - 1, 1)
if is_sphere:
theta = -np.pi / 2 + t * np.pi
phi = t * 2 * np.pi * turns
px = R * np.cos(theta) * np.cos(phi) + centroid[0]
py = R * np.cos(theta) * np.sin(phi) + centroid[1]
pz = R * np.sin(theta) + centroid[2]
nx = (px - centroid[0]) / R
ny = (py - centroid[1]) / R
nz = (pz - centroid[2]) / R
else:
phi = t * 2 * np.pi * turns
px = R * np.cos(phi) + centroid[0]
py = R * np.sin(phi) + centroid[1]
pz = -h / 2 + t * h + centroid[2]
nx = np.cos(phi)
ny = np.sin(phi)
nz = 0.0
# Tangente del percorso (analitica)
if is_sphere:
d_theta = np.pi
d_phi = 2 * np.pi * turns
tx = -R * np.sin(theta) * np.cos(phi) * d_theta - R * np.cos(theta) * np.sin(phi) * d_phi
ty = -R * np.sin(theta) * np.sin(phi) * d_theta + R * np.cos(theta) * np.cos(phi) * d_phi
tz = R * np.cos(theta) * d_theta
else:
d_phi = 2 * np.pi * turns
d_z = h
tx = -R * np.sin(phi) * d_phi
ty = R * np.cos(phi) * d_phi
tz = d_z
tl = np.sqrt(tx*tx + ty*ty + tz*tz)
if tl > 1e-8:
tx /= tl; ty /= tl; tz /= tl
else:
tx, ty, tz = 1.0, 0.0, 0.0
# u = cross(T, N), normalizzato
ux = ty * nz - tz * ny
uy = tz * nx - tx * nz
uz = tx * ny - ty * nx
ul = np.sqrt(ux*ux + uy*uy + uz*uz)
if ul > 1e-8:
ux /= ul; uy /= ul; uz /= ul
else:
ux, uy, uz = 1.0, 0.0, 0.0
# v = cross(T, u) — il terzo asse del cerchio
vx = ty * uz - tz * uy
vy = tz * ux - tx * uz
vz = tx * uy - ty * ux
# Cerchio nel piano perpendicolare al percorso
# Centro offsettato verso l'esterno di thread_radius lungo la normale (v = -N)
for j in range(circle_segments):
alpha = j / circle_segments * 2 * np.pi
c = np.cos(alpha)
s = np.sin(alpha)
cvx = ux * c * thread_radius + vx * s * thread_radius
cvy = uy * c * thread_radius + vy * s * thread_radius
cvz = uz * c * thread_radius + vz * s * thread_radius
all_verts.append([px - vx * thread_radius + cvx,
py - vy * thread_radius + cvy,
pz - vz * thread_radius + cvz])
if i > 0:
base = (i - 1) * circle_segments
for j in range(circle_segments):
jn = (j + 1) % circle_segments
a = base + j
b = base + jn
c = base + circle_segments + j
d = base + circle_segments + jn
all_faces.append([a, c, b])
all_faces.append([b, c, d])
result = trimesh.Trimesh(vertices=np.array(all_verts), faces=np.array(all_faces))
result.remove_unreferenced_vertices()
result.fix_normals()
return result
def _generate_blender_hollow_box(width: float, height: float, depth: float, wall: float) -> trimesh.Trimesh:
outer = trimesh.creation.box(extents=[width, depth, height])
inner_w = max(0.1, width - 2 * wall)
inner_h = max(0.1, height - 2 * wall)
inner_d = max(0.1, depth - 2 * wall)
inner = trimesh.creation.box(extents=[inner_w, inner_d, inner_h])
try:
result = boolean_safe([outer, inner], "difference")
if result is None or result.is_empty:
return outer
cut_h = height - wall
if cut_h > 0:
plane_orig = [0, 0, cut_h - height / 2]
plane_norm = [0, 0, -1]
sliced = trimesh.intersections.slice_mesh_plane(result, plane_norm, plane_orig, cap=True)
if sliced is not None and not sliced.is_empty:
result = sliced
result.fix_normals()
return result
except:
return outer
def _ensure_volume(mesh):
"""Tenta di rendere una mesh un volume valido per booleane."""
m = mesh.copy()
m.fix_normals()
if not m.is_watertight:
try:
trimesh.repair.fill_holes(m)
except:
pass
if not m.is_watertight:
try:
m.process(validate=True)
except:
pass
return m
def boolean_safe(meshes: List[trimesh.Trimesh], operation: str) -> trimesh.Trimesh:
"""
Esegue operazioni booleane in modo sicuro con fallback a metodi alternativi.
"""
if len(meshes) < 2:
raise ValueError("Servono almeno 2 mesh per l'operazione booleana")
op_map = {
"unione": "union",
"sottrazione": "difference",
"intersezione": "intersection"
}
op_type = op_map.get(operation.lower(), operation.lower())
op_func_map = {
"union": trimesh.boolean.union,
"difference": trimesh.boolean.difference,
"intersection": trimesh.boolean.intersection
}
op_func = op_func_map.get(op_type)
if op_func is None:
raise ValueError(f"Operazione sconosciuta: {operation}")
engines_to_try = ['manifold', None]
for engine in engines_to_try:
try:
return op_func(meshes, engine=engine)
except Exception:
continue
# Fallback: repara mesh e riprova
fixed = [_ensure_volume(m) for m in meshes]
for engine in engines_to_try:
try:
return op_func(fixed, engine=engine)
except Exception:
continue
# Ultimo fallback: mesh-by-mesh con scipy
try:
result = None
for m in fixed:
if result is None:
result = m
continue
if op_type == "union":
result = result.union(m)
elif op_type == "difference":
result = result.difference(m)
elif op_type == "intersection":
result = result.intersection(m)
if result is not None and not result.is_empty:
return result
except Exception as e2:
raise RuntimeError(f"Errore CSG: tutti i motori hanno fallito: {e2}")
def validate_and_place_mesh(mesh: Optional[trimesh.Trimesh]) -> trimesh.Trimesh:
try:
if mesh is None or len(mesh.vertices) < 3 or len(mesh.faces) < 1:
return _generate_blender_box(10, 10, 10)
# Processa e convalida la mesh
mesh.process(validate=True)
mesh.fix_normals()
# Allinea al piano XY se necessario
if hasattr(mesh, 'bounds') and mesh.bounds is not None and len(mesh.bounds) == 2:
z_min = mesh.bounds[0][2]
if abs(z_min) > 1e-6:
mesh.apply_translation([0, 0, -z_min])
return mesh
except Exception as e:
print(f"Errore validazione mesh: {e}")
return _generate_blender_box(10, 10, 10)
def create_mesh(shape_type: str, params: Dict[str, Any]) -> trimesh.Trimesh:
try:
if shape_type == "box":
mesh = _generate_blender_box(
float(params.get("larghezza", 20)),
float(params.get("altezza", 20)),
float(params.get("profondità", 20))
)
elif shape_type == "cylinder":
mesh = _generate_blender_cylinder(
float(params.get("raggio", 10)),
float(params.get("altezza", 30)),
int(params.get("sezioni", 64))
)
elif shape_type == "sphere":
mesh = _generate_blender_sphere(
float(params.get("raggio", 15)),
int(params.get("suddivisioni", 4))
)
elif shape_type == "cone":
mesh = _generate_blender_cone(
float(params.get("raggio_base", 12)),
float(params.get("altezza", 30)),
int(params.get("sezioni", 64))
)
elif shape_type == "hexagon":
mesh = _generate_blender_hexagon(float(params.get("raggio", 10)), float(params.get("altezza", 30)))
elif shape_type == "spiral":
mesh = _generate_blender_spiral(float(params.get("raggio", 15)), float(params.get("altezza", 30)), int(params.get("giri", 4)), float(params.get("spessore", 3)))
elif shape_type == "arc":
mesh = _generate_blender_arc(float(params.get("raggio_est", 20)), float(params.get("raggio_int", 12)), float(params.get("apertura", 90)), float(params.get("altezza", 8)))
elif shape_type == "hollow_box":
mesh = _generate_blender_hollow_box(float(params.get("larghezza", 30)), float(params.get("altezza", 20)), float(params.get("profondità", 20)), float(params.get("spessore_muro", 2.5)))
elif shape_type == "collare":
mesh = _generate_blender_collare(float(params.get("raggio_esterno", 20)), float(params.get("raggio_interno", 12)), float(params.get("altezza", 8)))
elif shape_type == "donut":
R = float(params.get("raggio_magg", 15))
r = float(params.get("raggio_min", 5))
if R <= r + 0.1:
R = r + 0.2
mesh = _generate_blender_donut(R, r, int(params.get("sezioni", 64)), int(params.get("sezioni", 64)) // 2)
else:
mesh = _generate_blender_box(10, 10, 10)
return validate_and_place_mesh(mesh)
except Exception as e:
print(f"Errore creazione mesh: {e}")
return validate_and_place_mesh(_generate_blender_box(10, 10, 10))
class Scene:
def __init__(self) -> None:
self.objects: List[trimesh.Trimesh] = []
self.selected_objects: List[trimesh.Trimesh] = []
self.undo_stack: List[Dict[str, Any]] = []
self.redo_stack: List[Dict[str, Any]] = []
self.color_idx: int = 0
self.sketch_entities: List[Dict[str, Any]] = []
self.dimensions = []
self.angle_dims = []
self.snap_grid: bool = True
self.scale_mode: str = "Disattivato"
self.magnetic_snap: bool = True
self.layers: Dict[str, Dict[str, Any]] = {"Default": {"visible": True, "locked": False, "color": [0.6, 0.75, 0.9, 1.0]}}
self.active_layer: str = "Default"
self.assemblies: Dict[str, Dict[str, Any]] = {}
self.operation_in_progress = False
self._spatial_index = None
self._needs_spatial_rebuild = True
self.measurement_mode = None
self.measurement_points = []
self.active_tool = "selection"
self.mirror_axis = "x"
self.fillet_radius = 1.0
self.offset_distance = 1.0
self.revolve_angle = 360.0
self.pattern_count = 3
self.pattern_distance = 10.0
self.pattern_direction = "x"
self.smooth_iterations = 1
self.subdivide_iterations = 1
self.decimate_target = 1000
self.hole_diameter = 5.0
self.hole_depth = 10.0
self.cut_axis = "z"
self.cut_position = 0.0
self.deformation_type = "bend"
self.deformation_intensity = 0.5
self.tool_diameter = 3.0
self.stepover = 0.5
self.feed_rate = 1000.0
self.plunge_rate = 500.0
self.depth_per_pass = 2.0
self.toolpath_strategy = "adaptive"
self.toolpath_direction = "climb"
self.toolpath_depth = 0.0
self.toolpath_offset = 0.0
self.toolpath_feedrate = 1000.0
self.toolpath_plunge_feedrate = 500.0
self.toolpath_spindle_speed = 12000
self.toolpath_coolant = "flood"
self.toolpath_tool_number = 1
self.toolpath_tool_diameter = 3.0
self.toolpath_tool_length = 50.0
self.toolpath_tool_flutes = 2
self.toolpath_tool_material = "carbide"
self.toolpath_tool_coating = "tialn"
self.toolpath_tool_cutting_diameter = 3.0
self.toolpath_tool_cutting_length = 20.0
self.toolpath_tool_shank_diameter = 6.0
self.toolpath_tool_shank_length = 30.0
self.toolpath_tool_corner_radius = 0.0
self.toolpath_tool_tip_angle = 0.0
self.toolpath_tool_tip_diameter = 0.0
self.toolpath_tool_tip_length = 0.0
self.toolpath_tool_tip_radius = 0.0
self.gcode_paths = []
@property
def grid_step(self) -> float:
return 0.0 if self.scale_mode == "Disattivato" else float(self.scale_mode.replace(" mm", ""))
@property
def has_selection(self) -> bool:
return len(self.selected_objects) > 0
@property
def single_selection(self) -> Optional[trimesh.Trimesh]:
return self.selected_objects[0] if self.selected_objects else None
def clear_selection(self) -> None:
self.selected_objects = []
def add_to_selection(self, obj: trimesh.Trimesh) -> None:
if obj not in self.selected_objects:
self.selected_objects.append(obj)
self._needs_spatial_rebuild = True
def remove_from_selection(self, obj: trimesh.Trimesh) -> None:
if obj in self.selected_objects:
self.selected_objects.remove(obj)
def toggle_selection(self, obj: trimesh.Trimesh) -> None:
if obj in self.selected_objects:
self.remove_from_selection(obj)
else:
self.add_to_selection(obj)
def add_shape(self, shape_type: str, params: Dict[str, Any], name: Optional[str] = None) -> trimesh.Trimesh:
mesh = create_mesh(shape_type, params)
color = NEUTRAL_COLORS[self.color_idx % len(NEUTRAL_COLORS)]
self.color_idx += 1
mesh.metadata.update({
"layer": self.active_layer,
"color": color,
"name": name or f"{shape_type}_{self.color_idx}",
"params": params.copy(),
"shape_type": shape_type,
"assembly": None
})
self.objects.append(mesh)
self._needs_spatial_rebuild = True
self._undo_push()
return mesh
def _rebuild_spatial_index(self):
try:
if len(self.objects) <= 100:
self._spatial_index = None
return
from scipy.spatial import cKDTree
centers = []
for obj in self.objects:
if hasattr(obj, 'bounds') and obj.bounds is not None and len(obj.bounds) == 2:
center = (obj.bounds[0] + obj.bounds[1]) / 2
centers.append(center)
else:
if hasattr(obj, 'vertices') and len(obj.vertices) > 0:
center = np.mean(obj.vertices, axis=0)
centers.append(center)
else:
centers.append([0, 0, 0])
self._spatial_index = cKDTree(centers)
except ImportError:
self._spatial_index = None
except Exception as e:
print(f"Errore nella creazione dell'octree: {e}")
self._spatial_index = None
def _get_nearby_objects(self, point, radius=10.0):
if self._spatial_index is None or len(self.objects) == 0:
return self.objects
indices = self._spatial_index.query_ball_point(point, radius)
return [self.objects[i] for i in indices]
def _undo_push(self) -> None:
try:
if self.operation_in_progress:
return
obj_copy = []
for obj in self.objects:
try:
if hasattr(obj, 'copy'):
obj_copy.append(obj.copy())
except:
continue
if obj_copy:
selected_copy = [obj for obj in self.selected_objects if obj in obj_copy]
self.undo_stack.append({
"obj": obj_copy,
"selected": selected_copy
})
if len(self.undo_stack) > 50:
self.undo_stack.pop(0)
self.redo_stack.clear()
except Exception as e:
print(f"Errore inserimento stack undo: {e}")
def start_operation(self) -> None:
self.operation_in_progress = True
def end_operation(self) -> None:
self.operation_in_progress = False
self._undo_push()
def undo(self) -> bool:
if self.undo_stack:
state = self.undo_stack.pop()
redo_state = {
"obj": [],
"selected": [obj for obj in self.selected_objects if obj in self.objects]
}
for obj in self.objects:
try:
if hasattr(obj, 'copy'):
redo_state["obj"].append(obj.copy())
except:
continue
if redo_state["obj"]:
self.redo_stack.append(redo_state)
self.objects = state["obj"]
self.selected_objects = state["selected"]
self._needs_spatial_rebuild = True
self._notify(f"Annullato (oggetti: {len(self.objects)}, selezionati: {len(self.selected_objects)})")
return True
return False
def redo(self) -> bool:
if self.redo_stack:
state = self.redo_stack.pop()
undo_state = {
"obj": [],
"selected": [obj for obj in self.selected_objects if obj in self.objects]
}
for obj in self.objects:
try:
if hasattr(obj, 'copy'):
undo_state["obj"].append(obj.copy())
except:
continue
if undo_state["obj"]:
self.undo_stack.append(undo_state)
self.objects = state["obj"]
self.selected_objects = state["selected"]
self._needs_spatial_rebuild = True
self._notify(f"Ripristinato (oggetti: {len(self.objects)}, selezionati: {len(self.selected_objects)})")
return True
return False
def delete(self) -> bool:
if not self.selected_objects:
return False
self.start_operation()
deleted = len(self.selected_objects)
for obj in self.selected_objects[:]:
if obj in self.objects:
self.objects.remove(obj)
self.selected_objects = []
self._needs_spatial_rebuild = True
self.end_operation()
self._notify(f"Eliminati {deleted} oggetti")
return True
def duplicate(self) -> None:
if not self.selected_objects:
self._notify("Nessun oggetto selezionato")
return