Programmatically add objects to Assembly (also unions)

382 views
Skip to first unread message

HJ EM

unread,
Sep 1, 2021, 7:51:29 PM9/1/21
to CadQuery
As a newbie I can't figure out how to add objects (polygons, boxes, etc) to an Assembly programmatically. Naively I would have guessed that something like this would work:

######################
import cadquery as cq

# a list of objects, polygons in my case
polys = [poly1, poly2, poly3] 

asym = cq.Assembly()
for ply in polys:
    asym.add(ply)

#save to step file, including just in case this causes an issue
asym.save('polys.step')
#########################

But that doesn't work. Additionally,  I would like to know how to programmatically add to a union. The pseudo code would look like this I would think:

#########################
import cadquery as cq

# a list of polygons, not specified
polys = [poly1, poly2, poly3] 

asym = cq.Assembly()
for i in len(polys):
    if i==0:
        mainpoly = polys[i]
    else:
        mainpoly.union(polys[i])

#########################

What's the right way to do this?

Thanks.





Roger Maitland

unread,
Sep 1, 2021, 8:36:39 PM9/1/21
to HJ EM, CadQuery
If I flush out your example a little bit to this:
import cadquery as cq

poly1 = cq.Solid.makeBox(5, 5, 5)
poly2 = cq.Solid.makeCone(5, 2.5, 5)
poly3 = cq.Solid.makeSphere(4).translate((5, 0, 0))
# a list of objects, polygons in my case
polys = [poly1, poly2, poly3]

asym = cq.Assembly()
for ply in polys:
asym.add(ply)

# save to step file, including just in case this causes an issue
asym.save("polys.step")
and open polys.step in FreeCAD I get this:
asm_example.png
Double checking poly1..3 might be worthwhile.

If you'd like to see another example of programmatically creating an assembly, take a look at my chain generator from cq_warehouse. In the same file you'll find a make_link() method that uses the union() method to build a chain link from several parts.

Cheers,
Roger

--
cadquery home: https://github.com/CadQuery/cadquery
post issues at https://github.com/CadQuery/cadquery/issues
run it at home at : https://github.com/CadQuery/CQ-editor
---
You received this message because you are subscribed to the Google Groups "CadQuery" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cadquery+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cadquery/0fc2caa6-00c6-4c85-b15d-5c42b66ee584n%40googlegroups.com.

HJ EM

unread,
Sep 3, 2021, 8:16:43 AM9/3/21
to CadQuery
Many thanks Roger. I should have flushed the example out myself and seen that there was an error elsewhere in the code. For posterity, the way to make the .union version of this work is to set the main object equal to the addition:
mainpoly  =  mainpoly.union(polys[i])
Reply all
Reply to author
Forward
0 new messages