-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathtest_assembly.py
More file actions
2404 lines (1816 loc) · 71.9 KB
/
test_assembly.py
File metadata and controls
2404 lines (1816 loc) · 71.9 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
import pytest
import os
from itertools import product
from math import degrees
import copy
from path import Path
from pathlib import PurePath
import re
from pytest import approx
import cadquery as cq
from cadquery.occ_impl.exporters.assembly import (
exportAssembly,
exportStepMeta,
exportCAF,
exportVTKJS,
exportVRML,
)
from cadquery.occ_impl.assembly import toJSON, toCAF, toFusedCAF
from cadquery.occ_impl.shapes import Face, box, cone, plane, Compound
from OCP.gp import gp_XYZ
from OCP.TDocStd import TDocStd_Document
from OCP.TDataStd import TDataStd_Name
from OCP.TCollection import TCollection_ExtendedString
from OCP.XCAFPrs import (
XCAFPrs_DocumentExplorer,
XCAFPrs_DocumentExplorerFlags_None,
XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes,
XCAFPrs_Style,
)
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType
from OCP.XCAFApp import XCAFApp_Application
from OCP.STEPCAFControl import STEPCAFControl_Reader
from OCP.IFSelect import IFSelect_RetDone
from OCP.TDF import TDF_ChildIterator
from OCP.Quantity import Quantity_ColorRGBA, Quantity_TOC_sRGB, Quantity_NameOfColor
from OCP.TopAbs import TopAbs_ShapeEnum
from OCP.Graphic3d import Graphic3d_NameOfMaterial
@pytest.fixture(scope="function")
def tmpdir(tmp_path_factory):
return Path(tmp_path_factory.mktemp("assembly"))
@pytest.fixture
def simple_assy():
b1 = cq.Solid.makeBox(1, 1, 1)
b2 = cq.Workplane().box(1, 1, 2)
b3 = cq.Workplane().pushPoints([(0, 0), (-2, -5)]).box(1, 1, 3)
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(2, -5, 0)))
assy.add(b2, loc=cq.Location(cq.Vector(1, 1, 0)))
assy.add(b3, loc=cq.Location(cq.Vector(2, 3, 0)))
return assy
@pytest.fixture
def nested_assy():
b1 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("top_face").end()
b2 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("bottom_face").end()
b3 = (
cq.Workplane()
.pushPoints([(-2, 0), (2, 0)])
.tag("pts")
.box(1, 1, 0.5)
.tag("boxes")
)
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(0, 0, 0)), name="TOP")
assy2 = cq.Assembly(b2, loc=cq.Location(cq.Vector(0, 4, 0)), name="SECOND")
assy2.add(b3, loc=cq.Location(cq.Vector(0, 4, 0)), name="BOTTOM")
assy.add(assy2, color=cq.Color("green"))
return assy
@pytest.fixture
def nested_assy_sphere():
b1 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("top_face").end()
b2 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("bottom_face").end()
b3 = cq.Workplane().pushPoints([(-2, 0), (2, 0)]).tag("pts").sphere(1).tag("boxes")
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(0, 0, 0)), name="TOP")
assy2 = cq.Assembly(b2, loc=cq.Location(cq.Vector(0, 4, 0)), name="SECOND")
assy2.add(b3, loc=cq.Location(cq.Vector(0, 4, 0)), name="BOTTOM")
assy.add(assy2, color=cq.Color("green"))
return assy
@pytest.fixture
def empty_top_assy():
b1 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly(name="top")
assy.add(b1, color=cq.Color("green"), name="b")
return assy
@pytest.fixture
def box_and_vertex():
box_wp = cq.Workplane().box(1, 2, 3)
assy = cq.Assembly(box_wp, name="box")
vertex_wp = cq.Workplane().newObject([cq.Vertex.makeVertex(0, 0, 0)])
assy.add(vertex_wp, name="vertex")
return assy
@pytest.fixture
def metadata_assy():
b1 = cq.Solid.makeBox(1, 1, 1)
b2 = cq.Workplane().box(1, 1, 2)
assy = cq.Assembly(
b1,
loc=cq.Location(cq.Vector(2, -5, 0)),
name="base",
metadata={"b1": "base-data"},
)
sub_assy = cq.Assembly(
b2, loc=cq.Location(cq.Vector(1, 1, 1)), name="sub", metadata={"b2": "sub-data"}
)
assy.add(sub_assy)
sub_assy2 = cq.Assembly(name="sub2", metadata={"mykey": "sub2-data"})
sub_assy2.add(
b1, name="sub2-0", loc=cq.Location((1, 0, 0)), metadata={"mykey": "sub2-0-data"}
)
sub_assy2.add(
b1, name="sub2-1", loc=cq.Location((2, 0, 0)), metadata={"mykey": "sub2-1-data"}
)
assy.add(
sub_assy2, metadata={"mykey": "sub2-data-add"}
) # override metadata mykey:sub2-data
return assy
@pytest.fixture
def simple_assy2():
b1 = cq.Workplane().box(1, 1, 1)
b2 = cq.Workplane().box(2, 1, 1)
assy = cq.Assembly()
assy.add(b1, name="b1")
assy.add(b2, loc=cq.Location(cq.Vector(0, 0, 4)), name="b2")
return assy
@pytest.fixture
def single_compound0_assy():
b0 = cq.Workplane().rect(1, 2).extrude(3, both=True)
assy = cq.Assembly(name="single_compound0")
assy.add(b0, color=cq.Color(1, 0, 0, 0.8))
return assy
@pytest.fixture
def single_compound1_assy():
b0 = cq.Workplane().circle(1).extrude(2)
b1 = cq.Workplane().circle(1).extrude(-2)
assy = cq.Assembly(name="single_compound1")
assy.add(
cq.Compound.makeCompound([b0.val(), b1.val()]), color=cq.Color(1, 0, 0, 0.8)
)
return assy
@pytest.fixture
def boxes0_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", color=cq.Color("red"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes1_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly(name="boxes", color=cq.Color("red"))
assy.add(b0, name="box0")
assy.add(b0, name="box1", loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes2_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes3_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes4_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box_0", color=cq.Color("red"))
assy.add(b0, name="box_1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes5_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box:a", color=cq.Color("red"))
assy.add(b0, name="box:b", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes6_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box__0", color=cq.Color("red"))
assy.add(b0, name="box__1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes7_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box_0", color=cq.Color("red"))
assy.add(b0, name="box", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
assy.add(
b0,
name="another box",
color=cq.Color(0.23, 0.26, 0.26, 0.6),
loc=cq.Location((2, 0, 0)),
)
return assy
@pytest.fixture
def boxes8_assy():
b0 = box(1, 1, 1)
assy = cq.Assembly(loc=cq.Location(0, 10, 0))
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes9_assy():
b0 = box(1, 1, 1)
assy = cq.Assembly(
b0, name="box0", loc=cq.Location(0, 10, 0), color=cq.Color("red")
)
assy.add(b0, name="box1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def spheres0_assy():
b0 = cq.Workplane().sphere(1)
assy = cq.Assembly(name="spheres0")
assy.add(b0, name="a", color=cq.Color(1, 0, 0, 0.2))
assy.add(b0, name="b", color=cq.Color(0, 1, 0, 0.2), loc=cq.Location((2.1, 0, 0)))
return assy
@pytest.fixture
def chassis0_assy():
r_wheel = 25
w_wheel = 10
l_axle = 80
l_chassis = 100
wheel = cq.Workplane("YZ").circle(r_wheel).extrude(w_wheel, both=True)
axle = cq.Workplane("YZ").circle(r_wheel / 10).extrude(l_axle / 2, both=True)
wheel_axle = cq.Assembly(name="wheel-axle")
wheel_axle.add(
wheel,
name="wheel:left",
color=cq.Color("red"),
loc=cq.Location((-l_axle / 2 - w_wheel, 0, 0)),
)
wheel_axle.add(
wheel,
name="wheel:right",
color=cq.Color("red"),
loc=cq.Location((l_axle / 2 + w_wheel, 0, 0)),
)
wheel_axle.add(axle, name="axle", color=cq.Color("green"))
chassis = cq.Assembly(name="chassis")
chassis.add(
wheel_axle, name="wheel-axle-front", loc=cq.Location((0, l_chassis / 2, 0))
)
chassis.add(
wheel_axle, name="wheel-axle-rear", loc=cq.Location((0, -l_chassis / 2, 0))
)
return chassis
@pytest.fixture
def subshape_assy():
"""
Builds an assembly with the needed subshapes to test the export and import of STEP files.
"""
# Create a simple assembly
assy = cq.Assembly(name="top_level")
cube_1 = cq.Workplane().box(10.0, 10.0, 10.0)
assy.add(cube_1, name="cube_1", color=cq.Color("green"))
# Add subshape name, color and layer
assy["cube_1"].addSubshape(
cube_1.faces(">Z").val(),
name="cube_1_top_face",
color=cq.Color("red"),
layer="cube_1_top_face_layer",
)
# Add a cylinder to the assembly
cyl_1 = cq.Workplane().cylinder(10.0, 2.5)
assy.add(
cyl_1, name="cyl_1", color=cq.Color("blue"), loc=cq.Location((0.0, 0.0, -10.0))
)
# Add a subshape face for the cylinder
assy["cyl_1"].addSubshape(
cyl_1.faces("<Z").val(),
name="cylinder_bottom_face",
color=cq.Color("green"),
layer="cylinder_bottom_face_layer",
)
# Add a subshape wire for the cylinder
assy["cyl_1"].addSubshape(
cyl_1.wires("<Z").val(),
name="cylinder_bottom_wire",
color=cq.Color("blue"),
layer="cylinder_bottom_wire_layer",
)
# Add two subshapes with the same name
assy["cyl_1"].addSubshape(cyl_1.faces(">Z").val(), name="2_faces")
assy["cyl_1"].addSubshape(cyl_1.faces("<Z").val(), name="2_faces")
return assy
@pytest.fixture
def multi_subshape_assy():
# Create a basic assembly
cube_1 = cq.Workplane().box(10, 10, 10)
assy = cq.Assembly(name="top_level")
assy.add(cube_1, name="cube_1", color=cq.Color("green"))
cube_2 = cq.Workplane().box(5, 5, 5)
assy.add(cube_2, name="cube_2", color=cq.Color("blue"), loc=cq.Location(10, 10, 10))
# Add subshape name, color and layer
assy.addSubshape(
cube_1.faces(">Z").val(),
name="cube_1_top_face",
color=cq.Color("red"),
layer="cube_1_top_face",
)
assy.addSubshape(
cube_2.faces(">X").val(),
name="cube_2_right_face",
color=cq.Color("red"),
layer="cube_2_right_face",
)
return assy
def read_step(stepfile) -> TDocStd_Document:
"""Read STEP file, return XCAF document"""
app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("XmlOcaf"))
app.InitDocument(doc)
reader = STEPCAFControl_Reader()
status = reader.ReadFile(str(stepfile))
assert status == IFSelect_RetDone
reader.Transfer(doc)
return doc
def get_doc_nodes(doc, leaf=False):
"""Read document and return list of nodes (dicts)"""
if leaf:
flags = XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes
else:
flags = XCAFPrs_DocumentExplorerFlags_None
expl = XCAFPrs_DocumentExplorer(doc, flags, XCAFPrs_Style())
tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
nodes = []
while expl.More():
node = expl.Current()
ctool = expl.ColorTool()
style = node.Style
label = node.RefLabel
label2 = node.Label
name_att = TDataStd_Name()
label.FindAttribute(TDataStd_Name.GetID_s(), name_att)
if label2.IsAttribute(TDataStd_Name.GetID_s()):
name_att = TDataStd_Name()
label2.FindAttribute(TDataStd_Name.GetID_s(), name_att)
color = style.GetColorSurfRGBA()
shape = expl.FindShapeFromPathId_s(doc, node.Id)
color_shape = Quantity_ColorRGBA()
ctool.GetColor(shape, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_shape)
# on STEP import colors applied to subshapes; and fused export mode
color_subshapes = None
color_subshapes_set = set()
faces = []
if not node.IsAssembly:
it = TDF_ChildIterator(label)
while it.More():
child = it.Value()
child_shape = tool.GetShape_s(child)
if child_shape.ShapeType() == TopAbs_ShapeEnum.TopAbs_FACE:
face = Face(child_shape)
color_subshape = Quantity_ColorRGBA()
face_color = None
if ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorGen, color_subshape
) or ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_subshape
):
face_color = (
*color_subshape.GetRGB().Values(Quantity_TOC_sRGB),
color_subshape.Alpha(),
)
faces.append(
{"center": face.Center().toTuple(), "color": face_color}
)
else:
color_subshape = Quantity_ColorRGBA()
if ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_subshape
):
color_subshapes_set.add(
(
*color_subshape.GetRGB().Values(Quantity_TOC_sRGB),
color_subshape.Alpha(),
)
)
it.Next()
if color_subshapes_set:
color_subshapes = color_subshapes_set.pop()
nodes.append(
{
"path": PurePath(node.Id.ToCString()),
"name": TCollection_ExtendedString(name_att.Get()).ToExtString(),
"color": (*color.GetRGB().Values(Quantity_TOC_sRGB), color.Alpha()),
"color_shape": (
*color_shape.GetRGB().Values(Quantity_TOC_sRGB),
color_shape.Alpha(),
),
"color_subshapes": color_subshapes,
"faces": faces,
}
)
expl.Next()
return nodes
def find_node(node_list, name_path):
"""Return node(s) matching node name path
:param node_list: list of nodes (output of get_doc_nodes)
:param name_path: list of node names (corresponding to path)
"""
def purepath_is_relative_to(p0, p1):
"""Alternative to PurePath.is_relative_to for Python 3.8
PurePath.is_relative_to is new in Python 3.9
"""
try:
if p0.relative_to(p1):
is_relative_to = True
except ValueError:
is_relative_to = False
return is_relative_to
def get_nodes(node_list, name, parents):
if parents:
nodes = []
for parent in parents:
nodes.extend(
[
p
for p in node_list
# if p["path"].is_relative_to(parent["path"])
if purepath_is_relative_to(p["path"], parent["path"])
and len(p["path"].relative_to(parent["path"]).parents) == 1
and re.fullmatch(name, p["name"])
and p not in nodes
]
)
else:
nodes = [p for p in node_list if re.fullmatch(name, p["name"])]
return nodes
parents = None
for name in name_path:
nodes = get_nodes(node_list, name, parents)
parents = nodes
return nodes
def test_metadata(metadata_assy):
"""Verify the metadata is present in both the base and sub assemblies"""
assert metadata_assy.metadata["b1"] == "base-data"
# The metadata should be able to be modified
metadata_assy.metadata["b2"] = 0
assert len(metadata_assy.metadata) == 2
# Test that metadata was copied by _copy() during the processing of adding the subassembly
assert metadata_assy.children[0].metadata["b2"] == "sub-data"
assert metadata_assy.children[1].metadata["mykey"] == "sub2-data-add"
assert metadata_assy.children[1].children[0].metadata["mykey"] == "sub2-0-data"
assert metadata_assy.children[1].children[1].metadata["mykey"] == "sub2-1-data"
def solve_result_check(solve_result: dict) -> bool:
checks = [
solve_result["success"] == True,
solve_result["iterations"]["inf_pr"][-1] < 1e-9,
]
return all(checks)
def test_color():
c1 = cq.Color("red")
assert c1.wrapped.GetRGB().Red() == 1
assert c1.wrapped.Alpha() == 1
c2 = cq.Color(1, 0, 0)
assert c2.wrapped.GetRGB().Red() == 1
assert c2.wrapped.Alpha() == 1
c3 = cq.Color(1, 0, 0, 0.5)
assert c3.wrapped.GetRGB().Red() == 1
assert c3.wrapped.Alpha() == 0.5
# test for srgb
c4 = cq.Color(0.5, 0.2, 0, 0.5, True)
assert c4.wrapped.GetRGB().Red() != 0.5
assert c4.wrapped.GetRGB().Green() != 0.2
assert c4.wrapped.Alpha() == 0.5
# test for linear rgb
c4 = cq.Color(0.5, 0.2, 0, 0.5, False)
assert c4.wrapped.GetRGB().Red() == pytest.approx(0.5)
assert c4.wrapped.GetRGB().Green() == pytest.approx(0.2)
assert c4.wrapped.Alpha() == 0.5
with pytest.raises(ValueError):
cq.Color("?????")
with pytest.raises(ValueError):
cq.Color(1, 2, 3, 4, 5, 6)
def test_assembly(simple_assy, nested_assy):
# basic checks
assert len(simple_assy.objects) == 3
assert len(simple_assy.children) == 2
assert len(simple_assy.shapes) == 1
assert len(nested_assy.objects) == 3
assert len(nested_assy.children) == 1
assert nested_assy.objects["SECOND"].parent is nested_assy
# bottom-up traversal
kvs = list(nested_assy.traverse())
assert kvs[0][0] == "BOTTOM"
assert len(kvs[0][1].shapes[0].Solids()) == 2
assert kvs[-1][0] == "TOP"
@pytest.mark.parametrize(
"assy_fixture, root_name", [("simple_assy", None), ("nested_assy", "TOP")],
)
def test_assy_root_name(assy_fixture, root_name, request):
assy = request.getfixturevalue(assy_fixture)
_, doc = toCAF(assy, True)
root = get_doc_nodes(doc, False)[0]
if root_name:
assert root["name"] == root_name
else:
# When a name is not user-specifed, the name is assigned a UUID
m = re.findall(r"[0-9a-f]+", root["name"])
assert list(map(len, m)) == [8, 4, 4, 4, 12]
def test_step_export(nested_assy, tmp_path_factory):
# Use a temporary directory
tmpdir = tmp_path_factory.mktemp("out")
nested_path = os.path.join(tmpdir, "nested.step")
nested_options_path = os.path.join(tmpdir, "nested_options.step")
exportAssembly(nested_assy, nested_path)
exportAssembly(
nested_assy, nested_options_path, write_pcurves=False, precision_mode=0
)
w = cq.importers.importStep(nested_path)
o = cq.importers.importStep(nested_options_path)
assert w.solids().size() == 4
assert o.solids().size() == 4
# check that locations were applied correctly
c = cq.Compound.makeCompound(w.solids().vals()).Center()
assert pytest.approx(c.toTuple()) == (0, 4, 0)
c2 = cq.Compound.makeCompound(o.solids().vals()).Center()
assert pytest.approx(c2.toTuple()) == (0, 4, 0)
def test_meta_step_export(tmp_path_factory):
"""
Tests that an assembly can be exported to a STEP file with faces tagged with names and colors,
and layers added.
"""
# Use a temporary directory
tmpdir = tmp_path_factory.mktemp("out")
meta_path = os.path.join(tmpdir, "meta.step")
# Most nested level of the assembly
subsubassy = cq.Assembly(name="third-level")
cone_1 = cq.Workplane(cone(5.0, 10.0, 5.0))
cone_2 = cq.Workplane(cone(2.5, 5.0, 2.5))
subsubassy.add(
cone_1,
name="cone_1",
color=cq.Color(1.0, 1.0, 1.0),
loc=cq.Location(-15.0, 10.0, 0.0),
)
subsubassy.add(
cone_2,
name="cone_2",
color=cq.Color(0.0, 0.0, 0.0),
loc=cq.Location((15.0, 10.0, -5.0)),
)
# First layer of nested assembly
subassy = cq.Assembly(name="second-level")
cylinder_1 = cq.Workplane().cylinder(radius=5.0, height=10.0)
cylinder_2 = cq.Workplane().cylinder(radius=2.5, height=5.0)
subassy.add(
cylinder_1,
name="cylinder_1",
color=cq.Color(1.0, 1.0, 0.0),
loc=cq.Location(-15.0, 0.0, 0.0),
)
subassy.add(
cylinder_2,
name="cylinder_2",
color=cq.Color(0.0, 1.0, 1.0),
loc=cq.Location((15.0, -10.0, -5.0)),
)
subassy.add(subsubassy)
# Top level of the assembly
assy = cq.Assembly(name="top-level")
cube_1 = cq.Workplane().box(10.0, 10.0, 10.0)
assy.add(cube_1, name="cube_1", color=cq.Color(0.5, 0.0, 0.5))
cube_2 = cq.Workplane().box(5.0, 5.0, 5.0)
assy.add(
cube_2,
name="cube_2",
color=cq.Color(0.0, 0.5, 0.0),
loc=cq.Location(10.0, 10.0, 10.0),
)
assy.add(subassy)
# Tag faces to test from all levels of the assembly
assy.addSubshape(cube_1.faces(">Z").val(), name="cube_1_top_face")
assy.addSubshape(cube_1.faces(">Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.addSubshape(cube_1.faces(">Z").val(), layer="cube_1_top_face")
assy.cube_2.addSubshape(cube_2.faces("<Z").val(), name="cube_2_bottom_face")
assy.cube_2.addSubshape(cube_2.faces("<Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.cube_2.addSubshape(cube_2.faces("<Z").val(), layer="cube_2_bottom_face")
with pytest.raises(ValueError):
assy.addSubshape(cylinder_1.faces(">Z").val(), name="cylinder_1_top_face")
assy.addSubshape(cylinder_1.faces(">Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.addSubshape(cylinder_1.faces(">Z").val(), layer="cylinder_1_top_face")
assy.addSubshape(cylinder_2.faces("<Z").val(), name="cylinder_2_bottom_face")
assy.addSubshape(cylinder_2.faces("<Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.addSubshape(cylinder_2.faces("<Z").val(), layer="cylinder_2_bottom_face")
assy.addSubshape(cone_1.faces(">Z").val(), name="cone_1_top_face")
assy.addSubshape(cone_1.faces(">Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.addSubshape(cone_1.faces(">Z").val(), layer="cone_1_top_face")
assy.addSubshape(cone_2.faces("<Z").val(), name="cone_2_bottom_face")
assy.addSubshape(cone_2.faces("<Z").val(), color=cq.Color(1.0, 0.0, 0.0))
assy.addSubshape(cone_2.faces("<Z").val(), layer="cone_2_bottom_face")
# Write once with pcurves turned on
success = exportStepMeta(assy, meta_path)
assert success
# Write again with pcurves turned off
success = exportStepMeta(assy, meta_path, write_pcurves=False)
assert success
# Make sure the step file exists
assert os.path.exists(meta_path)
# Read the contents as a step file as a string so we can check the outputs
with open(meta_path, "r") as f:
step_contents = f.read()
# Make sure that the face name strings were applied in ADVACED_FACE entries
assert "ADVANCED_FACE('cube_1_top_face'" in step_contents
assert "ADVANCED_FACE('cube_2_bottom_face'" in step_contents
# Make reasonably sure that the colors were applied to the faces
assert "DRAUGHTING_PRE_DEFINED_COLOUR('black')" in step_contents
assert "DRAUGHTING_PRE_DEFINED_COLOUR('white')" in step_contents
assert "DRAUGHTING_PRE_DEFINED_COLOUR('cyan')" in step_contents
assert "DRAUGHTING_PRE_DEFINED_COLOUR('yellow')" in step_contents
# Make sure that the layers were created
assert (
"PRESENTATION_LAYER_ASSIGNMENT('cube_1_top_face','visible'" in step_contents
)
assert (
"PRESENTATION_LAYER_ASSIGNMENT('cube_2_bottom_face','visible'"
in step_contents
)
def test_meta_step_export_edge_cases(tmp_path_factory):
"""
Test all the edge cases of the STEP export function.
"""
# Use a temporary directory
tmpdir = tmp_path_factory.mktemp("out")
meta_path = os.path.join(tmpdir, "meta_edges_cases.step")
# Create an assembly where the child is empty
assy = cq.Assembly(name="top-level")
subassy = cq.Assembly(name="second-level")
assy.add(subassy)
# Write an assembly with no children
success = exportStepMeta(assy, meta_path)
assert success
# Test an object with no color set
cube = cq.Workplane().box(10.0, 10.0, 10.0)
assy.add(cube, name="cube")
success = exportStepMeta(assy, meta_path)
assert success
# Tag a face that does not match the object
with pytest.raises(ValueError):
assy.addSubshape(plane(1, 1), name="cube_top_face")
# Tag the name but nothing else
assy.addSubshape(cube.faces(">Z").val(), name="cube_top_face")
success = exportStepMeta(assy, meta_path)
assert success
# Reset the assembly
assy.remove("cube")
cube = cq.Workplane().box(9.9, 9.9, 9.9)
assy.add(cube, name="cube")
# Tag the color but nothing else
assy.addSubshape(cube.faces(">Z").val(), color=cq.Color(1.0, 0.0, 0.0))
success = exportStepMeta(assy, meta_path)
assert success
# Reset the assembly
assy.remove("cube")
cube = cq.Workplane().box(9.8, 9.8, 9.8)
assy.add(cube, name="cube")
# Tag the layer but nothing else
assy.addSubshape(cube.faces(">Z").val(), layer="cube_top_face")
success = exportStepMeta(assy, meta_path)
assert success
def test_assembly_step_import(tmp_path_factory, subshape_assy):
"""
Test if the STEP import works correctly for an assembly with subshape data attached.
"""
# Use a temporary directory
tmpdir = tmp_path_factory.mktemp("out")
assy_step_path = os.path.join(tmpdir, "assembly_with_subshapes.step")
subshape_assy.export(assy_step_path)
# Import the STEP file back in
imported_assy = cq.Assembly.importStep(assy_step_path)
# Check that the assembly was imported successfully
assert imported_assy is not None
# Check for appropriate part name
assert imported_assy.children[0].name == "cube_1"
# Check for approximate color match
assert pytest.approx(imported_assy.children[0].color.toTuple(), rel=0.01) == (
0.0,
1.0,
0.0,
1.0,
)
# Check for appropriate part name
assert imported_assy.children[1].name == "cyl_1"
# Check for approximate color match
assert pytest.approx(imported_assy.children[1].color.toTuple(), rel=0.01) == (
0.0,
0.0,
1.0,
1.0,
)
# Make sure the shape locations were applied correctly
assert imported_assy.children[1].loc.toTuple()[0] == (0.0, 0.0, -10.0)
# Check the top-level assembly name
assert imported_assy.name == "top_level"
# Test a STEP file that does not contain an assembly
wp_step_path = os.path.join(tmpdir, "plain_workplane.step")
res = cq.Workplane().box(10, 10, 10)
res.export(wp_step_path)
# Import the STEP file back in
with pytest.raises(ValueError):
imported_assy = cq.Assembly.importStep(wp_step_path)
@pytest.mark.parametrize("kind", ["step", "xml", "xbf"])
def test_assembly_subshape_import(tmp_path_factory, subshape_assy, kind):
"""
Test if a STEP/XBF/XML file containing subshape information can be imported correctly.
"""
tmpdir = tmp_path_factory.mktemp("out")
assy_step_path = os.path.join(tmpdir, f"subshape_assy.{kind}")
# Export the assembly
subshape_assy.export(assy_step_path)
# Import the file back in
imported_assy = cq.Assembly.load(assy_step_path)
assert imported_assy.name == "top_level"
# Check the advanced face name
assert len(imported_assy.children[0]._subshape_names) == 1
assert (
list(imported_assy.children[0]._subshape_names.values())[0] == "cube_1_top_face"
)
# Check the color
color = list(imported_assy.children[0]._subshape_colors.values())[0]
assert Quantity_NameOfColor.Quantity_NOC_RED == color.wrapped.GetRGB().Name()
# Check the layer info
layer_name = list(imported_assy["cube_1"]._subshape_layers.values())[0]
assert layer_name == "cube_1_top_face_layer"
assert (
"cylinder_bottom_face_layer" in imported_assy["cyl_1"]._subshape_layers.values()
)
assert (
"cylinder_bottom_wire_layer" in imported_assy["cyl_1"]._subshape_layers.values()
)
@pytest.mark.parametrize("kind", ["step", "xml", "xbf"])
def test_assembly_multi_subshape_import(tmp_path_factory, multi_subshape_assy, kind):
"""
Test if a file containing subshape information can be imported correctly.
"""
tmpdir = tmp_path_factory.mktemp("out")
assy_step_path = os.path.join(tmpdir, f"multi_subshape_assy.{kind}")
# Export the assembly
multi_subshape_assy.export(assy_step_path)
# Import the file back in
imported_assy = cq.Assembly.load(assy_step_path)
# Check that the top-level assembly name is correct
assert imported_assy.name == "top_level"
# Check the advanced face name for the first cube
assert len(imported_assy.children[0]._subshape_names) == 1
assert (
list(imported_assy.children[0]._subshape_names.values())[0] == "cube_1_top_face"
)
# Check the color for the first cube
color = list(imported_assy.children[0]._subshape_colors.values())[0]
assert Quantity_NameOfColor.Quantity_NOC_RED == color.wrapped.GetRGB().Name()
# Check the layer info for the first cube
layer_name = list(imported_assy.children[0]._subshape_layers.values())[0]