diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..fb62e70 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "Libs/cadquery"] + path = Libs/cadquery + url = https://github.com/dcowden/cadquery.git diff --git a/Examples/Ex000_Introduction.py b/Examples/Ex000_Introduction.py deleted file mode 100644 index a11fb7f..0000000 --- a/Examples/Ex000_Introduction.py +++ /dev/null @@ -1,20 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -# From within FreeCAD, you can make changes to this script and then click -# CadQuery > Execute Script, or you can press F2. -# There are more examples in the Examples directory included with this module. -# Ex026_Lego_Brick.py is highly recommended as a great example of what CadQuery -# can do. -import cadquery -from Helpers import show - -# The dimensions of the box. These can be modified rather than changing the -# object's code directly. -length = 2.0 -height = 1.0 -thickness = 1.0 - -# Create a 3D box based on the dimension variables above -result = cadquery.Workplane("XY").box(length, height, thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex001_Simple_Block.py b/Examples/Ex001_Simple_Block.py deleted file mode 100644 index a95b064..0000000 --- a/Examples/Ex001_Simple_Block.py +++ /dev/null @@ -1,15 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the box. These can be modified rather than changing the -# object's code directly. -length = 80.0 -height = 60.0 -thickness = 10.0 - -# Create a 3D box based on the dimension variables above -result = cadquery.Workplane("XY").box(length, height, thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex002_Block_With_Bored_Center_Hole.py b/Examples/Ex002_Block_With_Bored_Center_Hole.py deleted file mode 100644 index 6203204..0000000 --- a/Examples/Ex002_Block_With_Bored_Center_Hole.py +++ /dev/null @@ -1,17 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the box. These can be modified rather than changing the -# object's code directly. -length = 80.0 -height = 60.0 -thickness = 10.0 -center_hole_dia = 22.0 - -# Create a box based on the dimensions above and add a 22mm center hole -result = cadquery.Workplane("XY").box(length, height, thickness) \ - .faces(">Z").workplane().hole(center_hole_dia) - -# Render the solid -show(result) diff --git a/Examples/Ex003_Pillow_Block_With_Counterbored_Holes.py b/Examples/Ex003_Pillow_Block_With_Counterbored_Holes.py deleted file mode 100644 index 74c1d84..0000000 --- a/Examples/Ex003_Pillow_Block_With_Counterbored_Holes.py +++ /dev/null @@ -1,23 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the box. These can be modified rather than changing the -# object's code directly. -length = 80.0 -height = 60.0 -thickness = 10.0 -center_hole_dia = 22.0 -cbore_hole_diameter = 2.4 -cbore_diameter = 4.4 -cbore_depth = 2.1 - -# Create a 3D box based on the dimensions above and add 4 counterbored holes -result = cadquery.Workplane("XY").box(length, height, thickness) \ - .faces(">Z").workplane().hole(center_hole_dia) \ - .faces(">Z").workplane() \ - .rect(length - 8.0, height - 8.0, forConstruction=True) \ - .vertices().cboreHole(cbore_hole_diameter, cbore_diameter, cbore_depth) - -# Render the solid -show(result) diff --git a/Examples/Ex004_Extruded_Cylindrical_Plate.py b/Examples/Ex004_Extruded_Cylindrical_Plate.py deleted file mode 100644 index 0de305a..0000000 --- a/Examples/Ex004_Extruded_Cylindrical_Plate.py +++ /dev/null @@ -1,18 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -circle_radius = 50.0 -rectangle_width = 13.0 -rectangle_length = 19.0 -thickness = 13.0 - -# Extrude a cylindrical plate with a rectangular hole in the middle of it -result = cadquery.Workplane("front").circle(circle_radius) \ - .rect(rectangle_width, rectangle_length) \ - .extrude(thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex005_Extruded_Lines_and_Arcs.py b/Examples/Ex005_Extruded_Lines_and_Arcs.py deleted file mode 100644 index 34e3a1b..0000000 --- a/Examples/Ex005_Extruded_Lines_and_Arcs.py +++ /dev/null @@ -1,17 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -width = 2.0 -thickness = 0.25 - -# Extrude a plate outline made of lines and an arc -result = cadquery.Workplane("front").lineTo(width, 0) \ - .lineTo(width, 1.0) \ - .threePointArc((1.0, 1.5), (0.0, 1.0)) \ - .close().extrude(thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex006_Moving_the_Current_Working_Point.py b/Examples/Ex006_Moving_the_Current_Working_Point.py deleted file mode 100644 index fbb463c..0000000 --- a/Examples/Ex006_Moving_the_Current_Working_Point.py +++ /dev/null @@ -1,22 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -circle_radius = 3.0 -thickness = 0.25 - -# Make the plate with two cutouts in it -# Current point is the center of the circle, at (0,0) -result = cadquery.Workplane("front").circle(circle_radius) -result = result.center(1.5, 0.0).rect(0.5, 0.5) # New work center is (1.5,0.0) - -result = result.center(-1.5, 1.5).circle(0.25) # New work center is ( 0.0,1.5) -# The new center is specified relative to the previous center, -# not global coordinates! - -result = result.extrude(thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex007_Using_Point_Lists.py b/Examples/Ex007_Using_Point_Lists.py deleted file mode 100644 index effd879..0000000 --- a/Examples/Ex007_Using_Point_Lists.py +++ /dev/null @@ -1,21 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -plate_radius = 2.0 -hole_pattern_radius = 0.25 -thickness = 0.125 - -# Make the plate with 4 holes in it at various points -# Make the base -r = cadquery.Workplane("front").circle(plate_radius) -# Now four points are on the stack -r = r.pushPoints([(1.5, 0), (0, 1.5), (-1.5, 0), (0, -1.5)]) -# Circle will operate on all four points -r = r.circle(hole_pattern_radius) -result = r.extrude(thickness) - -# Render the solid -show(result) diff --git a/Examples/Ex008_Polygon_Creation.py b/Examples/Ex008_Polygon_Creation.py deleted file mode 100644 index b3f3469..0000000 --- a/Examples/Ex008_Polygon_Creation.py +++ /dev/null @@ -1,20 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -width = 3.0 -height = 4.0 -thickness = 0.25 -polygon_sides = 6 -polygon_dia = 1.0 - -# Create a plate with two polygons cut through it -result = cadquery.Workplane("front").box(width, height, thickness) \ - .pushPoints([(0, 0.75), (0, -0.75)]) \ - .polygon(polygon_sides, polygon_dia) \ - .cutThruAll() - -# Render the solid -show(result) diff --git a/Examples/Ex009_Polylines.py b/Examples/Ex009_Polylines.py deleted file mode 100644 index 2de65be..0000000 --- a/Examples/Ex009_Polylines.py +++ /dev/null @@ -1,25 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Set up our Length, Height, Width, and thickness of the beam -(L, H, W, t) = (100.0, 20.0, 20.0, 1.0) - -# Define the locations that the polyline will be drawn to/thru -pts = [ - (0, H/2.0), - (W/2.0, H/2.0), - (W/2.0, (H/2.0 - t)), - (t/2.0, (H/2.0-t)), - (t/2.0, (t - H/2.0)), - (W/2.0, (t - H/2.0)), - (W/2.0, H/-2.0), - (0, H/-2.0) -] - -# We generate half of the I-beam outline and then mirror it to create the full -# I-beam -result = cadquery.Workplane("front").polyline(pts).mirrorY().extrude(L) - -# Render the solid -show(result) diff --git a/Examples/Ex010_Defining_an_Edge_with_a_Spline.py b/Examples/Ex010_Defining_an_Edge_with_a_Spline.py deleted file mode 100644 index ad985c5..0000000 --- a/Examples/Ex010_Defining_an_Edge_with_a_Spline.py +++ /dev/null @@ -1,26 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The workplane we want to create the spline on to extrude -s = cadquery.Workplane("XY") - -# The points that the spline will pass through -sPnts = [ - (2.75, 1.5), - (2.5, 1.75), - (2.0, 1.5), - (1.5, 1.0), - (1.0, 1.25), - (0.5, 1.0), - (0, 1.0) -] - -# Generate our plate with the spline feature and make sure it's a closed entity -r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close() - -# Extrude to turn the wire into a plate -result = r.extrude(0.5) - -# Render the solid -show(result) diff --git a/Examples/Ex011_Mirroring_Symmetric_Geometry.py b/Examples/Ex011_Mirroring_Symmetric_Geometry.py deleted file mode 100644 index a34a46d..0000000 --- a/Examples/Ex011_Mirroring_Symmetric_Geometry.py +++ /dev/null @@ -1,15 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# 1.0 is the distance, not coordinate -r = cadquery.Workplane("front").hLine(1.0) - -# hLineTo allows using xCoordinate not distance -r = r.vLine(0.5).hLine(-0.25).vLine(-0.25).hLineTo(0.0) - -# Mirror the geometry and extrude -result = r.mirrorY().extrude(0.25) - -# Render the solid -show(result) diff --git a/Examples/Ex012_Creating_Workplanes_on_Faces.py b/Examples/Ex012_Creating_Workplanes_on_Faces.py deleted file mode 100644 index 70ef1da..0000000 --- a/Examples/Ex012_Creating_Workplanes_on_Faces.py +++ /dev/null @@ -1,12 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Make a basic prism -result = cadquery.Workplane("front").box(2, 3, 0.5) - -# Find the top-most face and make a hole -result = result.faces(">Z").workplane().hole(0.5) - -# Render the solid -show(result) diff --git a/Examples/Ex013_Locating_a_Workplane_on_a_Vertex.py b/Examples/Ex013_Locating_a_Workplane_on_a_Vertex.py deleted file mode 100644 index dc7721a..0000000 --- a/Examples/Ex013_Locating_a_Workplane_on_a_Vertex.py +++ /dev/null @@ -1,15 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Make a basic prism -result = cadquery.Workplane("front").box(3, 2, 0.5) - -# Select the lower left vertex and make a workplane -result = result.faces(">Z").vertices("Z") \ - .workplane() \ - .transformed(offset=(0, -1.5, 1.0), rotate=(60, 0, 0)) \ - .rect(1.5, 1.5, forConstruction=True).vertices().hole(0.25) - -# Render the solid -show(result) diff --git a/Examples/Ex016_Using_Construction_Geometry.py b/Examples/Ex016_Using_Construction_Geometry.py deleted file mode 100644 index aee8058..0000000 --- a/Examples/Ex016_Using_Construction_Geometry.py +++ /dev/null @@ -1,11 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a block with holes in each corner of a rectangle on that workplane -result = cadquery.Workplane("front").box(2, 2, 0.5)\ - .faces(">Z").workplane() \ - .rect(1.5, 1.5, forConstruction=True).vertices().hole(0.125) - -# Render the solid -show(result) diff --git a/Examples/Ex017_Shelling_to_Create_Thin_Features.py b/Examples/Ex017_Shelling_to_Create_Thin_Features.py deleted file mode 100644 index b984306..0000000 --- a/Examples/Ex017_Shelling_to_Create_Thin_Features.py +++ /dev/null @@ -1,9 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a hollow box that's open on both ends with a thin wall -result = cadquery.Workplane("front").box(2, 2, 2).faces("+Z").shell(0.05) - -# Render the solid -show(result) diff --git a/Examples/Ex018_Making_Lofts.py b/Examples/Ex018_Making_Lofts.py deleted file mode 100644 index 6478f4a..0000000 --- a/Examples/Ex018_Making_Lofts.py +++ /dev/null @@ -1,11 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a lofted section between a rectangle and a circular section -result = cadquery.Workplane("front").box(4.0, 4.0, 0.25).faces(">Z") \ - .circle(1.5).workplane(offset=3.0) \ - .rect(0.75, 0.5).loft(combine=True) - -# Render the solid -show(result) diff --git a/Examples/Ex019_Counter_Sunk_Holes.py b/Examples/Ex019_Counter_Sunk_Holes.py deleted file mode 100644 index be70587..0000000 --- a/Examples/Ex019_Counter_Sunk_Holes.py +++ /dev/null @@ -1,11 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a plate with 4 counter-sunk holes in it -result = cadquery.Workplane(cadquery.Plane.XY()).box(4, 2, 0.5).faces(">Z") \ - .workplane().rect(3.5, 1.5, forConstruction=True)\ - .vertices().cskHole(0.125, 0.25, 82.0, depth=None) - -# Render the solid -show(result) diff --git a/Examples/Ex020_Rounding_Corners_with_Fillets.py b/Examples/Ex020_Rounding_Corners_with_Fillets.py deleted file mode 100644 index a2f7876..0000000 --- a/Examples/Ex020_Rounding_Corners_with_Fillets.py +++ /dev/null @@ -1,9 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a plate with 4 rounded corners in the Z-axis -result = cadquery.Workplane("XY").box(3, 3, 0.5).edges("|Z").fillet(0.125) - -# Render the solid -show(result) diff --git a/Examples/Ex021_Splitting_an_Object.py b/Examples/Ex021_Splitting_an_Object.py deleted file mode 100644 index 6cda407..0000000 --- a/Examples/Ex021_Splitting_an_Object.py +++ /dev/null @@ -1,13 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Create a simple block with a hole through it that we can split -c = cadquery.Workplane("XY").box(1, 1, 1).faces(">Z").workplane() \ - .circle(0.25).cutThruAll() - -# Cut the block in half sideways -result = c.faces(">Y").workplane(-0.5).split(keepTop=True) - -# Render the solid -show(result) diff --git a/Examples/Ex022_Classic_OCC_Bottle.py b/Examples/Ex022_Classic_OCC_Bottle.py deleted file mode 100644 index 0721335..0000000 --- a/Examples/Ex022_Classic_OCC_Bottle.py +++ /dev/null @@ -1,21 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Set up the length, width, and thickness -(L, w, t) = (20.0, 6.0, 3.0) -s = cadquery.Workplane("XY") - -# Draw half the profile of the bottle and extrude it -p = s.center(-L / 2.0, 0).vLine(w / 2.0) \ - .threePointArc((L / 2.0, w / 2.0 + t), (L, w / 2.0)).vLine(-w / 2.0) \ - .mirrorX().extrude(30.0, True) - -# Make the neck -p.faces(">Z").workplane().circle(3.0).extrude(2.0, True) - -# Make a shell -result = p.faces(">Z").shell(0.3) - -# Render the solid -show(result) diff --git a/Examples/Ex023_Parametric_Enclosure.py b/Examples/Ex023_Parametric_Enclosure.py deleted file mode 100644 index 82ebee4..0000000 --- a/Examples/Ex023_Parametric_Enclosure.py +++ /dev/null @@ -1,79 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# Parameter definitions -p_outerWidth = 100.0 # Outer width of box enclosure -p_outerLength = 150.0 # Outer length of box enclosure -p_outerHeight = 50.0 # Outer height of box enclosure - -p_thickness = 3.0 # Thickness of the box walls -p_sideRadius = 10.0 # Radius for the curves around the sides of the bo -p_topAndBottomRadius = 2.0 # Radius for the curves on the top and bottom edges - -p_screwpostInset = 12.0 # How far in from the edges the screwposts should be -p_screwpostID = 4.0 # Inner diameter of the screwpost holes, should be roughly screw diameter not including threads -p_screwpostOD = 10.0 # Outer diameter of the screwposts. Determines overall thickness of the posts - -p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any -p_boreDepth = 1.0 # Depth of the counterbore hole, if -p_countersinkDiameter = 0.0 # Outer diameter of countersink. Should roughly match the outer diameter of the screw head -p_countersinkAngle = 90.0 # Countersink angle (complete angle between opposite sides, not from center to one side) -p_lipHeight = 1.0 # Height of lip on the underside of the lid. Sits inside the box body for a snug fit. - -# Outer shell -oshell = cadquery.Workplane("XY").rect(p_outerWidth, p_outerLength) \ - .extrude(p_outerHeight + p_lipHeight) - -# Weird geometry happens if we make the fillets in the wrong order -if p_sideRadius > p_topAndBottomRadius: - oshell.edges("|Z").fillet(p_sideRadius) - oshell.edges("#Z").fillet(p_topAndBottomRadius) -else: - oshell.edges("#Z").fillet(p_topAndBottomRadius) - oshell.edges("|Z").fillet(p_sideRadius) - -# Inner shell -ishell = oshell.faces("Z").workplane(-p_thickness)\ - .rect(POSTWIDTH, POSTLENGTH, forConstruction=True)\ - .vertices() - -for v in postCenters.all(): - v.circle(p_screwpostOD / 2.0).circle(p_screwpostID / 2.0)\ - .extrude((-1.0) * ((p_outerHeight + p_lipHeight) - (2.0 * p_thickness)), True) - -# Split lid into top and bottom parts -(lid, bottom) = box.faces(">Z").workplane(-p_thickness - p_lipHeight).split(keepTop=True, keepBottom=True).all() - -# Translate the lid, and subtract the bottom from it to produce the lid inset -lowerLid = lid.translate((0, 0, -p_lipHeight)) -cutlip = lowerLid.cut(bottom).translate((p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight)) - -# Compute centers for counterbore/countersink or counterbore -topOfLidCenters = cutlip.faces(">Z").workplane().rect(POSTWIDTH, POSTLENGTH, forConstruction=True).vertices() - -# Add holes of the desired type -if p_boreDiameter > 0 and p_boreDepth > 0: - topOfLid = topOfLidCenters.cboreHole(p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness) -elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: - topOfLid = topOfLidCenters.cskHole(p_screwpostID, p_countersinkDiameter, p_countersinkAngle, (2.0) * p_thickness) -else: - topOfLid= topOfLidCenters.hole(p_screwpostID, 2.0 * p_thickness) - -# Return the combined result -result = topOfLid.combineSolids(bottom) - -# Render the solid -show(result) diff --git a/Examples/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py b/Examples/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py deleted file mode 100644 index 7bb1371..0000000 --- a/Examples/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py +++ /dev/null @@ -1,23 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -import FreeCAD - -# Create a new document that we can draw our model on -newDoc = FreeCAD.newDocument() - -# Shows a 1x1x1 FreeCAD cube in the display -initialBox = newDoc.addObject("Part::Box", "initialBox") -newDoc.recompute() - -# Make a CQ object -cqBox = cadquery.CQ(cadquery.Solid(initialBox.Shape)) - -# Extrude a peg -newThing = cqBox.faces(">Z").workplane().circle(0.5).extrude(0.25) - -# Add a FreeCAD object to the tree and then store a CQ object in it -nextShape = newDoc.addObject("Part::Feature", "nextShape") -nextShape.Shape = newThing.val().wrapped - -# Rerender the doc to see what the new solid looks like -newDoc.recompute() diff --git a/Examples/Ex025_Revolution.py b/Examples/Ex025_Revolution.py deleted file mode 100644 index da0bb39..0000000 --- a/Examples/Ex025_Revolution.py +++ /dev/null @@ -1,23 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# shape's code directly. -rectangle_width = 10.0 -rectangle_length = 10.0 -angle_degrees = 360.0 - -# Revolve a cylinder from a rectangle -# Switch comments around in this section to try the revolve operation with different parameters -result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve() -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve(angle_degrees) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5)) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5, -5),(-5, 5)) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5),(-5,5), False) - -# Revolve a donut with square walls -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, True).revolve(angle_degrees, (20, 0), (20, 10)) - -# Render the solid -show(result) diff --git a/Examples/Ex026_Lego_Brick.py b/Examples/Ex026_Lego_Brick.py deleted file mode 100644 index e52dde2..0000000 --- a/Examples/Ex026_Lego_Brick.py +++ /dev/null @@ -1,58 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -# This script can create any regular rectangular Lego(TM) Brick -import cadquery -from Helpers import show - -##### -# Inputs -###### -lbumps = 1 # number of bumps long -wbumps = 1 # number of bumps wide -thin = True # True for thin, False for thick - -# -# Lego Brick Constants-- these make a lego brick a lego :) -# -pitch = 8.0 -clearance = 0.1 -bumpDiam = 4.8 -bumpHeight = 1.8 -if thin: - height = 3.2 -else: - height = 9.6 - -t = (pitch - (2 * clearance) - bumpDiam) / 2.0 -postDiam = pitch - t # works out to 6.5 -total_length = lbumps*pitch - 2.0*clearance -total_width = wbumps*pitch - 2.0*clearance - -# make the base -s = cadquery.Workplane("XY").box(total_length, total_width, height) - -# shell inwards not outwards -s = s.faces("Z").workplane(). \ - rarray(pitch, pitch, lbumps, wbumps, True).circle(bumpDiam / 2.0) \ - .extrude(bumpHeight) - -# add posts on the bottom. posts are different diameter depending on geometry -# solid studs for 1 bump, tubes for multiple, none for 1x1 -tmp = s.faces(" 1 and wbumps > 1: - tmp = tmp.rarray(pitch, pitch, lbumps - 1, wbumps - 1, center=True). \ - circle(postDiam / 2.0).circle(bumpDiam / 2.0).extrude(height - t) -elif lbumps > 1: - tmp = tmp.rarray(pitch, pitch, lbumps - 1, 1, center=True). \ - circle(t).extrude(height - t) -elif wbumps > 1: - tmp = tmp.rarray(pitch, pitch, 1, wbumps - 1, center=True). \ - circle(t).extrude(height - t) -else: - tmp = s - -# Render the solid -show(tmp) diff --git a/Examples/Ex027_Remote_Enclosure.py b/Examples/Ex027_Remote_Enclosure.py deleted file mode 100644 index 9f900ae..0000000 --- a/Examples/Ex027_Remote_Enclosure.py +++ /dev/null @@ -1,89 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery as cq -from Helpers import show - -exploded = False # when true, moves the base away from the top so we see -showTop = True # When true, the top is rendered. -showCover = True # When true, the cover is rendered - -width = 2.2 # Nominal x dimension of the part -height = 0.5 # Height from bottom top to the top of the top :P -length = 1.5 # Nominal y dimension of the part -trapezoidFudge = 0.7 # ratio of trapezoid bases. set to 1.0 for cube -xHoleOffset = 0.500 # Holes are distributed symetrically about each axis -yHoleOffset = 0.500 -zFilletRadius = 0.50 # Fillet radius of corners perp. to Z axis. -yFilletRadius = 0.250 # Fillet readius of the top edge of the case -lipHeight = 0.1 # The height of the lip on the inside of the cover -wallThickness = 0.06 # Wall thickness for the case -coverThickness = 0.2 # Thickness of the cover plate -holeRadius = 0.30 # Button hole radius -counterSyncAngle = 100 # Countersink angle. - -xyplane = cq.Workplane("XY") -yzplane = cq.Workplane("YZ") - - -def trapezoid(b1, b2, h): - "Defines a symetrical trapezoid in the XY plane." - - y = h / 2 - x1 = b1 / 2 - x2 = b2 / 2 - return (xyplane - .polyline([(-x1, y), - (x1, y), - (x2, -y), - (-x2, -y), - (-x1, y)])) - - -# Defines our base shape: a box with fillets around the vertical edges. -# This has to be a function because we need to create multiple copies of -# the shape. -def base(h): - return (trapezoid(width, width * trapezoidFudge, length) - .extrude(h) - .translate((0, 0, height / 2)) - .edges("Z") - .fillet(zFilletRadius)) - -# start with the base shape -top = (base(height) - # then fillet the top edge - .edges(">Z") - .fillet(yFilletRadius) - # shell the solid from the bottom face, with a .060" wall thickness - .faces("-Z") - .shell(-wallThickness) - # cut five button holes into the top face in a cross pattern. - .faces("+Z") - .workplane() - .pushPoints([(0, 0), - (-xHoleOffset, 0), - (0, -yHoleOffset), - (xHoleOffset, 0), - (0, yHoleOffset)]) - .cskHole(diameter=holeRadius, - cskDiameter=holeRadius * 1.5, - cskAngle=counterSyncAngle)) - -# the bottom cover begins with the same basic shape as the top -cover = (base(coverThickness) - # we need to move it upwards into the parent solid slightly. - .translate((0, 0, -coverThickness + lipHeight)) - # now we subtract the top from the cover. This produces a lip on the - # solid NOTE: that this does not account for mechanical tolerances. - # But it looks cool. - .cut(top) - # try to fillet the inner edge of the cover lip. Technically this - # fillets every edge perpendicular to the Z axis. - .edges("#Z") - .fillet(.020) - .translate((0, 0, -0.5 if exploded else 0))) - -# Conditionally render the parts -if showTop: - show(top) -if showCover: - show(cover) diff --git a/Examples/Ex028_Numpy.py b/Examples/Ex028_Numpy.py deleted file mode 100644 index 0aa12a0..0000000 --- a/Examples/Ex028_Numpy.py +++ /dev/null @@ -1,26 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import numpy as np -import cadquery -from Helpers import show - -# Square side and offset in x and y. -side = 10 -offset = 5 - -# Define the locations that the polyline will be drawn to/thru. -# The polyline is defined as numpy.array so that operations like translation -# of all points are simplified. -pts = np.array([ - (0, 0), - (side, 0), - (side, side), - (0, side), - (0, 0), -]) + [offset, offset] - -result = cadquery.Workplane('XY') \ - .polyline(pts).extrude(2) \ - .faces('+Z').workplane().circle(side / 2).extrude(1) - -# Render the solid -show(result) diff --git a/Examples/Ex029_Braille.py b/Examples/Ex029_Braille.py deleted file mode 100644 index c366f4a..0000000 --- a/Examples/Ex029_Braille.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals, division - -from collections import namedtuple - -import cadquery as cq -from Helpers import show - -# text_lines is a list of text lines. -# FreeCAD in braille (converted with braille-converter: -# https://github.com/jpaugh/braille-converter.git). -text_lines = ['⠠ ⠋ ⠗ ⠑ ⠑ ⠠ ⠉ ⠠ ⠁ ⠠ ⠙'] -# See http://www.tiresias.org/research/reports/braille_cell.htm for examples -# of braille cell geometry. -horizontal_interdot = 2.5 -vertical_interdot = 2.5 -horizontal_intercell = 6 -vertical_interline = 10 -dot_height = 0.5 -dot_diameter = 1.3 - -base_thickness = 1.5 - -# End of configuration. -BrailleCellGeometry = namedtuple('BrailleCellGeometry', - ('horizontal_interdot', - 'vertical_interdot', - 'intercell', - 'interline', - 'dot_height', - 'dot_diameter')) - - -class Point(object): - def __init__(self, x, y): - self.x = x - self.y = y - - def __add__(self, other): - return Point(self.x + other.x, self.y + other.y) - - def __len__(self): - return 2 - - def __getitem__(self, index): - return (self.x, self.y)[index] - - def __str__(self): - return '({}, {})'.format(self.x, self.y) - - -def brailleToPoints(text, cell_geometry): - # Unicode bit pattern (cf. https://en.wikipedia.org/wiki/Braille_Patterns). - mask1 = 0b00000001 - mask2 = 0b00000010 - mask3 = 0b00000100 - mask4 = 0b00001000 - mask5 = 0b00010000 - mask6 = 0b00100000 - mask7 = 0b01000000 - mask8 = 0b10000000 - masks = (mask1, mask2, mask3, mask4, mask5, mask6, mask7, mask8) - - # Corresponding dot position - w = cell_geometry.horizontal_interdot - h = cell_geometry.vertical_interdot - pos1 = Point(0, 2 * h) - pos2 = Point(0, h) - pos3 = Point(0, 0) - pos4 = Point(w, 2 * h) - pos5 = Point(w, h) - pos6 = Point(w, 0) - pos7 = Point(0, -h) - pos8 = Point(w, -h) - pos = (pos1, pos2, pos3, pos4, pos5, pos6, pos7, pos8) - - # Braille blank pattern (u'\u2800'). - blank = '⠀' - points = [] - # Position of dot1 along the x-axis (horizontal). - character_origin = 0 - for c in text: - for m, p in zip(masks, pos): - delta_to_blank = ord(c) - ord(blank) - if (m & delta_to_blank): - points.append(p + Point(character_origin, 0)) - character_origin += cell_geometry.intercell - return points - - -def get_plate_height(text_lines, cell_geometry): - # cell_geometry.vertical_interdot is also used as space between base - # borders and characters. - return (2 * cell_geometry.vertical_interdot + - 2 * cell_geometry.vertical_interdot + - (len(text_lines) - 1) * cell_geometry.interline) - - -def get_plate_width(text_lines, cell_geometry): - # cell_geometry.horizontal_interdot is also used as space between base - # borders and characters. - max_len = max([len(t) for t in text_lines]) - return (2 * cell_geometry.horizontal_interdot + - cell_geometry.horizontal_interdot + - (max_len - 1) * cell_geometry.intercell) - - -def get_cylinder_radius(cell_geometry): - """Return the radius the cylinder should have - - The cylinder have the same radius as the half-sphere make the dots (the - hidden and the shown part of the dots). - The radius is such that the spherical cap with diameter - cell_geometry.dot_diameter has a height of cell_geometry.dot_height. - """ - h = cell_geometry.dot_height - r = cell_geometry.dot_diameter / 2 - return (r ** 2 + h ** 2) / 2 / h - - -def get_base_plate_thickness(plate_thickness, cell_geometry): - """Return the height on which the half spheres will sit""" - return (plate_thickness + - get_cylinder_radius(cell_geometry) - - cell_geometry.dot_height) - - -def make_base(text_lines, cell_geometry, plate_thickness): - base_width = get_plate_width(text_lines, cell_geometry) - base_height = get_plate_height(text_lines, cell_geometry) - base_thickness = get_base_plate_thickness(plate_thickness, cell_geometry) - base = cq.Workplane('XY').box(base_width, base_height, base_thickness, - centered=(False, False, False)) - return base - - -def make_embossed_plate(text_lines, cell_geometry): - """Make an embossed plate with dots as spherical caps - - Method: - - make a thin plate on which sit cylinders - - fillet the upper edge of the cylinders so to get pseudo half-spheres - - make the union with a thicker plate so that only the sphere caps stay - "visible". - """ - base = make_base(text_lines, cell_geometry, base_thickness) - - dot_pos = [] - base_width = get_plate_width(text_lines, cell_geometry) - base_height = get_plate_height(text_lines, cell_geometry) - y = base_height - 3 * cell_geometry.vertical_interdot - line_start_pos = Point(cell_geometry.horizontal_interdot, y) - for text in text_lines: - dots = brailleToPoints(text, cell_geometry) - dots = [p + line_start_pos for p in dots] - dot_pos += dots - line_start_pos += Point(0, -cell_geometry.interline) - - r = get_cylinder_radius(cell_geometry) - base = base.faces('>Z').vertices('Z').edges() \ - .fillet(r - 0.001) - hidding_box = cq.Workplane('XY').box( - base_width, base_height, base_thickness, centered=(False, False, False)) - result = hidding_box.union(base) - return result - -_cell_geometry = BrailleCellGeometry( - horizontal_interdot, - vertical_interdot, - horizontal_intercell, - vertical_interline, - dot_height, - dot_diameter) - -if base_thickness < get_cylinder_radius(_cell_geometry): - raise ValueError('Base thickness should be at least {}'.format(dot_height)) - -show(make_embossed_plate(text_lines, _cell_geometry)) diff --git a/Examples/Ex030_Panel_with_Various_Holes_for_Connector_Installation.py b/Examples/Ex030_Panel_with_Various_Holes_for_Connector_Installation.py deleted file mode 100644 index f3f08b4..0000000 --- a/Examples/Ex030_Panel_with_Various_Holes_for_Connector_Installation.py +++ /dev/null @@ -1,47 +0,0 @@ -# This example is meant to be used from within the CadQuery module of FreeCAD. -import cadquery -from Helpers import show - -# The dimensions of the model. These can be modified rather than changing the -# object's code directly. -width = 400 -height = 500 -thickness = 2 - -# Create a plate with two polygons cut through it -result = cadquery.Workplane("front").box(width, height, thickness) - -h_sep = 60 -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(157,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(157,-30-idx*h_sep).moveTo(-16.65,0).circle(1.6).moveTo(16.65,0).circle(1.6).moveTo(-10.1889,-5.7).threePointArc((-12.59306,-4.70416),(-13.5889,-2.3)).lineTo(-14.4,2.3).threePointArc((-13.40416,4.70416),(-11,5.7)).lineTo(11,5.7).threePointArc((13.40416,4.70416),(14.4,2.3)).lineTo(13.5889,-2.3).threePointArc((12.59306,-4.70416),(10.1889,-5.7)).close().cutThruAll() - -h_sep4DB9 = 30 -for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(91,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(25,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(25,-30-idx*h_sep).moveTo(-16.65,0).circle(1.6).moveTo(16.65,0).circle(1.6).moveTo(-10.1889,-5.7).threePointArc((-12.59306,-4.70416),(-13.5889,-2.3)).lineTo(-14.4,2.3).threePointArc((-13.40416,4.70416),(-11,5.7)).lineTo(11,5.7).threePointArc((13.40416,4.70416),(14.4,2.3)).lineTo(13.5889,-2.3).threePointArc((12.59306,-4.70416),(10.1889,-5.7)).close().cutThruAll() - -for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-41,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-107,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-107,-30-idx*h_sep).circle(14).rect(24.7487,24.7487, forConstruction=True).vertices().hole(3.2).cutThruAll() - -for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-173,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - -for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-173,-30-idx*h_sep).moveTo(-2.9176,-5.3).threePointArc((-6.05,0),(-2.9176,5.3)).lineTo(2.9176,5.3).threePointArc((6.05,0),(2.9176,-5.3)).close().cutThruAll() - -# Render the solid -show(result) diff --git a/Examples/Ex031_Sweep.py b/Examples/Ex031_Sweep.py deleted file mode 100644 index 16201b9..0000000 --- a/Examples/Ex031_Sweep.py +++ /dev/null @@ -1,42 +0,0 @@ -# This example is meant to be used from within the CadQuery module for FreeCAD -import cadquery -from Helpers import show - -# Points we will use to create spline and polyline paths to sweep over -pts = [ - (0, 1), - (1, 2), - (2, 4) -] - -# Spline path generated from our list of points (tuples) -path = cadquery.Workplane("XZ").spline(pts) - -# Sweep a circle with a diameter of 1.0 units along the spline path we just created -defaultSweep = cadquery.Workplane("XY").circle(1.0).sweep(path) - -# Sweep defaults to making a solid and not generating a Frenet solid. Setting Frenet to True helps prevent creep in -# the orientation of the profile as it is being swept -frenetShell = cadquery.Workplane("XY").circle(1.0).sweep(path, makeSolid=False, isFrenet=True) - -# We can sweep shapes other than circles -defaultRect = cadquery.Workplane("XY").rect(1.0, 1.0).sweep(path) - -# Switch to a polyline path, but have it use the same points as the spline -path = cadquery.Workplane("XZ").polyline(pts) - -# Using a polyline path leads to the resulting solid having segments rather than a single swept outer face -plineSweep = cadquery.Workplane("XY").circle(1.0).sweep(path) - -# Switch to an arc for the path -path = cadquery.Workplane("XZ").threePointArc((1.0, 1.5), (0.0, 1.0)) - -# Use a smaller circle section so that the resulting solid looks a little nicer -arcSweep = cadquery.Workplane("XY").circle(0.5).sweep(path) - -# Translate the resulting solids so that they do not overlap and display them left to right -show(defaultSweep) -show(frenetShell.translate((5, 0, 0))) -show(defaultRect.translate((10, 0, 0))) -show(plineSweep.translate((15, 0, 0))) -show(arcSweep.translate((20, 0, 0))) \ No newline at end of file diff --git a/Examples/Ex032_3D_Printer_Extruder_Support.py b/Examples/Ex032_3D_Printer_Extruder_Support.py deleted file mode 100644 index 556a4d1..0000000 --- a/Examples/Ex032_3D_Printer_Extruder_Support.py +++ /dev/null @@ -1,216 +0,0 @@ -# 3d printer for mounting hotend to X-carriage inspired by the P3steel Toolson -# edition - http://www.thingiverse.com/thing:1054909 -import cadquery as cq -from Helpers import show - - -def move_to_center(cqObject, shape): - ''' - Moves the origin of the current Workplane to the center of a given - geometry object - ''' - - # transform to workplane local coordinates - shape_center = shape.Center().sub(cqObject.plane.origin) - - # project onto plane using dot product - x_offset = shape_center.dot(cqObject.plane.xDir) - y_offset = shape_center.dot(cqObject.plane.yDir) - - return cqObject.center(x_offset, y_offset) - -# Parameter definitions - -main_plate_size_y = 67 # size of the main plate in y direction -main_plate_size_x = 50. # size of the main plate in x direction -main_plate_thickness = 10. # thickness of the main plate - -wing_size_x = 10. # size of the side wing supporting the bridge in x direction -wing_size_y = 10. # size of the side wing supporting the bridge in y direction - -bridge_depth = 35. # depth of the bridge - -support_depth = 18. # depth of the bridge support - -cutout_depth = 15. # depth of the hotend cutout -cutout_rad = 8. # radius of the cutout (cf groove mount sizes of E3D hotends) -cutout_offset = 2. # delta radius of the second cutout (cf groove mount sizes of E3D hotends) - -extruder_hole_spacing = 50. # spacing of the extruder mounting holes (Wade's geared extruder) - -m4_predrill = 3.7 # hole diameter for m4 tapping -m3_predrill = 2.5 # hole diameter for m3 tapping -m3_cbore = 5. # counterbore size for m3 socket screw - -mounting_hole_spacing = 28. # spacing of the mounting holes for attaching to x-carriage - -aux_hole_depth = 6. # depth of the auxiliary holes at the sides of the object -aux_hole_spacing = 5. # spacing of the auxiliary holes within a group -aux_hole_N = 2 # number of the auxiliary hole per group - -# make the main plate -res = cq.Workplane('front').box(main_plate_size_x, - main_plate_size_y, - main_plate_thickness) - - -def add_wing(obj, sign=1): - ''' - Adds a wing to the main plate, defined to keep the code DRY - ''' - obj = obj.workplane()\ - .hLine(sign*wing_size_x)\ - .vLine(-wing_size_y)\ - .line(-sign*wing_size_x, -2*wing_size_y)\ - .close().extrude(main_plate_thickness) - return obj - -# add wings - -# add right wing -res = res.faces('XY') -res = add_wing(res) - -# store sides of the plate for further reuse, their area is used later on to calculate "optimum" spacing of the aux hole groups -face_right = res.faces('>X[1]').val() -face_left = res.faces('>X[-2]').val() - -# add left wing -res = res.faces('Y').vertices('Z') # select top face -e = wp.edges('>Y') # select most extreme edge in Y direction - -bridge_length = e.val().Length() # the width of the bridge equals to the length of the selected edge - -# draw the bridge x-section and extrude -res = e.vertices('Z[1]') # take all faces in Z direction and select the middle one; note the new selector syntax -edge = faces.edges('>Y') # select the top edge of this face... -res = move_to_center(faces.workplane(), edge.val()).\ - transformed(rotate=(0, 90, 0)) # ...and make a workplane that is centered in this edge and oriented along X direction - -res = res.vLine(-support_depth).\ - line(-support_depth, support_depth).\ - close() # draw a triangle - -res = res.extrude(main_plate_size_x/2, both=True, clean=True) # extrude the triangle, now the bridge has a nice support making it much more stiff - -# Start cutting out a slot for hotend mounting -face = res.faces('>Y') # select the most extreme face in Y direction, i.e. top ot the "bridge" -res = move_to_center(face.workplane(), face.edges('>Z').val()) # shift the workplane to the center of the most extreme edge of the bridge - - -def make_slot(obj, depth=None): - ''' - Utility function that makes a slot for hotend mounting - ''' - obj = obj.moveTo(cutout_rad, -cutout_depth).\ - threePointArc((0, -cutout_depth-cutout_rad), - (-cutout_rad, -cutout_depth)).\ - vLineTo(0).hLineTo(cutout_rad).close() - - if depth is None: - obj = obj.cutThruAll() - else: - obj = obj.cutBlind(depth) - - return obj - -res = make_slot(res, None) # make the smaller slot - -cutout_rad += cutout_offset # increase the cutout radius... -res = make_slot(res.end().end(), -main_plate_thickness/2) # ...and make a slightly larger slot - -res = res.end().moveTo(0, 0) \ - .pushPoints([(-extruder_hole_spacing/2, -cutout_depth), (extruder_hole_spacing/2, -cutout_depth)]) \ - .hole(m4_predrill) # add extruder mounting holes at the top of the bridge - - -# make additional slot in the bridge support which allows the hotend's radiator to fit -cutout_rad += 3*cutout_offset -res = make_slot(res.end().moveTo(0, 0).workplane(offset=-main_plate_thickness)) - -# add reinforcement holes -cutout_rad -= 2*cutout_offset -res = res.faces('>Z').workplane().\ - pushPoints([(-cutout_rad, -main_plate_thickness/4), - (cutout_rad, -main_plate_thickness/4)]).\ - hole(m3_predrill) - -# add aux holes on the front face -res = res.moveTo(-main_plate_size_x/2., 0).workplane().rarray(aux_hole_spacing, 1, aux_hole_N, 1) \ - .hole(m3_predrill, depth=aux_hole_depth) -res = res.moveTo(main_plate_size_x, 0).workplane().rarray(aux_hole_spacing, 1, aux_hole_N, 1) \ - .hole(m3_predrill, depth=aux_hole_depth) - -# make a hexagonal cutout -res = res.faces('>Z[1]') -res = res.workplane(offset=bridge_depth). \ - transformed(rotate=(0, 0, 90)). \ - polygon(6, 30).cutThruAll() - -# make 4 mounting holes with cbores -res = res.end().moveTo(0, 0). \ - rect(mounting_hole_spacing, - mounting_hole_spacing, forConstruction=True) - -res = res.vertices(). \ - cboreHole(m3_predrill, - m3_cbore, - bridge_depth+m3_cbore/2) - -# make cutout and holes for mounting of the fan -res = res.transformed(rotate=(0, 0, 45)). \ - rect(35, 35).cutBlind(-bridge_depth).end(). \ - rect(25, 25, forConstruction=True).vertices().hole(m3_predrill) - - -def make_aux_holes(workplane, holes_span, N_hole_groups=3): - ''' - Utility function for creation of auxiliary mouting holes at the sides of the object - ''' - res = workplane.moveTo(-holes_span/2).workplane().rarray(aux_hole_spacing, 1, aux_hole_N, 1) \ - .hole(m3_predrill, depth=aux_hole_depth) - for i in range(N_hole_groups-1): - res = res.moveTo(holes_span/(N_hole_groups-1.)).workplane().rarray(aux_hole_spacing, 1, aux_hole_N, 1) \ - .hole(m3_predrill, depth=aux_hole_depth) - - return res - -# make aux holes at the bottom -res = res.faces('X').workplane().transformed((90, 0, 0)) -res = make_aux_holes(res, main_plate_size_x*2/3., 3) - -# make aux holes at the side (@main plate) -res = res.faces('|X').edges('X') -res = res.workplane() -res = move_to_center(res, face_right) -res = res.transformed((90, 0, 0)) -hole_sep = 0.5*face_right.Area()/main_plate_thickness -res = make_aux_holes(res, hole_sep, 2) - -# make aux holes at the side (@main plate) -res = res.faces('|X').edges('Z").shell(-0.2).\ - faces(">Z").edges("not(X or Y)").\ - chamfer(0.125) - -show(result) diff --git a/Gui/Command.py b/Gui/Command.py index f977db2..4a558eb 100644 --- a/Gui/Command.py +++ b/Gui/Command.py @@ -4,11 +4,14 @@ import imp, os, sys, tempfile import FreeCAD, FreeCADGui -from PySide import QtGui +from PySide import QtGui, QtCore import ExportCQ, ImportCQ import module_locator import Settings import Shared +from random import random +from cadquery import cqgi +from Helpers import show # Distinguish python built-in open function from the one declared here if open.__module__ == '__builtin__': @@ -20,7 +23,9 @@ class CadQueryClearOutput: def GetResources(self): return {"MenuText": "Clear Output", - "ToolTip": "Clears the script output from the Reports view"} + "Accel": "Shift+Alt+C", + "ToolTip": "Clears the script output from the Reports view", + "Pixmap": ":/icons/button_invalid.svg"} def IsActive(self): return True @@ -40,7 +45,8 @@ class CadQueryCloseScript: def GetResources(self): return {"MenuText": "Close Script", - "ToolTip": "Closes the CadQuery script"} + "ToolTip": "Closes the CadQuery script", + "Pixmap": ":/icons/edit_Cancel.svg"} def IsActive(self): return True @@ -84,7 +90,8 @@ class CadQueryExecuteExample: self.exFile = str(exFile) def GetResources(self): - return {"MenuText": str(self.exFile)} + return {"MenuText": str(self.exFile), + "Pixmap": ":/icons/accessories-text-editor.svg"} def Activated(self): FreeCAD.Console.PrintMessage(self.exFile + "\r\n") @@ -94,7 +101,7 @@ class CadQueryExecuteExample: # Start off defaulting to the Examples directory module_base_path = module_locator.module_path() - exs_dir_path = os.path.join(module_base_path, 'Examples') + exs_dir_path = os.path.join(module_base_path, 'Libs/cadquery/examples/FreeCAD') # Append this script's directory to sys.path sys.path.append(os.path.dirname(exs_dir_path)) @@ -122,23 +129,81 @@ class CadQueryExecuteScript: # Clear the old render before re-rendering Shared.clearActiveDocument() - # Save our code to a tempfile and render it - tempFile = tempfile.NamedTemporaryFile(delete=False) - tempFile.write(cqCodePane.toPlainText().encode('utf-8')) - tempFile.close() + scriptText = cqCodePane.toPlainText().encode('utf-8') - # Set some environment variables that may help the user - os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.file.path - os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path)) + # Check to see if we are executig a CQGI compliant script + if ("show_object(" in scriptText and "# show_object(" not in scriptText and "#show_boject(" not in scriptText) or ("debug(" in scriptText and "# debug(" not in scriptText and "#debug(" not in scriptText): + FreeCAD.Console.PrintMessage("Executing CQGI-compliant script.\r\n") - # We import this way because using execfile() causes non-standard script execution in some situations - imp.load_source('temp_module', tempFile.name) + # A repreentation of the CQ script with all the metadata attached + cqModel = cqgi.parse(scriptText) + + # Allows us to present parameters to users later that they can alter + parameters = cqModel.metadata.parameters + build_parameters = {} + + # Collect the build parameters from the Parameters Editor view, if they exist + mw = FreeCADGui.getMainWindow() + + # Tracks whether or not we have already added the variables editor + isPresent = False + + # If the widget is open, we need to close it + dockWidgets = mw.findChildren(QtGui.QDockWidget) + for widget in dockWidgets: + if widget.objectName() == "cqVarsEditor": + # Toggle the visibility of the widget + if not widget.visibleRegion().isEmpty(): + # Find all of the controls that will have parameter values in them + valueControls = mw.findChildren(QtGui.QLineEdit) + for valueControl in valueControls: + objectName = valueControl.objectName() + + # We only want text fields that will have parameter values in them + if objectName != None and objectName != '' and objectName.find('pcontrol_') >= 0: + # Associate the value in the text field with the variable name in the script + build_parameters[objectName.replace('pcontrol_', '')] = valueControl.text() + + build_result = cqModel.build(build_parameters=build_parameters) + + # Make sure that the build was successful + if build_result.success: + # Display all the results that the user requested + for result in build_result.results: + # Apply options to the show function if any were provided + if result.options and result.options["rgba"]: + show(result.shape, result.options["rgba"]) + else: + show(result.shape) + + for debugObj in build_result.debugObjects: + # Mark this as a debug object + debugObj.shape.val().label = "Debug" + str(random()) + + # Apply options to the show function if any were provided + if debugObj.options and debugObj.options["rgba"]: + show(debugObj.shape, debugObj.options["rgba"]) + else: + show(debugObj.shape, (255, 0, 0, 0.80)) + else: + FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n") + else: + # Save our code to a tempfile and render it + tempFile = tempfile.NamedTemporaryFile(delete=False) + tempFile.write(scriptText) + tempFile.close() + + # Set some environment variables that may help the user + os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.file.path + os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path)) + + # We import this way because using execfile() causes non-standard script execution in some situations + imp.load_source('temp_module', tempFile.name) msg = QtGui.QApplication.translate( "cqCodeWidget", "Executed ", - None, - QtGui.QApplication.UnicodeUTF8) + None) FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n") @@ -182,7 +247,7 @@ class CadQueryOpenScript: if self.previousPath is None: # Start off defaulting to the Examples directory module_base_path = module_locator.module_path() - exs_dir_path = os.path.join(module_base_path, 'Examples') + exs_dir_path = os.path.join(module_base_path, 'Libs/cadquery/examples/FreeCAD') self.previousPath = exs_dir_path @@ -223,7 +288,7 @@ class CadQuerySaveScript: # If the code pane doesn't have a filename, we need to present the save as dialog if len(cqCodePane.file.path) == 0 or os.path.basename(cqCodePane.file.path) == 'script_template.py' \ - or os.path.split(cqCodePane.file.path)[-2].endswith('Examples'): + or os.path.split(cqCodePane.file.path)[0].endswith('FreeCAD'): FreeCAD.Console.PrintError("You cannot save over a blank file, example file or template file.\r\n") CadQuerySaveAsScript().Activated() @@ -284,3 +349,82 @@ class CadQuerySaveAsScript: # Save the file before closing the original and the re-rendering the new one ExportCQ.save(filename[0]) CadQueryExecuteScript().Activated() + + +class ToggleParametersEditor: + """If the user is running a CQGI-compliant script, they can edit variables through this edistor""" + + def GetResources(self): + return {"MenuText": "Toggle Parameters Editor", + "Accel": "Shift+Alt+E", + "ToolTip": "Opens a live variables editor editor", + "Pixmap": ":/icons/edit-edit.svg"} + + def IsActive(self): + return True + + def Activated(self): + mw = FreeCADGui.getMainWindow() + + # Tracks whether or not we have already added the variables editor + isPresent = False + + # If the widget is open, we need to close it + dockWidgets = mw.findChildren(QtGui.QDockWidget) + for widget in dockWidgets: + if widget.objectName() == "cqVarsEditor": + # Toggle the visibility of the widget + if widget.visibleRegion().isEmpty(): + widget.setVisible(True) + else: + widget.setVisible(False) + + isPresent = True + + if not isPresent: + cqVariablesEditor = QtGui.QDockWidget("CadQuery Variables Editor") + cqVariablesEditor.setObjectName("cqVarsEditor") + + mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cqVariablesEditor) + + # Go ahead and populate the view if there are variables in the script + CadQueryValidateScript().Activated() + + +class CadQueryValidateScript: + """Checks the script for the user without executing it and populates the variable editor, if needed""" + + def GetResources(self): + return {"MenuText": "Validate Script", + "Accel": "F4", + "ToolTip": "Validates a CadQuery script", + "Pixmap": ":/icons/edit_OK.svg"} + + def IsActive(self): + return True + + def Activated(self): + # Grab our code editor so we can interact with it + cqCodePane = Shared.getActiveCodePane() + + # If there is no script to check, ignore this command + if cqCodePane is None: + FreeCAD.Console.PrintMessage("There is no script to validate.") + return + + # Clear the old render before re-rendering + Shared.clearActiveDocument() + + scriptText = cqCodePane.toPlainText().encode('utf-8') + + if ("show_object(" not in scriptText and "# show_object(" in scriptText and "#show_boject(" in scriptText) or ("debug(" not in scriptText and "# debug(" in scriptText and "#debug(" in scriptText): + FreeCAD.Console.PrintError("Script did not call show_object or debug, no output available. Script must be CQGI compliant to get build output, variable editing and validation.\r\n") + return + + # A repreentation of the CQ script with all the metadata attached + cqModel = cqgi.parse(scriptText) + + # Allows us to present parameters to users later that they can alter + parameters = cqModel.metadata.parameters + + Shared.populateParameterEditor(parameters) \ No newline at end of file diff --git a/Gui/ExportCQ.py b/Gui/ExportCQ.py index cba98f8..ca73d16 100644 --- a/Gui/ExportCQ.py +++ b/Gui/ExportCQ.py @@ -26,6 +26,5 @@ def save(filename=None): msg = QtGui.QApplication.translate( "cqCodeWidget", "Saved ", - None, - QtGui.QApplication.UnicodeUTF8) + None) FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n") diff --git a/Gui/ImportCQ.py b/Gui/ImportCQ.py index 303f0f3..bddb855 100644 --- a/Gui/ImportCQ.py +++ b/Gui/ImportCQ.py @@ -36,8 +36,7 @@ def open(filename): msg = QtGui.QApplication.translate( "cqCodeWidget", "Please install Python 2.7", - None, - QtGui.QApplication.UnicodeUTF8) + None) FreeCAD.Console.PrintError(msg + "\r\n") # The extra version numbers won't work on Windows @@ -98,8 +97,7 @@ def open(filename): msg = QtGui.QApplication.translate( "cqCodeWidget", "Opened ", - None, - QtGui.QApplication.UnicodeUTF8) + None) FreeCAD.Console.PrintMessage(msg + filename + "\r\n") return diff --git a/Init.py b/Init.py index bb2a5f8..120b0d7 100644 --- a/Init.py +++ b/Init.py @@ -14,7 +14,7 @@ libs_dir_path = os.path.join(module_base_path, 'Libs') sys.path.insert(0, libs_dir_path) # Tack on our CadQuery library git subtree -cq_lib_path = os.path.join(libs_dir_path, 'cadquery-lib') +cq_lib_path = os.path.join(libs_dir_path, 'cadquery') sys.path.insert(1, cq_lib_path) # Make sure we get the right libs under the FreeCAD installation diff --git a/InitGui.py b/InitGui.py index 87d012c..5f8468e 100644 --- a/InitGui.py +++ b/InitGui.py @@ -34,7 +34,7 @@ class CadQueryWorkbench (Workbench): self.appendMenu('CadQuery', ['CadQueryNewScript', 'CadQueryOpenScript', 'CadQuerySaveScript', 'CadQuerySaveAsScript', 'CadQueryCloseScript']) self.appendMenu(['CadQuery', 'Examples'], submenu) - self.appendMenu('CadQuery', ['Separator', 'CadQueryExecuteScript', 'CadQueryClearOutput']) + self.appendMenu('CadQuery', ['Separator', 'CadQueryExecuteScript', 'CadQueryValidateScript', 'ToggleVariablesEditor', 'CadQueryClearOutput']) def Activated(self): import os @@ -57,8 +57,7 @@ class CadQueryWorkbench (Workbench): "Author: David Cowden\r\n" "License: Apache-2.0\r\n" "Website: https://github.com/dcowden/cadquery\r\n", - None, - QtGui.QApplication.UnicodeUTF8) + None) FreeCAD.Console.PrintMessage(msg) #Getting the main window will allow us to start setting things up the way we want @@ -100,7 +99,7 @@ class CadQueryWorkbench (Workbench): # List all of the example files in an order that makes sense module_base_path = module_locator.module_path() - exs_dir_path = os.path.join(module_base_path, 'Examples') + exs_dir_path = os.path.join(module_base_path, 'Libs/cadquery/examples/FreeCAD') dirs = os.listdir(exs_dir_path) dirs.sort() @@ -111,7 +110,9 @@ FreeCADGui.addCommand('CadQueryOpenScript', CadQueryOpenScript()) FreeCADGui.addCommand('CadQuerySaveScript', CadQuerySaveScript()) FreeCADGui.addCommand('CadQuerySaveAsScript', CadQuerySaveAsScript()) FreeCADGui.addCommand('CadQueryExecuteScript', CadQueryExecuteScript()) +FreeCADGui.addCommand('CadQueryValidateScript', CadQueryValidateScript()) FreeCADGui.addCommand('CadQueryCloseScript', CadQueryCloseScript()) +FreeCADGui.addCommand('ToggleVariablesEditor', ToggleParametersEditor()) FreeCADGui.addCommand('CadQueryClearOutput', CadQueryClearOutput()) # Step through and add an Examples submenu item for each example diff --git a/Libs/cadquery b/Libs/cadquery new file mode 160000 index 0000000..d1fb644 --- /dev/null +++ b/Libs/cadquery @@ -0,0 +1 @@ +Subproject commit d1fb644aa45705c91067a74d3d37845dbc0faef9 diff --git a/Libs/cadquery-lib/.coverage b/Libs/cadquery-lib/.coverage deleted file mode 100644 index 09e0f75..0000000 --- a/Libs/cadquery-lib/.coverage +++ /dev/null @@ -1 +0,0 @@ -!coverage.py: This is a private format, don't read it directly!{"lines": {"/home/jwright/Downloads/cadquery/cadquery/cq_directive.py": [], "/home/jwright/Downloads/cadquery/cadquery/cq.py": [2049, 2052, 2053, 2054, 2056, 2057, 2058, 2060, 18, 20, 21, 22, 23, 24, 27, 2076, 2078, 33, 34, 35, 36, 2085, 2086, 39, 40, 2089, 43, 2093, 49, 51, 2102, 2103, 2104, 58, 59, 60, 2109, 62, 2111, 65, 2126, 2127, 2128, 81, 2130, 2131, 84, 2133, 2134, 2140, 2141, 2142, 2143, 96, 2145, 2147, 2149, 102, 2151, 104, 106, 107, 108, 110, 112, 2166, 2168, 2170, 2171, 2172, 2173, 2174, 2178, 363, 2180, 133, 2182, 2183, 136, 2185, 138, 2187, 140, 141, 2255, 143, 145, 149, 150, 151, 153, 154, 156, 2207, 368, 2211, 2213, 2215, 2217, 2218, 2220, 174, 175, 176, 178, 182, 184, 185, 2235, 188, 189, 190, 2239, 192, 193, 195, 374, 2246, 2247, 2249, 2251, 2252, 205, 2254, 207, 2257, 211, 213, 222, 224, 2427, 2276, 2277, 2279, 2282, 2087, 238, 239, 240, 2088, 243, 244, 246, 383, 253, 255, 2307, 2308, 2309, 2310, 2433, 2312, 265, 2314, 2316, 2318, 2333, 2336, 2339, 2340, 2341, 2342, 2344, 2346, 306, 2075, 308, 309, 310, 311, 2361, 314, 2363, 2364, 2366, 2368, 322, 329, 330, 332, 333, 335, 337, 341, 344, 345, 349, 350, 353, 355, 356, 357, 360, 361, 2411, 364, 365, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2422, 375, 2424, 378, 379, 2428, 382, 2431, 384, 385, 2434, 388, 390, 396, 398, 404, 406, 411, 413, 2471, 2472, 2474, 427, 428, 432, 2482, 2483, 2485, 2486, 2488, 2489, 2491, 2494, 2497, 2498, 2500, 454, 455, 456, 457, 458, 461, 462, 464, 466, 78, 79, 2524, 479, 80, 482, 483, 485, 486, 488, 490, 1447, 82, 2132, 519, 521, 2480, 551, 553, 582, 97, 584, 605, 607, 103, 839, 631, 633, 651, 653, 669, 671, 2502, 681, 683, 692, 694, 720, 722, 723, 724, 725, 727, 729, 2070, 742, 743, 745, 758, 2071, 766, 769, 131, 2072, 2523, 805, 807, 808, 811, 812, 813, 815, 137, 2527, 836, 838, 481, 842, 843, 844, 846, 369, 874, 876, 877, 880, 882, 883, 886, 910, 912, 914, 936, 937, 938, 939, 943, 947, 948, 949, 951, 952, 953, 955, 968, 969, 971, 972, 974, 975, 976, 977, 979, 981, 994, 995, 996, 997, 998, 999, 1001, 1022, 1024, 1025, 1026, 1027, 1031, 1032, 172, 1034, 1036, 1050, 1053, 1054, 1055, 1056, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1067, 1069, 1089, 1090, 1091, 1092, 1094, 1096, 1123, 1124, 1125, 1127, 2236, 2237, 1137, 1139, 1141, 1143, 1144, 1146, 1149, 2241, 1160, 1161, 1163, 1170, 1172, 1179, 1181, 1191, 1192, 1194, 1204, 1205, 1208, 2359, 1223, 1224, 1227, 2253, 1242, 1243, 1244, 1246, 2259, 1278, 1279, 1281, 1282, 1284, 1286, 1287, 1289, 1291, 1307, 1308, 1309, 1311, 1313, 1314, 1316, 1318, 1338, 1341, 1343, 1345, 1346, 1347, 1350, 1352, 1354, 2091, 1372, 1373, 1374, 1376, 1390, 1391, 1392, 1394, 1401, 1403, 1404, 1406, 1421, 1423, 1433, 1434, 1435, 1439, 1446, 241, 1448, 1449, 1451, 1472, 1475, 1476, 1478, 1480, 1481, 1482, 1486, 1487, 1488, 1490, 1492, 1524, 1525, 1527, 1529, 1530, 1532, 1534, 1535, 1536, 1538, 1540, 1542, 1560, 1561, 1564, 1567, 1568, 1570, 1572, 263, 2313, 1598, 1601, 1602, 1603, 1604, 1605, 1607, 1608, 1609, 1610, 1612, 1613, 1616, 1619, 1648, 1649, 1650, 1651, 1653, 1655, 1666, 1668, 1669, 1670, 1671, 1672, 1673, 1675, 1677, 1692, 1695, 1698, 1699, 1701, 1704, 1706, 1707, 1709, 1711, 1725, 1728, 1730, 1732, 1741, 1742, 1743, 1745, 1747, 1757, 1758, 1762, 1763, 1764, 1765, 1767, 1769, 1770, 1773, 1803, 1804, 1806, 1812, 1814, 1817, 1818, 1819, 1821, 1825, 2107, 2356, 2357, 1856, 1857, 1859, 1862, 1865, 1866, 1867, 1868, 1869, 1870, 1872, 1876, 2362, 63, 1902, 1903, 1905, 1911, 1913, 1914, 1916, 1919, 320, 1940, 1942, 1945, 1954, 1955, 1956, 1957, 1958, 1959, 1963, 1964, 1966, 1967, 1968, 1970, 1995, 1997, 1998, 2000, 2001, 2002, 2004, 2027, 2030, 2034, 2035, 2037, 2041, 2044, 2045, 2047], "/home/jwright/Downloads/cadquery/cadquery/freecad_impl/__init__.py": [18, 19, 22, 24, 25, 29, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 101, 102, 103, 104, 105, 106, 107, 108, 109], "/home/jwright/Downloads/cadquery/cadquery/freecad_impl/shapes.py": [1024, 514, 1027, 517, 519, 428, 523, 547, 526, 528, 88, 857, 537, 539, 90, 717, 603, 549, 550, 945, 552, 605, 49, 50, 51, 52, 565, 55, 568, 569, 571, 572, 61, 693, 352, 68, 69, 582, 71, 584, 74, 587, 588, 590, 79, 592, 580, 82, 83, 84, 85, 87, 600, 89, 602, 91, 604, 93, 94, 95, 96, 609, 98, 699, 104, 105, 618, 619, 621, 110, 623, 624, 113, 114, 627, 116, 617, 72, 636, 819, 640, 643, 134, 961, 567, 862, 651, 654, 655, 659, 662, 664, 669, 160, 673, 795, 677, 909, 682, 455, 172, 173, 175, 807, 178, 181, 694, 184, 628, 187, 188, 701, 702, 191, 799, 708, 710, 711, 204, 825, 206, 719, 720, 209, 210, 211, 212, 213, 729, 219, 794, 806, 208, 741, 742, 977, 233, 561, 809, 750, 752, 59, 243, 244, 245, 189, 247, 680, 249, 762, 931, 255, 256, 769, 258, 260, 897, 812, 898, 813, 276, 279, 280, 793, 282, 283, 796, 285, 286, 901, 288, 289, 802, 291, 292, 294, 295, 808, 297, 298, 300, 301, 303, 816, 904, 306, 307, 309, 822, 823, 564, 991, 317, 318, 821, 320, 321, 323, 324, 325, 327, 329, 330, 761, 332, 333, 335, 1017, 340, 343, 856, 241, 859, 860, 349, 350, 351, 864, 353, 500, 355, 486, 97, 487, 483, 368, 369, 370, 372, 373, 376, 890, 379, 892, 381, 800, 895, 385, 386, 387, 388, 389, 906, 392, 818, 394, 395, 908, 397, 401, 404, 921, 407, 920, 409, 855, 413, 926, 928, 240, 930, 419, 420, 933, 753, 424, 426, 427, 940, 429, 942, 925, 944, 433, 947, 949, 951, 952, 441, 954, 801, 444, 562, 672, 962, 331, 964, 803, 417, 456, 457, 459, 972, 418, 974, 975, 465, 466, 979, 468, 469, 471, 472, 475, 817, 442, 992, 995, 485, 998, 81, 1000, 489, 1004, 594, 1007, 1009, 499, 595, 1012, 501, 503, 596, 1018, 1019, 767, 1021, 511], "/home/jwright/Downloads/cadquery/cadquery/__init__.py": [2, 3, 4, 5, 10, 11, 15, 16, 17, 18, 21], "/home/jwright/Downloads/cadquery/cadquery/selectors.py": [18, 20, 21, 22, 25, 30, 31, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 71, 72, 73, 74, 76, 77, 83, 85, 98, 99, 100, 101, 102, 104, 106, 107, 108, 110, 113, 114, 115, 117, 118, 119, 120, 121, 122, 124, 125, 127, 129, 133, 134, 135, 136, 138, 142, 148, 149, 152, 154, 156, 157, 158, 160, 161, 162, 164, 166, 184, 186, 187, 189, 207, 209, 210, 212, 230, 232, 233, 234, 235, 238, 257, 258, 259, 261, 262, 263, 264, 265, 266, 268, 293, 294, 295, 296, 297, 298, 299, 301, 302, 310, 311, 313, 316, 318, 322, 323, 324, 325, 327, 328, 329, 331, 334, 337, 338, 340, 342, 345, 346, 348, 350, 354, 355, 356, 358, 362, 363, 364, 366, 368, 370, 405, 406, 408, 409, 410, 411, 412, 413, 414, 417, 418, 419, 420, 421, 422, 423, 425, 426, 427, 429, 430, 431, 432, 434, 439, 442, 443, 447, 448, 452, 454, 455, 457, 458, 459, 460, 461, 462, 463, 464, 465, 469, 474], "/home/jwright/Downloads/cadquery/cadquery/cqgi.py": [4, 5, 6, 7, 8, 10, 12, 23, 24, 27, 36, 38, 43, 44, 45, 46, 51, 53, 64, 66, 67, 68, 70, 71, 72, 74, 83, 95, 96, 98, 99, 101, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 122, 124, 125, 126, 128, 129, 131, 132, 133, 135, 136, 139, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159, 160, 162, 163, 165, 166, 167, 168, 171, 175, 176, 177, 179, 180, 182, 183, 184, 185, 188, 189, 192, 193, 196, 197, 200, 201, 204, 214, 215, 218, 221, 224, 227, 230, 232, 234, 235, 237, 238, 240, 241, 242, 243, 244, 245, 246, 247, 249, 251, 256, 257, 258, 259, 260, 261, 262, 263, 265, 266, 267, 268, 271, 275, 280, 285, 286, 287, 288, 290, 295, 297, 301, 303, 309, 315, 316, 318, 323, 324, 325, 326, 328, 332, 333, 336, 340, 341, 344, 349, 351, 362, 365, 368, 372, 377, 378, 379, 381, 382, 384, 385, 386, 388, 389, 390, 391, 393, 394, 395, 397, 398, 400, 403, 404, 405, 407, 411, 412, 416, 417, 418, 420, 421, 422, 423, 425, 428, 430, 431, 433, 434, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 453, 455, 456, 459, 462, 463, 464, 466, 467, 472], "/home/jwright/Downloads/cadquery/cadquery/freecad_impl/importers.py": [2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 15, 16, 17, 20, 28, 29, 33, 39, 41, 44, 45, 46, 48, 53], "/home/jwright/Downloads/cadquery/cadquery/freecad_impl/exporters.py": [1, 3, 4, 6, 9, 10, 15, 16, 17, 18, 19, 20, 23, 24, 25, 28, 34, 46, 47, 49, 51, 53, 55, 56, 59, 60, 61, 62, 63, 64, 65, 66, 71, 74, 76, 77, 78, 79, 83, 84, 86, 91, 92, 93, 95, 96, 99, 103, 105, 107, 108, 111, 115, 116, 118, 121, 122, 124, 125, 127, 128, 130, 131, 132, 133, 136, 137, 138, 139, 140, 141, 142, 143, 144, 147, 148, 149, 150, 151, 152, 153, 154, 157, 164, 165, 167, 168, 169, 170, 172, 173, 174, 177, 179, 180, 186, 187, 188, 189, 190, 191, 195, 210, 211, 212, 214, 215, 216, 217, 218, 220, 221, 223, 225, 226, 227, 232, 237, 239, 243, 245, 246, 247, 248, 251, 252, 254, 257, 258, 259, 260, 263, 266, 269, 270, 271, 273, 274, 275, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 294, 297, 304, 305, 306, 307, 353, 389, 391], "/home/jwright/Downloads/cadquery/cadquery/freecad_impl/geom.py": [515, 516, 517, 522, 523, 524, 529, 18, 20, 21, 22, 23, 26, 540, 542, 544, 546, 547, 548, 550, 632, 42, 44, 45, 46, 47, 560, 49, 50, 563, 564, 565, 567, 568, 569, 58, 572, 573, 575, 581, 70, 583, 72, 73, 74, 75, 76, 77, 78, 79, 592, 593, 594, 595, 597, 87, 89, 91, 93, 95, 608, 97, 99, 101, 614, 103, 616, 105, 618, 107, 109, 110, 113, 114, 116, 117, 630, 119, 120, 633, 122, 123, 125, 638, 127, 128, 130, 635, 132, 645, 134, 136, 144, 146, 147, 149, 152, 155, 158, 161, 162, 164, 167, 170, 173, 174, 177, 181, 182, 183, 184, 188, 189, 191, 192, 195, 586, 631, 206, 208, 209, 463, 634, 570, 238, 637, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 254, 255, 260, 261, 262, 263, 264, 266, 267, 268, 269, 270, 272, 273, 643, 278, 279, 280, 281, 282, 284, 285, 133, 48, 290, 291, 296, 297, 302, 303, 51, 308, 309, 52, 314, 315, 590, 629, 53, 320, 321, 326, 327, 55, 332, 345, 346, 348, 349, 350, 352, 354, 356, 358, 360, 362, 364, 365, 367, 609, 389, 391, 495, 69, 418, 419, 582, 423, 424, 71, 428, 430, 584, 611, 585, 445, 446, 587, 454, 588, 461, 462, 589, 464, 466, 467, 469, 591, 483, 485, 488, 489, 490, 491, 494, 613, 497, 499], "/home/jwright/Downloads/cadquery/cadquery/plugins/__init__.py": [18], "/home/jwright/Downloads/cadquery/cadquery/contrib/__init__.py": []}} \ No newline at end of file diff --git a/Libs/cadquery-lib/.gitignore b/Libs/cadquery-lib/.gitignore deleted file mode 100644 index e7df8cf..0000000 --- a/Libs/cadquery-lib/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -build/ -*.pyc -doc/_build/* -dist/* -.idea/* -cadquery.egg-info -target/* diff --git a/Libs/cadquery-lib/.travis.yml b/Libs/cadquery-lib/.travis.yml deleted file mode 100644 index 3537f48..0000000 --- a/Libs/cadquery-lib/.travis.yml +++ /dev/null @@ -1,31 +0,0 @@ -language: python -before_install: -- sudo add-apt-repository -y ppa:freecad-maintainers/freecad-stable -- sudo apt-get update -qq -install: -- sudo apt-get install -y freecad freecad-doc -- gcc --version -- g++ --version -- python ./setup.py install -- pip install coverage -- pip install coveralls -- pip install Sphinx==1.3.2 -- pip install travis-sphinx -- pip install pyparsing -script: -- coverage run --source=cadquery ./runtests.py -- travis-sphinx --nowarn --source=doc build -after_success: -- coveralls -- travis-sphinx deploy -branches: - except: - - pythonocc - - 2_0_branch -deploy: - provider: pypi - user: dcowden - password: - secure: aP02wBbry1j3hYG/w++siF1lk26teuRQlPAx1c+ec8fxUw+bECa2HbPQHcIvSXB5N6nc6P3L9LjHt9ktm+Dn6FLJu3qWYNGAZx9PTn24ug0iAmB+JyNrsET3nK6WUKR1XpBqvjKgdpukd1Hknh2FSzYoyUvFWH9/CovITCFN3jo= - on: - tags: true \ No newline at end of file diff --git a/Libs/cadquery-lib/AUTHORS.md b/Libs/cadquery-lib/AUTHORS.md deleted file mode 100644 index 31b30e8..0000000 --- a/Libs/cadquery-lib/AUTHORS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Core CQ Developers - -* [Dave Cowden](https://github.com/dcowden), Creator - Lead Developer -* [Jeremy Wright](https://github.com/jmwright) (a.k.a [innovationstech](https://github.com/innovationstech)) diff --git a/Libs/cadquery-lib/LICENSE b/Libs/cadquery-lib/LICENSE deleted file mode 100644 index d4fa4f1..0000000 --- a/Libs/cadquery-lib/LICENSE +++ /dev/null @@ -1,208 +0,0 @@ -CadQuery -Copyright (C) 2015 Parametric Products Intellectual Holdings, LLC - -This library is free software; you can redistribute it and/or -modify it under the terms of the Apache Public License, v 2.0 - - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [Parametric Products Intellectual Holdings, LLC] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/Libs/cadquery-lib/MANIFEST b/Libs/cadquery-lib/MANIFEST deleted file mode 100644 index ce5c215..0000000 --- a/Libs/cadquery-lib/MANIFEST +++ /dev/null @@ -1,24 +0,0 @@ -README.txt -README.md -setup.cfg -setup.py -cadquery\cq.py -cadquery\__init__.py -cadquery\cq_directive.py -cadquery\selectors.py -cadquery\cqgi.py -cadquery\contrib\__init__.py -cadquery\freecad_impl\__init__.py -cadquery\freecad_impl\exporters.py -cadquery\freecad_impl\importers.py -cadquery\freecad_impl\geom.py -cadquery\freecad_impl\shapes.py -cadquery\plugins\__init__.py -tests\TestCQSelectors.py -tests\TestCadObjects.py -tests\TestCadQuery.py -tests\TestExporters.py -tests\TestImporters.py -tests\TestWorkplanes.py -tests\TestCQGI.py -tests\__init__.py diff --git a/Libs/cadquery-lib/MANIFEST.in b/Libs/cadquery-lib/MANIFEST.in deleted file mode 100644 index bb3ec5f..0000000 --- a/Libs/cadquery-lib/MANIFEST.in +++ /dev/null @@ -1 +0,0 @@ -include README.md diff --git a/Libs/cadquery-lib/README.md b/Libs/cadquery-lib/README.md deleted file mode 100644 index 60fc9d4..0000000 --- a/Libs/cadquery-lib/README.md +++ /dev/null @@ -1,235 +0,0 @@ -What is a CadQuery? -======================================== - -[![Travis Build Status](https://travis-ci.org/dcowden/cadquery.svg?branch=master)](https://travis-ci.org/dcowden/cadquery?branch=master) -[![Coverage Status](https://coveralls.io/repos/dcowden/cadquery/badge.svg)](https://coveralls.io/r/dcowden/cadquery) -[![GitHub version](https://badge.fury.io/gh/dcowden%2Fcadquery.svg)](https://github.com/dcowden/cadquery/releases/tag/v0.3.0) -[![License](https://img.shields.io/badge/license-Apache2-blue.svg)](https://github.com/dcowden/cadquery/blob/master/LICENSE) - -CadQuery is an intuitive, easy-to-use python based language for building parametric 3D CAD models. CadQuery is for 3D CAD what jQuery is for javascript. Imagine selecting Faces of a 3d object the same way you select DOM objects with JQuery! - -CadQuery has several goals: - -* Build models with scripts that are as close as possible to how you'd describe the object to a human. -* Create parametric models that can be very easily customized by end users -* Output high quality CAD formats like STEP and AMF in addition to traditional STL -* Provide a non-proprietary, plain text model format that can be edited and executed with only a web browser - -Using CadQuery, you can write short, simple scripts that produce high quality CAD models. It is easy to make many different objects using a single script that can be customized. - -Full Documentation -============================ -You can find the full cadquery documentation at http://dcowden.github.io/cadquery - - -Getting Started With CadQuery -======================================== - -The easiest way to get started with CadQuery is to Install FreeCAD (version 14+) (http://www.freecadweb.org/), and then to use our great CadQuery-FreeCAD plugin here: https://github.com/jmwright/cadquery-freecad-module - - -It includes the latest version of cadquery alreadby bundled, and has super-easy installation on Mac, Windows, and Unix. - -It has tons of awesome features like integration with FreeCAD so you can see your objects, code-autocompletion, an examples bundle, and script saving/loading. Its definitely the best way to kick the tires! - -We also have a Google Group to make it easy to get help from other CadQuery users. Please join the group and introduce yourself, and we would also love to hear what you are doing with CadQuery. https://groups.google.com/forum/#!forum/cadquery - -Examples -====================== - -This resin mold was modeled using cadquery and then created on a CNC machine: - -

- - -

- -The cadquery script is surprisingly short, and allows easily customizing any of the variables:: - -```python - import cadquery as cq - from Helpers import show - BS = cq.selectors.BoxSelector - - # PARAMETERS - mount_holes = True - - # mold size - mw = 40 - mh = 13 - ml = 120 - - # wire and fix size - wd = 6 # wire diameter - rt = 7 # resin thickness - rl = 50 # resin length - rwpl = 10 # resin to wire pass length - - # pocket fillet - pf = 18 - - # mount holes - mhd = 7 # hole diameter - mht = 3 # hole distance from edge - - # filling hole - fhd = 6 - - # DRAWING - - # draw base - base = cq.Workplane("XY").box(ml, mw, mh, (True, True, False)) - - # draw wire - pocket = cq.Workplane("XY", (0, 0, mh)).moveTo(-ml/2., 0).line(0, wd/2.)\ - .line((ml-rl)/2.-rwpl, 0).line(rwpl, rt).line(rl, 0)\ - .line(rwpl, -rt).line((ml-rl)/2.-rwpl, 0)\ - .line(0, -(wd/2.)).close().revolve(axisEnd=(1, 0))\ - .edges(BS((-rl/2.-rwpl-.1, -100, -100), (rl/2.+rwpl+.1, 100, 100)))\ - .fillet(pf) - - r = base.cut(pocket) - - # mount holes - if mount_holes: - px = ml/2.-mht-mhd/2. - py = mw/2.-mht-mhd/2 - r = r.faces("`_ ), a popular framework that -revolutionized web development involving javascript. - -If you are familiar with how jQuery, you will probably recognize several jQuery features that CadQuery uses: - -* A fluent api to create clean, easy to read code -* Language features that make selection and iteration incredibly easy -* -* Ability to use the library along side other python libraries -* Clear and complete documentation, with plenty of samples. - diff --git a/Libs/cadquery-lib/build-docs.sh b/Libs/cadquery-lib/build-docs.sh deleted file mode 100755 index bef2f78..0000000 --- a/Libs/cadquery-lib/build-docs.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -sphinx-build -b html doc target/docs \ No newline at end of file diff --git a/Libs/cadquery-lib/cadquery/README.txt b/Libs/cadquery-lib/cadquery/README.txt deleted file mode 100644 index ab8dc7e..0000000 --- a/Libs/cadquery-lib/cadquery/README.txt +++ /dev/null @@ -1,8 +0,0 @@ -*** -Core CadQuery implementation. - -No files should depend on or import FreeCAD , pythonOCC, or other CAD Kernel libraries!!! -Dependencies should be on the classes provided by implementation packages, which in turn -can depend on CAD libraries. - -*** \ No newline at end of file diff --git a/Libs/cadquery-lib/cadquery/__init__.py b/Libs/cadquery-lib/cadquery/__init__.py deleted file mode 100644 index a9b77e4..0000000 --- a/Libs/cadquery-lib/cadquery/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -#these items point to the freecad implementation -from .freecad_impl.geom import Plane,BoundBox,Vector,Matrix,sortWiresByBuildOrder -from .freecad_impl.shapes import Shape,Vertex,Edge,Face,Wire,Solid,Shell,Compound -from .freecad_impl import exporters -from .freecad_impl import importers - -#these items are the common implementation - -#the order of these matter -from .selectors import * -from .cq import * - - -__all__ = [ - 'CQ','Workplane','plugins','selectors','Plane','BoundBox','Matrix','Vector','sortWiresByBuildOrder', - 'Shape','Vertex','Edge','Wire','Face','Solid','Shell','Compound','exporters', 'importers', - 'NearestToPointSelector','ParallelDirSelector','DirectionSelector','PerpendicularDirSelector', - 'TypeSelector','DirectionMinMaxSelector','StringSyntaxSelector','Selector','plugins' -] - -__version__ = "1.0.0" diff --git a/Libs/cadquery-lib/cadquery/contrib/__init__.py b/Libs/cadquery-lib/cadquery/contrib/__init__.py deleted file mode 100644 index 67c7b68..0000000 --- a/Libs/cadquery-lib/cadquery/contrib/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see -""" diff --git a/Libs/cadquery-lib/cadquery/cq.py b/Libs/cadquery-lib/cadquery/cq.py deleted file mode 100644 index b2d3a50..0000000 --- a/Libs/cadquery-lib/cadquery/cq.py +++ /dev/null @@ -1,2527 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see -""" - -import time -import math -from cadquery import * -from cadquery import selectors -from cadquery import exporters - - -class CQContext(object): - """ - A shared context for modeling. - - All objects in the same CQ chain share a reference to this same object instance - which allows for shared state when needed, - """ - def __init__(self): - self.pendingWires = [] # a list of wires that have been created and need to be extruded - self.pendingEdges = [] # a list of created pending edges that need to be joined into wires - # a reference to the first point for a set of edges. - # Used to determine how to behave when close() is called - self.firstPoint = None - self.tolerance = 0.0001 # user specified tolerance - - -class CQ(object): - """ - Provides enhanced functionality for a wrapped CAD primitive. - - Examples include feature selection, feature creation, 2d drawing - using work planes, and 3d operations like fillets, shells, and splitting - """ - - def __init__(self, obj): - """ - Construct a new CadQuery (CQ) object that wraps a CAD primitive. - - :param obj: Object to Wrap. - :type obj: A CAD Primitive ( wire,vertex,face,solid,edge ) - """ - self.objects = [] - self.ctx = CQContext() - self.parent = None - - if obj: # guarded because sometimes None for internal use - self.objects.append(obj) - - def newObject(self, objlist): - """ - Make a new CQ object. - - :param objlist: The stack of objects to use - :type objlist: a list of CAD primitives ( wire,face,edge,solid,vertex,etc ) - - The parent of the new object will be set to the current object, - to preserve the chain correctly. - - Custom plugins and subclasses should use this method to create new CQ objects - correctly. - """ - r = CQ(None) # create a completely blank one - r.parent = self - r.ctx = self.ctx # context solid remains the same - r.objects = list(objlist) - return r - - def _collectProperty(self, propName): - """ - Collects all of the values for propName, - for all items on the stack. - FreeCAD objects do not implement id correctly, - so hashCode is used to ensure we don't add the same - object multiple times. - - One weird use case is that the stack could have a solid reference object - on it. This is meant to be a reference to the most recently modified version - of the context solid, whatever it is. - """ - all = {} - for o in self.objects: - - # tricky-- if an object is a compound of solids, - # do not return all of the solids underneath-- typically - # then we'll keep joining to ourself - if propName == 'Solids' and isinstance(o, Solid) and o.ShapeType() == 'Compound': - for i in getattr(o, 'Compounds')(): - all[i.hashCode()] = i - else: - if hasattr(o, propName): - for i in getattr(o, propName)(): - all[i.hashCode()] = i - - return list(all.values()) - - def split(self, keepTop=False, keepBottom=False): - """ - Splits a solid on the stack into two parts, optionally keeping the separate parts. - - :param boolean keepTop: True to keep the top, False or None to discard it - :param boolean keepBottom: True to keep the bottom, False or None to discard it - :raises: ValueError if keepTop and keepBottom are both false. - :raises: ValueError if there is not a solid in the current stack or the parent chain - :returns: CQ object with the desired objects on the stack. - - The most common operation splits a solid and keeps one half. This sample creates - split bushing:: - - #drill a hole in the side - c = Workplane().box(1,1,1).faces(">Z").workplane().circle(0.25).cutThruAll()F - #now cut it in half sideways - c.faces(">Y").workplane(-0.5).split(keepTop=True) - """ - - solid = self.findSolid() - - if (not keepTop) and (not keepBottom): - raise ValueError("You have to keep at least one half") - - maxDim = solid.BoundingBox().DiagonalLength * 10.0 - topCutBox = self.rect(maxDim, maxDim)._extrude(maxDim) - bottomCutBox = self.rect(maxDim, maxDim)._extrude(-maxDim) - - top = solid.cut(bottomCutBox) - bottom = solid.cut(topCutBox) - - if keepTop and keepBottom: - # Put both on the stack, leave original unchanged. - return self.newObject([top, bottom]) - else: - # Put the one we are keeping on the stack, and also update the - # context solidto the one we kept. - if keepTop: - solid.wrapped = top.wrapped - return self.newObject([top]) - else: - solid.wrapped = bottom.wrapped - return self.newObject([bottom]) - - def combineSolids(self, otherCQToCombine=None): - """ - !!!DEPRECATED!!! use union() - Combines all solids on the current stack, and any context object, together - into a single object. - - After the operation, the returned solid is also the context solid. - - :param otherCQToCombine: another CadQuery to combine. - :return: a cQ object with the resulting combined solid on the stack. - - Most of the time, both objects will contain a single solid, which is - combined and returned on the stack of the new object. - """ - #loop through current stack objects, and combine them - #TODO: combine other types of objects as well, like edges and wires - toCombine = self.solids().vals() - - if otherCQToCombine: - for obj in otherCQToCombine.solids().vals(): - toCombine.append(obj) - - if len(toCombine) < 1: - raise ValueError("Cannot Combine: at least one solid required!") - - #get context solid and we don't want to find our own objects - ctxSolid = self.findSolid(searchStack=False, searchParents=True) - - if ctxSolid is None: - ctxSolid = toCombine.pop(0) - - #now combine them all. make sure to save a reference to the ctxSolid pointer! - s = ctxSolid - for tc in toCombine: - s = s.fuse(tc) - - ctxSolid.wrapped = s.wrapped - return self.newObject([s]) - - def all(self): - """ - Return a list of all CQ objects on the stack. - - useful when you need to operate on the elements - individually. - - Contrast with vals, which returns the underlying - objects for all of the items on the stack - """ - return [self.newObject([o]) for o in self.objects] - - def size(self): - """ - Return the number of objects currently on the stack - """ - return len(self.objects) - - def vals(self): - """ - get the values in the current list - - :rtype: list of FreeCAD objects - :returns: the values of the objects on the stack. - - Contrast with :py:meth:`all`, which returns CQ objects for all of the items on the stack - """ - return self.objects - - def add(self, obj): - """ - Adds an object or a list of objects to the stack - - :param obj: an object to add - :type obj: a CQ object, CAD primitive, or list of CAD primitives - :return: a CQ object with the requested operation performed - - If an CQ object, the values of that object's stack are added. If a list of cad primitives, - they are all added. If a single CAD primitive it is added - - Used in rare cases when you need to combine the results of several CQ results - into a single CQ object. Shelling is one common example - """ - if type(obj) == list: - self.objects.extend(obj) - elif type(obj) == CQ or type(obj) == Workplane: - self.objects.extend(obj.objects) - else: - self.objects.append(obj) - return self - - def val(self): - """ - Return the first value on the stack - - :return: the first value on the stack. - :rtype: A FreeCAD object or a SolidReference - """ - return self.objects[0] - - def toFreecad(self): - """ - Directly returns the wrapped FreeCAD object to cut down on the amount of boiler plate code - needed when rendering a model in FreeCAD's 3D view. - :return: The wrapped FreeCAD object - :rtype A FreeCAD object or a SolidReference - """ - - return self.objects[0].wrapped - - def workplane(self, offset=0.0, invert=False, centerOption='CenterOfMass'): - """ - Creates a new 2-D workplane, located relative to the first face on the stack. - - :param offset: offset for the work plane in the Z direction. Default - :param invert: invert the Z direction from that of the face. - :type offset: float or None=0.0 - :type invert: boolean or None=False - :rtype: Workplane object ( which is a subclass of CQ ) - - The first element on the stack must be a face, a set of - co-planar faces or a vertex. If a vertex, then the parent - item on the chain immediately before the vertex must be a - face. - - The result will be a 2-d working plane - with a new coordinate system set up as follows: - - * The origin will be located in the *center* of the - face/faces, if a face/faces was selected. If a vertex was - selected, the origin will be at the vertex, and located - on the face. - * The Z direction will be normal to the plane of the face,computed - at the center point. - * The X direction will be parallel to the x-y plane. If the workplane is parallel to - the global x-y plane, the x direction of the workplane will co-incide with the - global x direction. - - Most commonly, the selected face will be planar, and the workplane lies in the same plane - of the face ( IE, offset=0). Occasionally, it is useful to define a face offset from - an existing surface, and even more rarely to define a workplane based on a face that is - not planar. - - To create a workplane without first having a face, use the Workplane() method. - - Future Enhancements: - * Allow creating workplane from planar wires - * Allow creating workplane based on an arbitrary point on a face, not just the center. - For now you can work around by creating a workplane and then offsetting the center - afterwards. - """ - def _isCoPlanar(f0, f1): - """Test if two faces are on the same plane.""" - p0 = f0.Center() - p1 = f1.Center() - n0 = f0.normalAt() - n1 = f1.normalAt() - - # test normals (direction of planes) - if not ((abs(n0.x-n1.x) < self.ctx.tolerance) or - (abs(n0.y-n1.y) < self.ctx.tolerance) or - (abs(n0.z-n1.z) < self.ctx.tolerance)): - return False - - # test if p1 is on the plane of f0 (offset of planes) - return abs(n0.dot(p0.sub(p1)) < self.ctx.tolerance) - - def _computeXdir(normal): - """ - Figures out the X direction based on the given normal. - :param :normal The direction that's normal to the plane. - :type :normal A Vector - :return A vector representing the X direction. - """ - xd = Vector(0, 0, 1).cross(normal) - if xd.Length < self.ctx.tolerance: - #this face is parallel with the x-y plane, so choose x to be in global coordinates - xd = Vector(1, 0, 0) - return xd - - if len(self.objects) > 1: - # are all objects 'PLANE'? - if not all(o.geomType() == 'PLANE' for o in self.objects): - raise ValueError("If multiple objects selected, they all must be planar faces.") - - # are all faces co-planar with each other? - if not all(_isCoPlanar(self.objects[0], f) for f in self.objects[1:]): - raise ValueError("Selected faces must be co-planar.") - - if centerOption == 'CenterOfMass': - center = Shape.CombinedCenter(self.objects) - elif centerOption == 'CenterOfBoundBox': - center = Shape.CombinedCenterOfBoundBox(self.objects) - - normal = self.objects[0].normalAt() - xDir = _computeXdir(normal) - - else: - obj = self.objects[0] - - if isinstance(obj, Face): - if centerOption == 'CenterOfMass': - center = obj.Center() - elif centerOption == 'CenterOfBoundBox': - center = obj.CenterOfBoundBox() - normal = obj.normalAt(center) - xDir = _computeXdir(normal) - else: - if hasattr(obj, 'Center'): - if centerOption == 'CenterOfMass': - center = obj.Center() - elif centerOption == 'CenterOfBoundBox': - center = obj.CenterOfBoundBox() - normal = self.plane.zDir - xDir = self.plane.xDir - else: - raise ValueError("Needs a face or a vertex or point on a work plane") - - #invert if requested - if invert: - normal = normal.multiply(-1.0) - - #offset origin if desired - offsetVector = normal.normalized().multiply(offset) - offsetCenter = center.add(offsetVector) - - #make the new workplane - plane = Plane(offsetCenter, xDir, normal) - s = Workplane(plane) - s.parent = self - s.ctx = self.ctx - - #a new workplane has the center of the workplane on the stack - return s - - def first(self): - """ - Return the first item on the stack - :returns: the first item on the stack. - :rtype: a CQ object - """ - return self.newObject(self.objects[0:1]) - - def item(self, i): - """ - - Return the ith item on the stack. - :rtype: a CQ object - """ - return self.newObject([self.objects[i]]) - - def last(self): - """ - Return the last item on the stack. - :rtype: a CQ object - """ - return self.newObject([self.objects[-1]]) - - def end(self): - """ - Return the parent of this CQ element - :rtype: a CQ object - :raises: ValueError if there are no more parents in the chain. - - For example:: - - CQ(obj).faces("+Z").vertices().end() - - will return the same as:: - - CQ(obj).faces("+Z") - """ - if self.parent: - return self.parent - else: - raise ValueError("Cannot End the chain-- no parents!") - - def findSolid(self, searchStack=True, searchParents=True): - """ - Finds the first solid object in the chain, searching from the current node - backwards through parents until one is found. - - :param searchStack: should objects on the stack be searched first. - :param searchParents: should parents be searched? - :raises: ValueError if no solid is found in the current object or its parents, - and errorOnEmpty is True - - This function is very important for chains that are modifying a single parent object, - most often a solid. - - Most of the time, a chain defines or selects a solid, and then modifies it using workplanes - or other operations. - - Plugin Developers should make use of this method to find the solid that should be modified, - if the plugin implements a unary operation, or if the operation will automatically merge its - results with an object already on the stack. - """ - #notfound = ValueError("Cannot find a Valid Solid to Operate on!") - - if searchStack: - for s in self.objects: - if isinstance(s, Solid): - return s - elif isinstance(s, Compound): - return s.Solids() - - if searchParents and self.parent is not None: - return self.parent.findSolid(searchStack=True, searchParents=searchParents) - - return None - - def _selectObjects(self, objType, selector=None): - """ - Filters objects of the selected type with the specified selector,and returns results - - :param objType: the type of object we are searching for - :type objType: string: (Vertex|Edge|Wire|Solid|Shell|Compound|CompSolid) - :return: a CQ object with the selected objects on the stack. - - **Implementation Note**: This is the base implementation of the vertices,edges,faces, - solids,shells, and other similar selector methods. It is a useful extension point for - plugin developers to make other selector methods. - """ - # A single list of all faces from all objects on the stack - toReturn = self._collectProperty(objType) - - if selector is not None: - if isinstance(selector, str) or isinstance(selector, unicode): - selectorObj = selectors.StringSyntaxSelector(selector) - else: - selectorObj = selector - toReturn = selectorObj.filter(toReturn) - - return self.newObject(toReturn) - - def vertices(self, selector=None): - """ - Select the vertices of objects on the stack, optionally filtering the selection. If there - are multiple objects on the stack, the vertices of all objects are collected and a list of - all the distinct vertices is returned. - - :param selector: - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains the *distinct* vertices of *all* objects on the - current stack, after being filtered by the selector, if provided - - If there are no vertices for any objects on the current stack, an empty CQ object - is returned - - The typical use is to select the vertices of a single object on the stack. For example:: - - Workplane().box(1,1,1).faces("+Z").vertices().size() - - returns 4, because the topmost face of cube will contain four vertices. While this:: - - Workplane().box(1,1,1).faces().vertices().size() - - returns 8, because a cube has a total of 8 vertices - - **Note** Circles are peculiar, they have a single vertex at the center! - - :py:class:`StringSyntaxSelector` - - """ - return self._selectObjects('Vertices', selector) - - def faces(self, selector=None): - """ - Select the faces of objects on the stack, optionally filtering the selection. If there are - multiple objects on the stack, the faces of all objects are collected and a list of all the - distinct faces is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* faces of *all* objects on - the current stack, filtered by the provided selector. - - If there are no vertices for any objects on the current stack, an empty CQ object - is returned. - - The typical use is to select the faces of a single object on the stack. For example:: - - CQ(aCube).faces("+Z").size() - - returns 1, because a cube has one face with a normal in the +Z direction. Similarly:: - - CQ(aCube).faces().size() - - returns 6, because a cube has a total of 6 faces, And:: - - CQ(aCube).faces("|Z").size() - - returns 2, because a cube has 2 faces having normals parallel to the z direction - - See more about selectors HERE - """ - return self._selectObjects('Faces', selector) - - def edges(self, selector=None): - """ - Select the edges of objects on the stack, optionally filtering the selection. If there are - multiple objects on the stack, the edges of all objects are collected and a list of all the - distinct edges is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* edges of *all* objects on - the current stack, filtered by the provided selector. - - If there are no edges for any objects on the current stack, an empty CQ object is returned - - The typical use is to select the edges of a single object on the stack. For example:: - - CQ(aCube).faces("+Z").edges().size() - - returns 4, because a cube has one face with a normal in the +Z direction. Similarly:: - - CQ(aCube).edges().size() - - returns 12, because a cube has a total of 12 edges, And:: - - CQ(aCube).edges("|Z").size() - - returns 4, because a cube has 4 edges parallel to the z direction - - See more about selectors HERE - """ - return self._selectObjects('Edges', selector) - - def wires(self, selector=None): - """ - Select the wires of objects on the stack, optionally filtering the selection. If there are - multiple objects on the stack, the wires of all objects are collected and a list of all the - distinct wires is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* wires of *all* objects on - the current stack, filtered by the provided selector. - - If there are no wires for any objects on the current stack, an empty CQ object is returned - - The typical use is to select the wires of a single object on the stack. For example:: - - CQ(aCube).faces("+Z").wires().size() - - returns 1, because a face typically only has one outer wire - - See more about selectors HERE - """ - return self._selectObjects('Wires', selector) - - def solids(self, selector=None): - """ - Select the solids of objects on the stack, optionally filtering the selection. If there are - multiple objects on the stack, the solids of all objects are collected and a list of all the - distinct solids is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* solids of *all* objects on - the current stack, filtered by the provided selector. - - If there are no solids for any objects on the current stack, an empty CQ object is returned - - The typical use is to select the a single object on the stack. For example:: - - CQ(aCube).solids().size() - - returns 1, because a cube consists of one solid. - - It is possible for single CQ object ( or even a single CAD primitive ) to contain - multiple solids. - - See more about selectors HERE - """ - return self._selectObjects('Solids', selector) - - def shells(self, selector=None): - """ - Select the shells of objects on the stack, optionally filtering the selection. If there are - multiple objects on the stack, the shells of all objects are collected and a list of all the - distinct shells is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* solids of *all* objects on - the current stack, filtered by the provided selector. - - If there are no shells for any objects on the current stack, an empty CQ object is returned - - Most solids will have a single shell, which represents the outer surface. A shell will - typically be composed of multiple faces. - - See more about selectors HERE - """ - return self._selectObjects('Shells', selector) - - def compounds(self, selector=None): - """ - Select compounds on the stack, optionally filtering the selection. If there are multiple - objects on the stack, they are collected and a list of all the distinct compounds - is returned. - - :param selector: A selector - :type selector: None, a Selector object, or a string selector expression. - :return: a CQ object who's stack contains all of the *distinct* solids of *all* objects on - the current stack, filtered by the provided selector. - - A compound contains multiple CAD primitives that resulted from a single operation, such as - a union, cut, split, or fillet. Compounds can contain multiple edges, wires, or solids. - - See more about selectors HERE - """ - return self._selectObjects('Compounds', selector) - - def toSvg(self, opts=None): - """ - Returns svg text that represents the first item on the stack. - - for testing purposes. - - :param opts: svg formatting options - :type opts: dictionary, width and height - :return: a string that contains SVG that represents this item. - """ - return exporters.getSVG(self.val().wrapped, opts) - - def exportSvg(self, fileName): - """ - Exports the first item on the stack as an SVG file - - For testing purposes mainly. - - :param fileName: the filename to export - :type fileName: String, absolute path to the file - """ - exporters.exportSVG(self, fileName) - - def rotateAboutCenter(self, axisEndPoint, angleDegrees): - """ - Rotates all items on the stack by the specified angle, about the specified axis - - The center of rotation is a vector starting at the center of the object on the stack, - and ended at the specified point. - - :param axisEndPoint: the second point of axis of rotation - :type axisEndPoint: a three-tuple in global coordinates - :param angleDegrees: the rotation angle, in degrees - :type angleDegrees: float - :returns: a CQ object, with all items rotated. - - WARNING: This version returns the same cq object instead of a new one-- the - old object is not accessible. - - Future Enhancements: - * A version of this method that returns a transformed copy, rather than modifying - the originals - * This method doesnt expose a very good interface, because the axis of rotation - could be inconsistent between multiple objects. This is because the beginning - of the axis is variable, while the end is fixed. This is fine when operating on - one object, but is not cool for multiple. - """ - - #center point is the first point in the vector - endVec = Vector(axisEndPoint) - - def _rot(obj): - startPt = obj.Center() - endPt = startPt + endVec - return obj.rotate(startPt, endPt, angleDegrees) - - return self.each(_rot, False) - - def rotate(self, axisStartPoint, axisEndPoint, angleDegrees): - """ - Returns a copy of all of the items on the stack rotated through and angle around the axis - of rotation. - - :param axisStartPoint: The first point of the axis of rotation - :type axisStartPoint: a 3-tuple of floats - :type axisEndPoint: The second point of the axis of rotation - :type axisEndPoint: a 3-tuple of floats - :param angleDegrees: the rotation angle, in degrees - :type angleDegrees: float - :returns: a CQ object - """ - return self.newObject([o.rotate(axisStartPoint, axisEndPoint, angleDegrees) - for o in self.objects]) - - def mirror(self, mirrorPlane="XY", basePointVector=(0, 0, 0)): - """ - Mirror a single CQ object. This operation is the same as in the FreeCAD PartWB's mirroring - - :param mirrorPlane: the plane to mirror about - :type mirrorPlane: string, one of "XY", "YX", "XZ", "ZX", "YZ", "ZY" the planes - :param basePointVector: the base point to mirror about - :type basePointVector: tuple - """ - newS = self.newObject([self.objects[0].mirror(mirrorPlane, basePointVector)]) - return newS.first() - - - def translate(self, vec): - """ - Returns a copy of all of the items on the stack moved by the specified translation vector. - - :param tupleDistance: distance to move, in global coordinates - :type tupleDistance: a 3-tuple of float - :returns: a CQ object - """ - return self.newObject([o.translate(vec) for o in self.objects]) - - - def shell(self, thickness): - """ - Remove the selected faces to create a shell of the specified thickness. - - To shell, first create a solid, and *in the same chain* select the faces you wish to remove. - - :param thickness: a positive float, representing the thickness of the desired shell. - Negative values shell inwards, positive values shell outwards. - :raises: ValueError if the current stack contains objects that are not faces of a solid - further up in the chain. - :returns: a CQ object with the resulting shelled solid selected. - - This example will create a hollowed out unit cube, where the top most face is open, - and all other walls are 0.2 units thick:: - - Workplane().box(1,1,1).faces("+Z").shell(0.2) - - Shelling is one of the cases where you may need to use the add method to select several - faces. For example, this example creates a 3-walled corner, by removing three faces - of a cube:: - - s = Workplane().box(1,1,1) - s1 = s.faces("+Z") - s1.add(s.faces("+Y")).add(s.faces("+X")) - self.saveModel(s1.shell(0.2)) - - This fairly yucky syntax for selecting multiple faces is planned for improvement - - **Note**: When sharp edges are shelled inwards, they remain sharp corners, but **outward** - shells are automatically filleted, because an outward offset from a corner generates - a radius. - - - Future Enhancements: - Better selectors to make it easier to select multiple faces - """ - solidRef = self.findSolid() - - for f in self.objects: - if type(f) != Face: - raise ValueError("Shelling requires that faces be selected") - - s = solidRef.shell(self.objects, thickness) - solidRef.wrapped = s.wrapped - return self.newObject([s]) - - def fillet(self, radius): - """ - Fillets a solid on the selected edges. - - The edges on the stack are filleted. The solid to which the edges belong must be in the - parent chain of the selected edges. - - :param radius: the radius of the fillet, must be > zero - :type radius: positive float - :raises: ValueError if at least one edge is not selected - :raises: ValueError if the solid containing the edge is not in the chain - :returns: cq object with the resulting solid selected. - - This example will create a unit cube, with the top edges filleted:: - - s = Workplane().box(1,1,1).faces("+Z").edges().fillet(0.1) - """ - # TODO: we will need much better edge selectors for this to work - # TODO: ensure that edges selected actually belong to the solid in the chain, otherwise, - # TODO: we segfault - - solid = self.findSolid() - - edgeList = self.edges().vals() - if len(edgeList) < 1: - raise ValueError("Fillets requires that edges be selected") - - s = solid.fillet(radius, edgeList) - solid.wrapped = s.wrapped - return self.newObject([s]) - - def chamfer(self, length, length2=None): - """ - Chamfers a solid on the selected edges. - - The edges on the stack are chamfered. The solid to which the - edges belong must be in the parent chain of the selected - edges. - - Optional parameter `length2` can be supplied with a different - value than `length` for a chamfer that is shorter on one side - longer on the other side. - - :param length: the length of the fillet, must be greater than zero - :param length2: optional parameter for asymmetrical chamfer - :type length: positive float - :type length2: positive float - :raises: ValueError if at least one edge is not selected - :raises: ValueError if the solid containing the edge is not in the chain - :returns: cq object with the resulting solid selected. - - This example will create a unit cube, with the top edges chamfered:: - - s = Workplane("XY").box(1,1,1).faces("+Z").chamfer(0.1) - - This example will create chamfers longer on the sides:: - - s = Workplane("XY").box(1,1,1).faces("+Z").chamfer(0.2, 0.1) - """ - solid = self.findSolid() - - edgeList = self.edges().vals() - if len(edgeList) < 1: - raise ValueError("Chamfer requires that edges be selected") - - s = solid.chamfer(length, length2, edgeList) - - solid.wrapped = s.wrapped - return self.newObject([s]) - - -class Workplane(CQ): - """ - Defines a coordinate system in space, in which 2-d coordinates can be used. - - :param plane: the plane in which the workplane will be done - :type plane: a Plane object, or a string in (XY|YZ|XZ|front|back|top|bottom|left|right) - :param origin: the desired origin of the new workplane - :type origin: a 3-tuple in global coordinates, or None to default to the origin - :param obj: an object to use initially for the stack - :type obj: a CAD primitive, or None to use the centerpoint of the plane as the initial - stack value. - :raises: ValueError if the provided plane is not a plane, a valid named workplane - :return: A Workplane object, with coordinate system matching the supplied plane. - - The most common use is:: - - s = Workplane("XY") - - After creation, the stack contains a single point, the origin of the underlying plane, - and the *current point* is on the origin. - - .. note:: - You can also create workplanes on the surface of existing faces using - :py:meth:`CQ.workplane` - """ - - FOR_CONSTRUCTION = 'ForConstruction' - - def __init__(self, inPlane, origin=(0, 0, 0), obj=None): - """ - make a workplane from a particular plane - - :param inPlane: the plane in which the workplane will be done - :type inPlane: a Plane object, or a string in (XY|YZ|XZ|front|back|top|bottom|left|right) - :param origin: the desired origin of the new workplane - :type origin: a 3-tuple in global coordinates, or None to default to the origin - :param obj: an object to use initially for the stack - :type obj: a CAD primitive, or None to use the centerpoint of the plane as the initial - stack value. - :raises: ValueError if the provided plane is not a plane, or one of XY|YZ|XZ - :return: A Workplane object, with coordinate system matching the supplied plane. - - The most common use is:: - - s = Workplane("XY") - - After creation, the stack contains a single point, the origin of the underlying plane, and - the *current point* is on the origin. - """ - - if inPlane.__class__.__name__ == 'Plane': - tmpPlane = inPlane - elif isinstance(inPlane, str) or isinstance(inPlane, unicode): - tmpPlane = Plane.named(inPlane, origin) - else: - tmpPlane = None - - if tmpPlane is None: - raise ValueError( - 'Provided value {} is not a valid work plane'.format(inPlane)) - - self.obj = obj - self.plane = tmpPlane - self.firstPoint = None - # Changed so that workplane has the center as the first item on the stack - self.objects = [self.plane.origin] - self.parent = None - self.ctx = CQContext() - - def transformed(self, rotate=(0, 0, 0), offset=(0, 0, 0)): - """ - Create a new workplane based on the current one. - The origin of the new plane is located at the existing origin+offset vector, where offset is - given in coordinates local to the current plane - The new plane is rotated through the angles specified by the components of the rotation - vector. - :param rotate: 3-tuple of angles to rotate, in degrees relative to work plane coordinates - :param offset: 3-tuple to offset the new plane, in local work plane coordinates - :return: a new work plane, transformed as requested - """ - - #old api accepted a vector, so we'll check for that. - if rotate.__class__.__name__ == 'Vector': - rotate = rotate.toTuple() - - if offset.__class__.__name__ == 'Vector': - offset = offset.toTuple() - - p = self.plane.rotated(rotate) - p.origin = self.plane.toWorldCoords(offset) - ns = self.newObject([p.origin]) - ns.plane = p - - return ns - - def newObject(self, objlist): - """ - Create a new workplane object from this one. - - Overrides CQ.newObject, and should be used by extensions, plugins, and - subclasses to create new objects. - - :param objlist: new objects to put on the stack - :type objlist: a list of CAD primitives - :return: a new Workplane object with the current workplane as a parent. - """ - - #copy the current state to the new object - ns = Workplane("XY") - ns.plane = self.plane - ns.parent = self - ns.objects = list(objlist) - ns.ctx = self.ctx - return ns - - def _findFromPoint(self, useLocalCoords=False): - """ - Finds the start point for an operation when an existing point - is implied. Examples include 2d operations such as lineTo, - which allows specifying the end point, and implicitly use the - end of the previous line as the starting point - - :return: a Vector representing the point to use, or none if - such a point is not available. - - :param useLocalCoords: selects whether the point is returned - in local coordinates or global coordinates. - - The algorithm is this: - * If an Edge is on the stack, its end point is used.yp - * if a vector is on the stack, it is used - - WARNING: only the last object on the stack is used. - - NOTE: - """ - obj = self.objects[-1] - - if isinstance(obj, Edge): - p = obj.endPoint() - elif isinstance(obj, Vector): - p = obj - else: - raise RuntimeError("Cannot convert object type '%s' to vector " % type(obj)) - - if useLocalCoords: - return self.plane.toLocalCoords(p) - else: - return p - - def rarray(self, xSpacing, ySpacing, xCount, yCount, center=True): - """ - Creates an array of points and pushes them onto the stack. - If you want to position the array at another point, create another workplane - that is shifted to the position you would like to use as a reference - - :param xSpacing: spacing between points in the x direction ( must be > 0) - :param ySpacing: spacing between points in the y direction ( must be > 0) - :param xCount: number of points ( > 0 ) - :param yCount: number of points ( > 0 ) - :param center: if true, the array will be centered at the center of the workplane. if - false, the lower left corner will be at the center of the work plane - """ - - if xSpacing < 1 or ySpacing < 1 or xCount < 1 or yCount < 1: - raise ValueError("Spacing and count must be > 0 ") - - lpoints = [] # coordinates relative to bottom left point - for x in range(xCount): - for y in range(yCount): - lpoints.append((xSpacing * x, ySpacing * y)) - - #shift points down and left relative to origin if requested - if center: - xc = xSpacing*(xCount-1) * 0.5 - yc = ySpacing*(yCount-1) * 0.5 - cpoints = [] - for p in lpoints: - cpoints.append((p[0] - xc, p[1] - yc)) - lpoints = list(cpoints) - - return self.pushPoints(lpoints) - - def pushPoints(self, pntList): - """ - Pushes a list of points onto the stack as vertices. - The points are in the 2-d coordinate space of the workplane face - - :param pntList: a list of points to push onto the stack - :type pntList: list of 2-tuples, in *local* coordinates - :return: a new workplane with the desired points on the stack. - - A common use is to provide a list of points for a subsequent operation, such as creating - circles or holes. This example creates a cube, and then drills three holes through it, - based on three points:: - - s = Workplane().box(1,1,1).faces(">Z").workplane().\ - pushPoints([(-0.3,0.3),(0.3,0.3),(0,0)]) - body = s.circle(0.05).cutThruAll() - - Here the circle function operates on all three points, and is then extruded to create three - holes. See :py:meth:`circle` for how it works. - """ - vecs = [] - for pnt in pntList: - vec = self.plane.toWorldCoords(pnt) - vecs.append(vec) - - return self.newObject(vecs) - - def center(self, x, y): - """ - Shift local coordinates to the specified location. - - The location is specified in terms of local coordinates. - - :param float x: the new x location - :param float y: the new y location - :returns: the workplane object, with the center adjusted. - - The current point is set to the new center. - This method is useful to adjust the center point after it has been created automatically on - a face, but not where you'd like it to be. - - In this example, we adjust the workplane center to be at the corner of a cube, instead of - the center of a face, which is the default:: - - #this workplane is centered at x=0.5,y=0.5, the center of the upper face - s = Workplane().box(1,1,1).faces(">Z").workplane() - - s.center(-0.5,-0.5) # move the center to the corner - t = s.circle(0.25).extrude(0.2) - assert ( t.faces().size() == 9 ) # a cube with a cylindrical nub at the top right corner - - The result is a cube with a round boss on the corner - """ - "Shift local coordinates to the specified location, according to current coordinates" - self.plane.setOrigin2d(x, y) - n = self.newObject([self.plane.origin]) - return n - - def lineTo(self, x, y, forConstruction=False): - """ - Make a line from the current point to the provided point - - :param float x: the x point, in workplane plane coordinates - :param float y: the y point, in workplane plane coordinates - :return: the Workplane object with the current point at the end of the new line - - see :py:meth:`line` if you want to use relative dimensions to make a line instead. - """ - startPoint = self._findFromPoint(False) - - endPoint = self.plane.toWorldCoords((x, y)) - - p = Edge.makeLine(startPoint, endPoint) - - if not forConstruction: - self._addPendingEdge(p) - - return self.newObject([p]) - - # line a specified incremental amount from current point - def line(self, xDist, yDist, forConstruction=False): - """ - Make a line from the current point to the provided point, using - dimensions relative to the current point - - :param float xDist: x distance from current point - :param float yDist: y distance from current point - :return: the workplane object with the current point at the end of the new line - - see :py:meth:`lineTo` if you want to use absolute coordinates to make a line instead. - """ - p = self._findFromPoint(True) # return local coordinates - return self.lineTo(p.x + xDist, yDist + p.y, forConstruction) - - def vLine(self, distance, forConstruction=False): - """ - Make a vertical line from the current point the provided distance - - :param float distance: (y) distance from current point - :return: the workplane object with the current point at the end of the new line - """ - return self.line(0, distance, forConstruction) - - def hLine(self, distance, forConstruction=False): - """ - Make a horizontal line from the current point the provided distance - - :param float distance: (x) distance from current point - :return: the Workplane object with the current point at the end of the new line - """ - return self.line(distance, 0, forConstruction) - - def vLineTo(self, yCoord, forConstruction=False): - """ - Make a vertical line from the current point to the provided y coordinate. - - Useful if it is more convenient to specify the end location rather than distance, - as in :py:meth:`vLine` - - :param float yCoord: y coordinate for the end of the line - :return: the Workplane object with the current point at the end of the new line - """ - p = self._findFromPoint(True) - return self.lineTo(p.x, yCoord, forConstruction) - - def hLineTo(self, xCoord, forConstruction=False): - """ - Make a horizontal line from the current point to the provided x coordinate. - - Useful if it is more convenient to specify the end location rather than distance, - as in :py:meth:`hLine` - - :param float xCoord: x coordinate for the end of the line - :return: the Workplane object with the current point at the end of the new line - """ - p = self._findFromPoint(True) - return self.lineTo(xCoord, p.y, forConstruction) - - #absolute move in current plane, not drawing - def moveTo(self, x=0, y=0): - """ - Move to the specified point, without drawing. - - :param x: desired x location, in local coordinates - :type x: float, or none for zero - :param y: desired y location, in local coordinates - :type y: float, or none for zero. - - Not to be confused with :py:meth:`center`, which moves the center of the entire - workplane, this method only moves the current point ( and therefore does not affect objects - already drawn ). - - See :py:meth:`move` to do the same thing but using relative dimensions - """ - newCenter = Vector(x, y, 0) - return self.newObject([self.plane.toWorldCoords(newCenter)]) - - #relative move in current plane, not drawing - def move(self, xDist=0, yDist=0): - """ - Move the specified distance from the current point, without drawing. - - :param xDist: desired x distance, in local coordinates - :type xDist: float, or none for zero - :param yDist: desired y distance, in local coordinates - :type yDist: float, or none for zero. - - Not to be confused with :py:meth:`center`, which moves the center of the entire - workplane, this method only moves the current point ( and therefore does not affect objects - already drawn ). - - See :py:meth:`moveTo` to do the same thing but using absolute coordinates - """ - p = self._findFromPoint(True) - newCenter = p + Vector(xDist, yDist, 0) - return self.newObject([self.plane.toWorldCoords(newCenter)]) - - def spline(self, listOfXYTuple, forConstruction=False): - """ - Create a spline interpolated through the provided points. - - :param listOfXYTuple: points to interpolate through - :type listOfXYTuple: list of 2-tuple - :return: a Workplane object with the current point at the end of the spline - - The spline will begin at the current point, and - end with the last point in the XY tuple list - - This example creates a block with a spline for one side:: - - s = Workplane(Plane.XY()) - sPnts = [ - (2.75,1.5), - (2.5,1.75), - (2.0,1.5), - (1.5,1.0), - (1.0,1.25), - (0.5,1.0), - (0,1.0) - ] - r = s.lineTo(3.0,0).lineTo(3.0,1.0).spline(sPnts).close() - r = r.extrude(0.5) - - *WARNING* It is fairly easy to create a list of points - that cannot be correctly interpreted as a spline. - - Future Enhancements: - * provide access to control points - """ - gstartPoint = self._findFromPoint(False) - gEndPoint = self.plane.toWorldCoords(listOfXYTuple[-1]) - - vecs = [self.plane.toWorldCoords(p) for p in listOfXYTuple] - allPoints = [gstartPoint] + vecs - - e = Edge.makeSpline(allPoints) - - if not forConstruction: - self._addPendingEdge(e) - - return self.newObject([e]) - - def threePointArc(self, point1, point2, forConstruction=False): - """ - Draw an arc from the current point, through point1, and ending at point2 - - :param point1: point to draw through - :type point1: 2-tuple, in workplane coordinates - :param point2: end point for the arc - :type point2: 2-tuple, in workplane coordinates - :return: a workplane with the current point at the end of the arc - - Future Enhancements: - provide a version that allows an arc using relative measures - provide a centerpoint arc - provide tangent arcs - """ - - gstartPoint = self._findFromPoint(False) - gpoint1 = self.plane.toWorldCoords(point1) - gpoint2 = self.plane.toWorldCoords(point2) - - arc = Edge.makeThreePointArc(gstartPoint, gpoint1, gpoint2) - - if not forConstruction: - self._addPendingEdge(arc) - - return self.newObject([arc]) - - def rotateAndCopy(self, matrix): - """ - Makes a copy of all edges on the stack, rotates them according to the - provided matrix, and then attempts to consolidate them into a single wire. - - :param matrix: a 4xr transformation matrix, in global coordinates - :type matrix: a FreeCAD Base.Matrix object - :return: a CadQuery object with consolidated wires, and any originals on the stack. - - The most common use case is to create a set of open edges, and then mirror them - around either the X or Y axis to complete a closed shape. - - see :py:meth:`mirrorX` and :py:meth:`mirrorY` to mirror about the global X and Y axes - see :py:meth:`mirrorX` and for an example - - Future Enhancements: - faster implementation: this one transforms 3 times to accomplish the result - """ - - #convert edges to a wire, if there are pending edges - n = self.wire(forConstruction=False) - - #attempt to consolidate wires together. - consolidated = n.consolidateWires() - - rotatedWires = self.plane.rotateShapes(consolidated.wires().vals(), matrix) - - for w in rotatedWires: - consolidated.objects.append(w) - consolidated._addPendingWire(w) - - #attempt again to consolidate all of the wires - c = consolidated.consolidateWires() - - return c - - def mirrorY(self): - """ - Mirror entities around the y axis of the workplane plane. - - :return: a new object with any free edges consolidated into as few wires as possible. - - All free edges are collected into a wire, and then the wire is mirrored, - and finally joined into a new wire - - Typically used to make creating wires with symmetry easier. This line of code:: - - s = Workplane().lineTo(2,2).threePointArc((3,1),(2,0)).mirrorX().extrude(0.25) - - Produces a flat, heart shaped object - - Future Enhancements: - mirrorX().mirrorY() should work but doesnt, due to some FreeCAD weirdness - """ - tm = Matrix() - tm.rotateY(math.pi) - return self.rotateAndCopy(tm) - - def mirrorX(self): - """ - Mirror entities around the x axis of the workplane plane. - - :return: a new object with any free edges consolidated into as few wires as possible. - - All free edges are collected into a wire, and then the wire is mirrored, - and finally joined into a new wire - - Typically used to make creating wires with symmetry easier. - - Future Enhancements: - mirrorX().mirrorY() should work but doesnt, due to some FreeCAD weirdness - """ - tm = Matrix() - tm.rotateX(math.pi) - return self.rotateAndCopy(tm) - - def _addPendingEdge(self, edge): - """ - Queues an edge for later combination into a wire. - - :param edge: - :return: - """ - self.ctx.pendingEdges.append(edge) - - if self.ctx.firstPoint is None: - self.ctx.firstPoint = self.plane.toLocalCoords(edge.startPoint()) - - def _addPendingWire(self, wire): - """ - Queue a Wire for later extrusion - - Internal Processing Note. In FreeCAD, edges-->wires-->faces-->solids. - - but users do not normally care about these distinctions. Users 'think' in terms - of edges, and solids. - - CadQuery tracks edges as they are drawn, and automatically combines them into wires - when the user does an operation that needs it. - - Similarly, cadQuery tracks pending wires, and automatically combines them into faces - when necessary to make a solid. - """ - self.ctx.pendingWires.append(wire) - - def consolidateWires(self): - """ - Attempt to consolidate wires on the stack into a single. - If possible, a new object with the results are returned. - if not possible, the wires remain separated - - FreeCAD has a bug in Part.Wire([]) which does not create wires/edges properly sometimes - Additionally, it has a bug where a profile composed of two wires ( rather than one ) - also does not work properly. Together these are a real problem. - """ - wires = self.wires().vals() - if len(wires) < 2: - return self - - #TODO: this makes the assumption that either all wires could be combined, or none. - #in reality trying each combination of wires is probably not reasonable anyway - w = Wire.combine(wires) - - #ok this is a little tricky. if we consolidate wires, we have to actually - #modify the pendingWires collection to remove the original ones, and replace them - #with the consolidate done - #since we are already assuming that all wires could be consolidated, its easy, we just - #clear the pending wire list - r = self.newObject([w]) - r.ctx.pendingWires = [] - r._addPendingWire(w) - return r - - def wire(self, forConstruction=False): - """ - Returns a CQ object with all pending edges connected into a wire. - - All edges on the stack that can be combined will be combined into a single wire object, - and other objects will remain on the stack unmodified - - :param forConstruction: whether the wire should be used to make a solid, or if it is just - for reference - :type forConstruction: boolean. true if the object is only for reference - - This method is primarily of use to plugin developers making utilities for 2-d construction. - This method should be called when a user operation implies that 2-d construction is - finished, and we are ready to begin working in 3d - - SEE '2-d construction concepts' for a more detailed explanation of how CadQuery handles - edges, wires, etc - - Any non edges will still remain. - """ - - edges = self.ctx.pendingEdges - - #do not consolidate if there are no free edges - if len(edges) == 0: - return self - - self.ctx.pendingEdges = [] - - others = [] - for e in self.objects: - if type(e) != Edge: - others.append(e) - - - w = Wire.assembleEdges(edges) - if not forConstruction: - self._addPendingWire(w) - - return self.newObject(others + [w]) - - def each(self, callBackFunction, useLocalCoordinates=False): - """ - Runs the provided function on each value in the stack, and collects the return values into - a new CQ object. - - Special note: a newly created workplane always has its center point as its only stack item - - :param callBackFunction: the function to call for each item on the current stack. - :param useLocalCoordinates: should values be converted from local coordinates first? - :type useLocalCoordinates: boolean - - The callback function must accept one argument, which is the item on the stack, and return - one object, which is collected. If the function returns None, nothing is added to the stack. - The object passed into the callBackFunction is potentially transformed to local coordinates, - if useLocalCoordinates is true - - useLocalCoordinates is very useful for plugin developers. - - If false, the callback function is assumed to be working in global coordinates. Objects - created are added as-is, and objects passed into the function are sent in using global - coordinates - - If true, the calling function is assumed to be working in local coordinates. Objects are - transformed to local coordinates before they are passed into the callback method, and result - objects are transformed to global coordinates after they are returned. - - This allows plugin developers to create objects in local coordinates, without worrying - about the fact that the working plane is different than the global coordinate system. - - - TODO: wrapper object for Wire will clean up forConstruction flag everywhere - """ - results = [] - for obj in self.objects: - - if useLocalCoordinates: - #TODO: this needs to work for all types of objects, not just vectors! - r = callBackFunction(self.plane.toLocalCoords(obj)) - r = r.transformShape(self.plane.rG) - else: - r = callBackFunction(obj) - - if type(r) == Wire: - if not r.forConstruction: - self._addPendingWire(r) - - results.append(r) - - return self.newObject(results) - - def eachpoint(self, callbackFunction, useLocalCoordinates=False): - """ - Same as each(), except each item on the stack is converted into a point before it - is passed into the callback function. - - :return: CadQuery object which contains a list of vectors (points ) on its stack. - - :param useLocalCoordinates: should points be in local or global coordinates - :type useLocalCoordinates: boolean - - The resulting object has a point on the stack for each object on the original stack. - Vertices and points remain a point. Faces, Wires, Solids, Edges, and Shells are converted - to a point by using their center of mass. - - If the stack has zero length, a single point is returned, which is the center of the current - workplane/coordinate system - """ - #convert stack to a list of points - pnts = [] - if len(self.objects) == 0: - #nothing on the stack. here, we'll assume we should operate with the - #origin as the context point - pnts.append(self.plane.origin) - else: - - for v in self.objects: - pnts.append(v.Center()) - - return self.newObject(pnts).each(callbackFunction, useLocalCoordinates) - - def rect(self, xLen, yLen, centered=True, forConstruction=False): - """ - Make a rectangle for each item on the stack. - - :param xLen: length in xDirection ( in workplane coordinates ) - :type xLen: float > 0 - :param yLen: length in yDirection ( in workplane coordinates ) - :type yLen: float > 0 - :param boolean centered: true if the rect is centered on the reference point, false if the - lower-left is on the reference point - :param forConstruction: should the new wires be reference geometry only? - :type forConstruction: true if the wires are for reference, false if they are creating part - geometry - :return: a new CQ object with the created wires on the stack - - A common use case is to use a for-construction rectangle to define the centers of a hole - pattern:: - - s = Workplane().rect(4.0,4.0,forConstruction=True).vertices().circle(0.25) - - Creates 4 circles at the corners of a square centered on the origin. - - Future Enhancements: - better way to handle forConstruction - project points not in the workplane plane onto the workplane plane - """ - def makeRectangleWire(pnt): - # Here pnt is in local coordinates due to useLocalCoords=True - # (xc,yc,zc) = pnt.toTuple() - if centered: - p1 = pnt.add(Vector(xLen/-2.0, yLen/-2.0, 0)) - p2 = pnt.add(Vector(xLen/2.0, yLen/-2.0, 0)) - p3 = pnt.add(Vector(xLen/2.0, yLen/2.0, 0)) - p4 = pnt.add(Vector(xLen/-2.0, yLen/2.0, 0)) - else: - p1 = pnt - p2 = pnt.add(Vector(xLen, 0, 0)) - p3 = pnt.add(Vector(xLen, yLen, 0)) - p4 = pnt.add(Vector(0, yLen, 0)) - - w = Wire.makePolygon([p1, p2, p3, p4, p1], forConstruction) - return w - #return Part.makePolygon([p1,p2,p3,p4,p1]) - - return self.eachpoint(makeRectangleWire, True) - - #circle from current point - def circle(self, radius, forConstruction=False): - """ - Make a circle for each item on the stack. - - :param radius: radius of the circle - :type radius: float > 0 - :param forConstruction: should the new wires be reference geometry only? - :type forConstruction: true if the wires are for reference, false if they are creating - part geometry - :return: a new CQ object with the created wires on the stack - - A common use case is to use a for-construction rectangle to define the centers of a - hole pattern:: - - s = Workplane().rect(4.0,4.0,forConstruction=True).vertices().circle(0.25) - - Creates 4 circles at the corners of a square centered on the origin. Another common case is - to use successive circle() calls to create concentric circles. This works because the - center of a circle is its reference point:: - - s = Workplane().circle(2.0).circle(1.0) - - Creates two concentric circles, which when extruded will form a ring. - - Future Enhancements: - better way to handle forConstruction - project points not in the workplane plane onto the workplane plane - - """ - def makeCircleWire(obj): - cir = Wire.makeCircle(radius, obj, Vector(0, 0, 1)) - cir.forConstruction = forConstruction - return cir - - return self.eachpoint(makeCircleWire, useLocalCoordinates=True) - - def polygon(self, nSides, diameter, forConstruction=False): - """ - Creates a polygon inscribed in a circle of the specified diameter for each point on - the stack - - The first vertex is always oriented in the x direction. - - :param nSides: number of sides, must be > 3 - :param diameter: the size of the circle the polygon is inscribed into - :return: a polygon wire - """ - def _makePolygon(center): - #pnt is a vector in local coordinates - angle = 2.0 * math.pi / nSides - pnts = [] - for i in range(nSides+1): - pnts.append(center + Vector((diameter / 2.0 * math.cos(angle*i)), - (diameter / 2.0 * math.sin(angle*i)), 0)) - return Wire.makePolygon(pnts, forConstruction) - - return self.eachpoint(_makePolygon, True) - - def polyline(self, listOfXYTuple, forConstruction=False): - """ - Create a polyline from a list of points - - :param listOfXYTuple: a list of points in Workplane coordinates - :type listOfXYTuple: list of 2-tuples - :param forConstruction: whether or not the edges are used for reference - :type forConstruction: true if the edges are for reference, false if they are for creating geometry - part geometry - :return: a new CQ object with a list of edges on the stack - - *NOTE* most commonly, the resulting wire should be closed. - """ - - # Our list of new edges that will go into a new CQ object - edges = [] - - # The very first startPoint comes from our original object, but not after that - startPoint = self._findFromPoint(False) - - # Draw a line for each set of points, starting from the from-point of the original CQ object - for curTuple in listOfXYTuple: - endPoint = self.plane.toWorldCoords(curTuple) - - edges.append(Edge.makeLine(startPoint, endPoint)) - - # We need to move the start point for the next line that we draw or we get stuck at the same startPoint - startPoint = endPoint - - if not forConstruction: - self._addPendingEdge(edges[-1]) - - return self.newObject(edges) - - def close(self): - """ - End 2-d construction, and attempt to build a closed wire. - - :return: a CQ object with a completed wire on the stack, if possible. - - After 2-d drafting with lineTo,threePointArc, and polyline, it is necessary - to convert the edges produced by these into one or more wires. - - When a set of edges is closed, cadQuery assumes it is safe to build the group of edges - into a wire. This example builds a simple triangular prism:: - - s = Workplane().lineTo(1,0).lineTo(1,1).close().extrude(0.2) - """ - self.lineTo(self.ctx.firstPoint.x, self.ctx.firstPoint.y) - - # Need to reset the first point after closing a wire - self.ctx.firstPoint=None - - return self.wire() - - def largestDimension(self): - """ - Finds the largest dimension in the stack. - Used internally to create thru features, this is how you can compute - how long or wide a feature must be to make sure to cut through all of the material - :return: A value representing the largest dimension of the first solid on the stack - """ - #TODO: this implementation is naive and returns the dims of the first solid... most of - #TODO: the time this works. but a stronger implementation would be to search all solids. - s = self.findSolid() - if s: - return s.BoundingBox().DiagonalLength * 5.0 - else: - return -1 - - def cutEach(self, fcn, useLocalCoords=False, clean=True): - """ - Evaluates the provided function at each point on the stack (ie, eachpoint) - and then cuts the result from the context solid. - :param fcn: a function suitable for use in the eachpoint method: ie, that accepts a vector - :param useLocalCoords: same as for :py:meth:`eachpoint` - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :return: a CQ object that contains the resulting solid - :raises: an error if there is not a context solid to cut from - """ - ctxSolid = self.findSolid() - if ctxSolid is None: - raise ValueError("Must have a solid in the chain to cut from!") - - #will contain all of the counterbores as a single compound - results = self.eachpoint(fcn, useLocalCoords).vals() - s = ctxSolid - for cb in results: - s = s.cut(cb) - - if clean: s = s.clean() - - ctxSolid.wrapped = s.wrapped - return self.newObject([s]) - - #but parameter list is different so a simple function pointer wont work - def cboreHole(self, diameter, cboreDiameter, cboreDepth, depth=None, clean=True): - """ - Makes a counterbored hole for each item on the stack. - - :param diameter: the diameter of the hole - :type diameter: float > 0 - :param cboreDiameter: the diameter of the cbore - :type cboreDiameter: float > 0 and > diameter - :param cboreDepth: depth of the counterbore - :type cboreDepth: float > 0 - :param depth: the depth of the hole - :type depth: float > 0 or None to drill thru the entire part. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - - The surface of the hole is at the current workplane plane. - - One hole is created for each item on the stack. A very common use case is to use a - construction rectangle to define the centers of a set of holes, like so:: - - s = Workplane(Plane.XY()).box(2,4,0.5).faces(">Z").workplane()\ - .rect(1.5,3.5,forConstruction=True)\ - .vertices().cboreHole(0.125, 0.25,0.125,depth=None) - - This sample creates a plate with a set of holes at the corners. - - **Plugin Note**: this is one example of the power of plugins. Counterbored holes are quite - time consuming to create, but are quite easily defined by users. - - see :py:meth:`cskHole` to make countersinks instead of counterbores - """ - if depth is None: - depth = self.largestDimension() - - def _makeCbore(center): - """ - Makes a single hole with counterbore at the supplied point - returns a solid suitable for subtraction - pnt is in local coordinates - """ - boreDir = Vector(0, 0, -1) - #first make the hole - hole = Solid.makeCylinder(diameter/2.0, depth, center, boreDir) # local coordianates! - - #add the counter bore - cbore = Solid.makeCylinder(cboreDiameter / 2.0, cboreDepth, center, boreDir) - r = hole.fuse(cbore) - return r - - return self.cutEach(_makeCbore, True, clean) - - #TODO: almost all code duplicated! - #but parameter list is different so a simple function pointer wont work - def cskHole(self, diameter, cskDiameter, cskAngle, depth=None, clean=True): - """ - Makes a countersunk hole for each item on the stack. - - :param diameter: the diameter of the hole - :type diameter: float > 0 - :param cskDiameter: the diameter of the countersink - :type cskDiameter: float > 0 and > diameter - :param cskAngle: angle of the countersink, in degrees ( 82 is common ) - :type cskAngle: float > 0 - :param depth: the depth of the hole - :type depth: float > 0 or None to drill thru the entire part. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - - The surface of the hole is at the current workplane. - - One hole is created for each item on the stack. A very common use case is to use a - construction rectangle to define the centers of a set of holes, like so:: - - s = Workplane(Plane.XY()).box(2,4,0.5).faces(">Z").workplane()\ - .rect(1.5,3.5,forConstruction=True)\ - .vertices().cskHole(0.125, 0.25,82,depth=None) - - This sample creates a plate with a set of holes at the corners. - - **Plugin Note**: this is one example of the power of plugins. CounterSunk holes are quite - time consuming to create, but are quite easily defined by users. - - see :py:meth:`cboreHole` to make counterbores instead of countersinks - """ - - if depth is None: - depth = self.largestDimension() - - def _makeCsk(center): - #center is in local coordinates - - boreDir = Vector(0, 0, -1) - - #first make the hole - hole = Solid.makeCylinder(diameter/2.0, depth, center, boreDir) # local coords! - r = cskDiameter / 2.0 - h = r / math.tan(math.radians(cskAngle / 2.0)) - csk = Solid.makeCone(r, 0.0, h, center, boreDir) - r = hole.fuse(csk) - return r - - return self.cutEach(_makeCsk, True, clean) - - #TODO: almost all code duplicated! - #but parameter list is different so a simple function pointer wont work - def hole(self, diameter, depth=None, clean=True): - """ - Makes a hole for each item on the stack. - - :param diameter: the diameter of the hole - :type diameter: float > 0 - :param depth: the depth of the hole - :type depth: float > 0 or None to drill thru the entire part. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - - The surface of the hole is at the current workplane. - - One hole is created for each item on the stack. A very common use case is to use a - construction rectangle to define the centers of a set of holes, like so:: - - s = Workplane(Plane.XY()).box(2,4,0.5).faces(">Z").workplane()\ - .rect(1.5,3.5,forConstruction=True)\ - .vertices().hole(0.125, 0.25,82,depth=None) - - This sample creates a plate with a set of holes at the corners. - - **Plugin Note**: this is one example of the power of plugins. CounterSunk holes are quite - time consuming to create, but are quite easily defined by users. - - see :py:meth:`cboreHole` and :py:meth:`cskHole` to make counterbores or countersinks - """ - if depth is None: - depth = self.largestDimension() - - def _makeHole(center): - """ - Makes a single hole with counterbore at the supplied point - returns a solid suitable for subtraction - pnt is in local coordinates - """ - boreDir = Vector(0, 0, -1) - #first make the hole - hole = Solid.makeCylinder(diameter / 2.0, depth, center, boreDir) # local coordinates! - return hole - - return self.cutEach(_makeHole, True, clean) - - #TODO: duplicated code with _extrude and extrude - def twistExtrude(self, distance, angleDegrees, combine=True, clean=True): - """ - Extrudes a wire in the direction normal to the plane, but also twists by the specified - angle over the length of the extrusion - - The center point of the rotation will be the center of the workplane - - See extrude for more details, since this method is the same except for the the addition - of the angle. In fact, if angle=0, the result is the same as a linear extrude. - - **NOTE** This method can create complex calculations, so be careful using it with - complex geometries - - :param distance: the distance to extrude normal to the workplane - :param angle: angline ( in degrees) to rotate through the extrusion - :param boolean combine: True to combine the resulting solid with parent solids if found. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :return: a CQ object with the resulting solid selected. - """ - #group wires together into faces based on which ones are inside the others - #result is a list of lists - wireSets = sortWiresByBuildOrder(list(self.ctx.pendingWires), self.plane, []) - - self.ctx.pendingWires = [] # now all of the wires have been used to create an extrusion - - #compute extrusion vector and extrude - eDir = self.plane.zDir.multiply(distance) - - #one would think that fusing faces into a compound and then extruding would work, - #but it doesnt-- the resulting compound appears to look right, ( right number of faces, etc) - #but then cutting it from the main solid fails with BRep_NotDone. - #the work around is to extrude each and then join the resulting solids, which seems to work - - #underlying cad kernel can only handle simple bosses-- we'll aggregate them if there - # are multiple sets - r = None - for ws in wireSets: - thisObj = Solid.extrudeLinearWithRotation(ws[0], ws[1:], self.plane.origin, - eDir, angleDegrees) - if r is None: - r = thisObj - else: - r = r.fuse(thisObj) - - if combine: - newS = self._combineWithBase(r) - else: - newS = self.newObject([r]) - if clean: newS = newS.clean() - return newS - - def extrude(self, distance, combine=True, clean=True, both=False): - """ - Use all un-extruded wires in the parent chain to create a prismatic solid. - - :param distance: the distance to extrude, normal to the workplane plane - :type distance: float, negative means opposite the normal direction - :param boolean combine: True to combine the resulting solid with parent solids if found. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :param boolean both: extrude in both directions symmetrically - :return: a CQ object with the resulting solid selected. - - extrude always *adds* material to a part. - - The returned object is always a CQ object, and depends on wither combine is True, and - whether a context solid is already defined: - - * if combine is False, the new value is pushed onto the stack. - * if combine is true, the value is combined with the context solid if it exists, - and the resulting solid becomes the new context solid. - - FutureEnhancement: - Support for non-prismatic extrusion ( IE, sweeping along a profile, not just - perpendicular to the plane extrude to surface. this is quite tricky since the surface - selected may not be planar - """ - r = self._extrude(distance,both=both) # returns a Solid (or a compound if there were multiple) - - if combine: - newS = self._combineWithBase(r) - else: - newS = self.newObject([r]) - if clean: newS = newS.clean() - return newS - - def revolve(self, angleDegrees=360.0, axisStart=None, axisEnd=None, combine=True, clean=True): - """ - Use all un-revolved wires in the parent chain to create a solid. - - :param angleDegrees: the angle to revolve through. - :type angleDegrees: float, anything less than 360 degrees will leave the shape open - :param axisStart: the start point of the axis of rotation - :type axisStart: tuple, a two tuple - :param axisEnd: the end point of the axis of rotation - :type axisEnd: tuple, a two tuple - :param combine: True to combine the resulting solid with parent solids if found. - :type combine: boolean, combine with parent solid - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :return: a CQ object with the resulting solid selected. - - The returned object is always a CQ object, and depends on wither combine is True, and - whether a context solid is already defined: - - * if combine is False, the new value is pushed onto the stack. - * if combine is true, the value is combined with the context solid if it exists, - and the resulting solid becomes the new context solid. - """ - #Make sure we account for users specifying angles larger than 360 degrees - angleDegrees %= 360.0 - - #Compensate for FreeCAD not assuming that a 0 degree revolve means a 360 degree revolve - angleDegrees = 360.0 if angleDegrees == 0 else angleDegrees - - # The default start point of the vector defining the axis of rotation will be the origin - # of the workplane - if axisStart is None: - axisStart = self.plane.toWorldCoords((0, 0)).toTuple() - else: - axisStart = self.plane.toWorldCoords(axisStart).toTuple() - - # The default end point of the vector defining the axis of rotation should be along the - # normal from the plane - if axisEnd is None: - # Make sure we match the user's assumed axis of rotation if they specified an start - # but not an end - if axisStart[1] != 0: - axisEnd = self.plane.toWorldCoords((0, axisStart[1])).toTuple() - else: - axisEnd = self.plane.toWorldCoords((0, 1)).toTuple() - else: - axisEnd = self.plane.toWorldCoords(axisEnd).toTuple() - - # returns a Solid (or a compound if there were multiple) - r = self._revolve(angleDegrees, axisStart, axisEnd) - if combine: - newS = self._combineWithBase(r) - else: - newS = self.newObject([r]) - if clean: newS = newS.clean() - return newS - - def sweep(self, path, makeSolid=True, isFrenet=False, combine=True, clean=True): - """ - Use all un-extruded wires in the parent chain to create a swept solid. - - :param path: A wire along which the pending wires will be swept - :param boolean combine: True to combine the resulting solid with parent solids if found. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :return: a CQ object with the resulting solid selected. - """ - - r = self._sweep(path.wire(), makeSolid, isFrenet) # returns a Solid (or a compound if there were multiple) - if combine: - newS = self._combineWithBase(r) - else: - newS = self.newObject([r]) - if clean: newS = newS.clean() - return newS - - def _combineWithBase(self, obj): - """ - Combines the provided object with the base solid, if one can be found. - :param obj: - :return: a new object that represents the result of combining the base object with obj, - or obj if one could not be found - """ - baseSolid = self.findSolid(searchParents=True) - r = obj - if baseSolid is not None: - r = baseSolid.fuse(obj) - baseSolid.wrapped = r.wrapped - - return self.newObject([r]) - - def combine(self, clean=True): - """ - Attempts to combine all of the items on the stack into a single item. - WARNING: all of the items must be of the same type! - - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :raises: ValueError if there are no items on the stack, or if they cannot be combined - :return: a CQ object with the resulting object selected - """ - items = list(self.objects) - s = items.pop(0) - for ss in items: - s = s.fuse(ss) - - if clean: s = s.clean() - - return self.newObject([s]) - - def union(self, toUnion=None, combine=True, clean=True): - """ - Unions all of the items on the stack of toUnion with the current solid. - If there is no current solid, the items in toUnion are unioned together. - if combine=True, the result and the original are updated to point to the new object - if combine=False, the result will be on the stack, but the original is unmodified - - :param toUnion: - :type toUnion: a solid object, or a CQ object having a solid, - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :raises: ValueError if there is no solid to add to in the chain - :return: a CQ object with the resulting object selected - """ - - #first collect all of the items together - if type(toUnion) == CQ or type(toUnion) == Workplane: - solids = toUnion.solids().vals() - if len(solids) < 1: - raise ValueError("CQ object must have at least one solid on the stack to union!") - newS = solids.pop(0) - for s in solids: - newS = newS.fuse(s) - elif type(toUnion) == Solid: - newS = toUnion - else: - raise ValueError("Cannot union type '{}'".format(type(toUnion))) - - #now combine with existing solid, if there is one - # look for parents to cut from - solidRef = self.findSolid(searchStack=True, searchParents=True) - if combine and solidRef is not None: - r = solidRef.fuse(newS) - solidRef.wrapped = newS.wrapped - else: - r = newS - - if clean: r = r.clean() - - return self.newObject([r]) - - def cut(self, toCut, combine=True, clean=True): - """ - Cuts the provided solid from the current solid, IE, perform a solid subtraction - - if combine=True, the result and the original are updated to point to the new object - if combine=False, the result will be on the stack, but the original is unmodified - - :param toCut: object to cut - :type toCut: a solid object, or a CQ object having a solid, - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :raises: ValueError if there is no solid to subtract from in the chain - :return: a CQ object with the resulting object selected - """ - - # look for parents to cut from - solidRef = self.findSolid(searchStack=True, searchParents=True) - - if solidRef is None: - raise ValueError("Cannot find solid to cut from") - solidToCut = None - if type(toCut) == CQ or type(toCut) == Workplane: - solidToCut = toCut.val() - elif type(toCut) == Solid: - solidToCut = toCut - else: - raise ValueError("Cannot cut type '{}'".format(type(toCut))) - - newS = solidRef.cut(solidToCut) - - if clean: newS = newS.clean() - - if combine: - solidRef.wrapped = newS.wrapped - - return self.newObject([newS]) - - def cutBlind(self, distanceToCut, clean=True): - """ - Use all un-extruded wires in the parent chain to create a prismatic cut from existing solid. - - Similar to extrude, except that a solid in the parent chain is required to remove material - from. cutBlind always removes material from a part. - - :param distanceToCut: distance to extrude before cutting - :type distanceToCut: float, >0 means in the positive direction of the workplane normal, - <0 means in the negative direction - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :raises: ValueError if there is no solid to subtract from in the chain - :return: a CQ object with the resulting object selected - - see :py:meth:`cutThruAll` to cut material from the entire part - - Future Enhancements: - Cut Up to Surface - """ - #first, make the object - toCut = self._extrude(distanceToCut) - - #now find a solid in the chain - - solidRef = self.findSolid() - - s = solidRef.cut(toCut) - - if clean: s = s.clean() - - solidRef.wrapped = s.wrapped - return self.newObject([s]) - - def cutThruAll(self, positive=False, clean=True): - """ - Use all un-extruded wires in the parent chain to create a prismatic cut from existing solid. - - Similar to extrude, except that a solid in the parent chain is required to remove material - from. cutThruAll always removes material from a part. - - :param boolean positive: True to cut in the positive direction, false to cut in the - negative direction - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - :raises: ValueError if there is no solid to subtract from in the chain - :return: a CQ object with the resulting object selected - - see :py:meth:`cutBlind` to cut material to a limited depth - """ - maxDim = self.largestDimension() - if not positive: - maxDim *= (-1.0) - - return self.cutBlind(maxDim, clean) - - def loft(self, filled=True, ruled=False, combine=True): - """ - Make a lofted solid, through the set of wires. - :return: a CQ object containing the created loft - """ - wiresToLoft = self.ctx.pendingWires - self.ctx.pendingWires = [] - - r = Solid.makeLoft(wiresToLoft, ruled) - - if combine: - parentSolid = self.findSolid(searchStack=False, searchParents=True) - if parentSolid is not None: - r = parentSolid.fuse(r) - parentSolid.wrapped = r.wrapped - - return self.newObject([r]) - - def _extrude(self, distance, both=False): - """ - Make a prismatic solid from the existing set of pending wires. - - :param distance: distance to extrude - :param boolean both: extrude in both directions symmetrically - :return: a FreeCAD solid, suitable for boolean operations. - - This method is a utility method, primarily for plugin and internal use. - It is the basis for cutBlind,extrude,cutThruAll, and all similar methods. - - Future Enhancements: - extrude along a profile (sweep) - """ - - #group wires together into faces based on which ones are inside the others - #result is a list of lists - s = time.time() - wireSets = sortWiresByBuildOrder(list(self.ctx.pendingWires), self.plane, []) - #print "sorted wires in %d sec" % ( time.time() - s ) - self.ctx.pendingWires = [] # now all of the wires have been used to create an extrusion - - #compute extrusion vector and extrude - eDir = self.plane.zDir.multiply(distance) - - - #one would think that fusing faces into a compound and then extruding would work, - #but it doesnt-- the resulting compound appears to look right, ( right number of faces, etc) - #but then cutting it from the main solid fails with BRep_NotDone. - #the work around is to extrude each and then join the resulting solids, which seems to work - - # underlying cad kernel can only handle simple bosses-- we'll aggregate them if there are - # multiple sets - - # IMPORTANT NOTE: OCC is slow slow slow in boolean operations. So you do NOT want to fuse - # each item to another and save the result-- instead, you want to combine all of the new - # items into a compound, and fuse them together!!! - # r = None - # for ws in wireSets: - # thisObj = Solid.extrudeLinear(ws[0], ws[1:], eDir) - # if r is None: - # r = thisObj - # else: - # s = time.time() - # r = r.fuse(thisObj) - # print "Fused in %0.3f sec" % ( time.time() - s ) - # return r - - toFuse = [] - for ws in wireSets: - thisObj = Solid.extrudeLinear(ws[0], ws[1:], eDir) - toFuse.append(thisObj) - - if both: - thisObj = Solid.extrudeLinear(ws[0], ws[1:], eDir.multiply(-1.)) - toFuse.append(thisObj) - - return Compound.makeCompound(toFuse) - - def _revolve(self, angleDegrees, axisStart, axisEnd): - """ - Make a solid from the existing set of pending wires. - - :param angleDegrees: the angle to revolve through. - :type angleDegrees: float, anything less than 360 degrees will leave the shape open - :param axisStart: the start point of the axis of rotation - :type axisStart: tuple, a two tuple - :param axisEnd: the end point of the axis of rotation - :type axisEnd: tuple, a two tuple - :return: a FreeCAD solid, suitable for boolean operations. - - This method is a utility method, primarily for plugin and internal use. - """ - #We have to gather the wires to be revolved - wireSets = sortWiresByBuildOrder(list(self.ctx.pendingWires), self.plane, []) - - #Mark that all of the wires have been used to create a revolution - self.ctx.pendingWires = [] - - #Revolve the wires, make a compound out of them and then fuse them - toFuse = [] - for ws in wireSets: - thisObj = Solid.revolve(ws[0], ws[1:], angleDegrees, axisStart, axisEnd) - toFuse.append(thisObj) - - return Compound.makeCompound(toFuse) - - def _sweep(self, path, makeSolid=True, isFrenet=False): - """ - Makes a swept solid from an existing set of pending wires. - - :param path: A wire along which the pending wires will be swept - :return:a FreeCAD solid, suitable for boolean operations - """ - - # group wires together into faces based on which ones are inside the others - # result is a list of lists - s = time.time() - wireSets = sortWiresByBuildOrder(list(self.ctx.pendingWires), self.plane, []) - # print "sorted wires in %d sec" % ( time.time() - s ) - self.ctx.pendingWires = [] # now all of the wires have been used to create an extrusion - - toFuse = [] - for ws in wireSets: - thisObj = Solid.sweep(ws[0], ws[1:], path.val(), makeSolid, isFrenet) - toFuse.append(thisObj) - - return Compound.makeCompound(toFuse) - - def box(self, length, width, height, centered=(True, True, True), combine=True, clean=True): - """ - Return a 3d box with specified dimensions for each object on the stack. - - :param length: box size in X direction - :type length: float > 0 - :param width: box size in Y direction - :type width: float > 0 - :param height: box size in Z direction - :type height: float > 0 - :param centered: should the box be centered, or should reference point be at the lower - bound of the range? - :param combine: should the results be combined with other solids on the stack - (and each other)? - :type combine: true to combine shapes, false otherwise. - :param boolean clean: call :py:meth:`clean` afterwards to have a clean shape - - Centered is a tuple that describes whether the box should be centered on the x,y, and - z axes. If true, the box is centered on the respective axis relative to the workplane - origin, if false, the workplane center will represent the lower bound of the resulting box - - one box is created for each item on the current stack. If no items are on the stack, one box - using the current workplane center is created. - - If combine is true, the result will be a single object on the stack: - if a solid was found in the chain, the result is that solid with all boxes produced - fused onto it otherwise, the result is the combination of all the produced boxes - - if combine is false, the result will be a list of the boxes produced - - Most often boxes form the basis for a part:: - - #make a single box with lower left corner at origin - s = Workplane().box(1,2,3,centered=(False,False,False) - - But sometimes it is useful to create an array of them: - - #create 4 small square bumps on a larger base plate: - s = Workplane().box(4,4,0.5).faces(">Z").workplane()\ - .rect(3,3,forConstruction=True).vertices().box(0.25,0.25,0.25,combine=True) - - """ - - def _makebox(pnt): - - #(xp,yp,zp) = self.plane.toLocalCoords(pnt) - (xp, yp, zp) = pnt.toTuple() - if centered[0]: - xp -= (length / 2.0) - if centered[1]: - yp -= (width / 2.0) - if centered[2]: - zp -= (height / 2.0) - - return Solid.makeBox(length, width, height, Vector(xp, yp, zp)) - - boxes = self.eachpoint(_makebox, True) - - #if combination is not desired, just return the created boxes - if not combine: - return boxes - else: - #combine everything - return self.union(boxes, clean=clean) - - def sphere(self, radius, direct=(0, 0, 1), angle1=-90, angle2=90, angle3=360, - centered=(True, True, True), combine=True, clean=True): - """ - Returns a 3D sphere with the specified radius for each point on the stack - - :param radius: The radius of the sphere - :type radius: float > 0 - :param direct: The direction axis for the creation of the sphere - :type direct: A three-tuple - :param angle1: The first angle to sweep the sphere arc through - :type angle1: float > 0 - :param angle2: The second angle to sweep the sphere arc through - :type angle2: float > 0 - :param angle3: The third angle to sweep the sphere arc through - :type angle3: float > 0 - :param centered: A three-tuple of booleans that determines whether the sphere is centered - on each axis origin - :param combine: Whether the results should be combined with other solids on the stack - (and each other) - :type combine: true to combine shapes, false otherwise - :return: A sphere object for each point on the stack - - Centered is a tuple that describes whether the sphere should be centered on the x,y, and - z axes. If true, the sphere is centered on the respective axis relative to the workplane - origin, if false, the workplane center will represent the lower bound of the resulting - sphere. - - One sphere is created for each item on the current stack. If no items are on the stack, one - box using the current workplane center is created. - - If combine is true, the result will be a single object on the stack: - If a solid was found in the chain, the result is that solid with all spheres produced - fused onto it otherwise, the result is the combination of all the produced boxes - - If combine is false, the result will be a list of the spheres produced - """ - - # Convert the direction tuple to a vector, if needed - if isinstance(direct, tuple): - direct = Vector(direct) - - def _makesphere(pnt): - """ - Inner function that is used to create a sphere for each point/object on the workplane - :param pnt: The center point for the sphere - :return: A CQ Solid object representing a sphere - """ - (xp, yp, zp) = pnt.toTuple() - - if not centered[0]: - xp += radius - - if not centered[1]: - yp += radius - - if not centered[2]: - zp += radius - - return Solid.makeSphere(radius, Vector(xp, yp, zp), direct, angle1, angle2, angle3) - - # We want a sphere for each point on the workplane - spheres = self.eachpoint(_makesphere, True) - - # If we don't need to combine everything, just return the created spheres - if not combine: - return spheres - else: - return self.union(spheres, clean=clean) - - def clean(self): - """ - Cleans the current solid by removing unwanted edges from the - faces. - - Normally you don't have to call this function. It is - automatically called after each related operation. You can - disable this behavior with `clean=False` parameter if method - has any. In some cases this can improve performance - drastically but is generally dis-advised since it may break - some operations such as fillet. - - Note that in some cases where lots of solid operations are - chained, `clean()` may actually improve performance since - the shape is 'simplified' at each step and thus next operation - is easier. - - Also note that, due to limitation of the underlying engine, - `clean` may fail to produce a clean output in some cases such as - spherical faces. - """ - try: - cleanObjects = [obj.clean() for obj in self.objects] - except AttributeError: - raise AttributeError("%s object doesn't support `clean()` method!" % obj.ShapeType()) - return self.newObject(cleanObjects) diff --git a/Libs/cadquery-lib/cadquery/cq_directive.py b/Libs/cadquery-lib/cadquery/cq_directive.py deleted file mode 100644 index 0dc5fae..0000000 --- a/Libs/cadquery-lib/cadquery/cq_directive.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -A special directive for including a cq object. - -""" - -import traceback -from cadquery import * -from cadquery import cqgi -import StringIO -from docutils.parsers.rst import directives - -template = """ - -.. raw:: html - -
- %(out_svg)s -
-
-
- -""" -template_content_indent = ' ' - - -def cq_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - # only consider inline snippets - plot_code = '\n'.join(content) - - # Since we don't have a filename, use a hash based on the content - # the script must define a variable called 'out', which is expected to - # be a CQ object - out_svg = "Your Script Did not assign call build_output() function!" - - try: - _s = StringIO.StringIO() - result = cqgi.parse(plot_code).build() - - if result.success: - exporters.exportShape(result.first_result, "SVG", _s) - out_svg = _s.getvalue() - else: - raise result.exception - - except Exception: - traceback.print_exc() - out_svg = traceback.format_exc() - - # now out - # Now start generating the lines of output - lines = [] - - # get rid of new lines - out_svg = out_svg.replace('\n', '') - - txt_align = "left" - if "align" in options: - txt_align = options['align'] - - lines.extend((template % locals()).split('\n')) - - lines.extend(['::', '']) - lines.extend([' %s' % row.rstrip() - for row in plot_code.split('\n')]) - lines.append('') - - if len(lines): - state_machine.insert_input( - lines, state_machine.input_lines.source(0)) - - return [] - - -def setup(app): - setup.app = app - setup.config = app.config - setup.confdir = app.confdir - - options = {'height': directives.length_or_unitless, - 'width': directives.length_or_percentage_or_unitless, - 'align': directives.unchanged - } - - app.add_directive('cq_plot', cq_directive, True, (0, 2, 0), **options) diff --git a/Libs/cadquery-lib/cadquery/cqgi.py b/Libs/cadquery-lib/cadquery/cqgi.py deleted file mode 100644 index 01701db..0000000 --- a/Libs/cadquery-lib/cadquery/cqgi.py +++ /dev/null @@ -1,472 +0,0 @@ -""" -The CadQuery Gateway Interface. -Provides classes and tools for executing CadQuery scripts -""" -import ast -import traceback -import time -import cadquery - -CQSCRIPT = "" - -def parse(script_source): - """ - Parses the script as a model, and returns a model. - - If you would prefer to access the underlying model without building it, - for example, to inspect its available parameters, construct a CQModel object. - - :param script_source: the script to run. Must be a valid cadquery script - :return: a CQModel object that defines the script and allows execution - - """ - model = CQModel(script_source) - return model - - -class CQModel(object): - """ - Represents a Cadquery Script. - - After construction, the metadata property contains - a ScriptMetaData object, which describes the model in more detail, - and can be used to retrive the parameters defined by the model. - - the build method can be used to generate a 3d model - """ - - def __init__(self, script_source): - """ - Create an object by parsing the supplied python script. - :param script_source: a python script to parse - """ - self.metadata = ScriptMetadata() - self.ast_tree = ast.parse(script_source, CQSCRIPT) - self.script_source = script_source - self._find_vars() - - # TODO: pick up other scirpt metadata: - # describe - # pick up validation methods - self._find_descriptions() - - def _find_vars(self): - """ - Parse the script, and populate variables that appear to be - overridable. - """ - #assumption here: we assume that variable declarations - #are only at the top level of the script. IE, we'll ignore any - #variable definitions at lower levels of the script - - #we dont want to use the visit interface because here we excplicitly - #want to walk only the top level of the tree. - assignment_finder = ConstantAssignmentFinder(self.metadata) - - for node in self.ast_tree.body: - if isinstance(node, ast.Assign): - assignment_finder.visit_Assign(node) - - def _find_descriptions(self): - description_finder = ParameterDescriptionFinder(self.metadata) - description_finder.visit(self.ast_tree) - - def validate(self, params): - """ - Determine if the supplied parameters are valid. - NOT IMPLEMENTED YET-- raises NotImplementedError - :param params: a dictionary of parameters - - """ - raise NotImplementedError("not yet implemented") - - def build(self, build_parameters=None, build_options=None): - """ - Executes the script, using the optional parameters to override those in the model - :param build_parameters: a dictionary of variables. The variables must be - assignable to the underlying variable type. These variables override default values in the script - :param build_options: build options for how to build the model. Build options include things like - timeouts, tesselation tolerances, etc - :raises: Nothing. If there is an exception, it will be on the exception property of the result. - This is the interface so that we can return other information on the result, such as the build time - :return: a BuildResult object, which includes the status of the result, and either - a resulting shape or an exception - """ - if not build_parameters: - build_parameters = {} - - start = time.clock() - result = BuildResult() - - try: - self.set_param_values(build_parameters) - collector = ScriptCallback() - env = EnvironmentBuilder().with_real_builtins().with_cadquery_objects() \ - .add_entry("build_object", collector.build_object) \ - .add_entry("debug", collector.debug) \ - .add_entry("describe_parameter",collector.describe_parameter) \ - .build() - - c = compile(self.ast_tree, CQSCRIPT, 'exec') - exec (c, env) - result.set_debug(collector.debugObjects ) - if collector.has_results(): - result.set_success_result(collector.outputObjects) - else: - raise NoOutputError("Script did not call build_object-- no output available.") - except Exception, ex: - print "Error Executing Script:" - result.set_failure_result(ex) - traceback.print_exc() - print "Full Text of Script:" - print self.script_source - - end = time.clock() - result.buildTime = end - start - return result - - def set_param_values(self, params): - model_parameters = self.metadata.parameters - - for k, v in params.iteritems(): - if k not in model_parameters: - raise InvalidParameterError("Cannot set value '%s': not a parameter of the model." % k) - - p = model_parameters[k] - p.set_value(v) - - -class BuildResult(object): - """ - The result of executing a CadQuery script. - The success property contains whether the exeuction was successful. - - If successful, the results property contains a list of all results, - and the first_result property contains the first result. - - If unsuccessful, the exception property contains a reference to - the stack trace that occurred. - """ - def __init__(self): - self.buildTime = None - self.results = [] - self.debugObjects = [] - self.first_result = None - self.success = False - self.exception = None - - def set_failure_result(self, ex): - self.exception = ex - self.success = False - - def set_debug(self, debugObjects): - self.debugObjects = debugObjects - - def set_success_result(self, results): - self.results = results - self.first_result = self.results[0] - self.success = True - - -class ScriptMetadata(object): - """ - Defines the metadata for a parsed CQ Script. - the parameters property is a dict of InputParameter objects. - """ - def __init__(self): - self.parameters = {} - - def add_script_parameter(self, p): - self.parameters[p.name] = p - - def add_parameter_description(self,name,description): - print 'Adding Parameter name=%s, desc=%s' % ( name, description ) - p = self.parameters[name] - p.desc = description - - -class ParameterType(object): - pass - - -class NumberParameterType(ParameterType): - pass - - -class StringParameterType(ParameterType): - pass - - -class BooleanParameterType(ParameterType): - pass - - -class InputParameter: - """ - Defines a parameter that can be supplied when the model is executed. - - Name, varType, and default_value are always available, because they are computed - from a variable assignment line of code: - - The others are only available if the script has used define_parameter() to - provide additional metadata - - """ - def __init__(self): - - #: the default value for the variable. - self.default_value = None - - #: the name of the parameter. - self.name = None - - #: type of the variable: BooleanParameter, StringParameter, NumericParameter - self.varType = None - - #: help text describing the variable. Only available if the script used describe_parameter() - self.desc = None - - #: valid values for the variable. Only available if the script used describe_parameter() - self.valid_values = [] - - self.ast_node = None - - @staticmethod - def create(ast_node, var_name, var_type, default_value, valid_values=None, desc=None): - - if valid_values is None: - valid_values = [] - - p = InputParameter() - p.ast_node = ast_node - p.default_value = default_value - p.name = var_name - p.desc = desc - p.varType = var_type - p.valid_values = valid_values - return p - - def set_value(self, new_value): - - if len(self.valid_values) > 0 and new_value not in self.valid_values: - raise InvalidParameterError( - "Cannot set value '{0:s}' for parameter '{1:s}': not a valid value. Valid values are {2:s} " - .format(str(new_value), self.name, str(self.valid_values))) - - if self.varType == NumberParameterType: - try: - f = float(new_value) - self.ast_node.n = f - except ValueError: - raise InvalidParameterError( - "Cannot set value '{0:s}' for parameter '{1:s}': parameter must be numeric." - .format(str(new_value), self.name)) - - elif self.varType == StringParameterType: - self.ast_node.s = str(new_value) - elif self.varType == BooleanParameterType: - if new_value: - self.ast_node.id = 'True' - else: - self.ast_node.id = 'False' - else: - raise ValueError("Unknown Type of var: ", str(self.varType)) - - def __str__(self): - return "InputParameter: {name=%s, type=%s, defaultValue=%s" % ( - self.name, str(self.varType), str(self.default_value)) - - -class ScriptCallback(object): - """ - Allows a script to communicate with the container - the build_object() method is exposed to CQ scripts, to allow them - to return objects to the execution environment - """ - def __init__(self): - self.outputObjects = [] - self.debugObjects = [] - - def build_object(self, shape): - """ - return an object to the executing environment - :param shape: a cadquery object - """ - self.outputObjects.append(shape) - - def debug(self,obj,args={}): - """ - Debug print/output an object, with optional arguments. - """ - self.debugObjects.append(DebugObject(obj,args)) - - def describe_parameter(self,var_data ): - """ - Do Nothing-- we parsed the ast ahead of exection to get what we need. - """ - pass - - def add_error(self, param, field_list): - """ - Not implemented yet: allows scripts to indicate that there are problems with inputs - """ - pass - - def has_results(self): - return len(self.outputObjects) > 0 - -class DebugObject(object): - """ - Represents a request to debug an object - Object is the type of object we want to debug - args are parameters for use during debuging ( for example, color, tranparency ) - """ - def __init__(self,object,args): - self.args = args - self.object = object - -class InvalidParameterError(Exception): - """ - Raised when an attempt is made to provide a new parameter value - that cannot be assigned to the model - """ - pass - - -class NoOutputError(Exception): - """ - Raised when the script does not execute the build_object() method to - return a solid - """ - pass - - -class ScriptExecutionError(Exception): - """ - Represents a script syntax error. - Useful for helping clients pinpoint issues with the script - interactively - """ - - def __init__(self, line=None, message=None): - if line is None: - self.line = 0 - else: - self.line = line - - if message is None: - self.message = "Unknown Script Error" - else: - self.message = message - - def full_message(self): - return self.__repr__() - - def __str__(self): - return self.__repr__() - - def __repr__(self): - return "ScriptError [Line %s]: %s" % (self.line, self.message) - - -class EnvironmentBuilder(object): - """ - Builds an execution environment for a cadquery script. - The environment includes the builtins, as well as - the other methods the script will need. - """ - def __init__(self): - self.env = {} - - def with_real_builtins(self): - return self.with_builtins(__builtins__) - - def with_builtins(self, env_dict): - self.env['__builtins__'] = env_dict - return self - - def with_cadquery_objects(self): - self.env['cadquery'] = cadquery - self.env['cq'] = cadquery - return self - - def add_entry(self, name, value): - self.env[name] = value - return self - - def build(self): - return self.env - -class ParameterDescriptionFinder(ast.NodeTransformer): - """ - Visits a parse tree, looking for function calls to describe_parameter(var, description ) - """ - def __init__(self, cq_model): - self.cqModel = cq_model - - def visit_Call(self,node): - """ - Called when we see a function call. Is it describe_parameter? - """ - try: - if node.func.id == 'describe_parameter': - #looks like we have a call to our function. - #first parameter is the variable, - #second is the description - varname = node.args[0].id - desc = node.args[1].s - self.cqModel.add_parameter_description(varname,desc) - - except: - print "Unable to handle function call" - pass - return node - -class ConstantAssignmentFinder(ast.NodeTransformer): - """ - Visits a parse tree, and adds script parameters to the cqModel - """ - - def __init__(self, cq_model): - self.cqModel = cq_model - - def handle_assignment(self, var_name, value_node): - try: - - if type(value_node) == ast.Num: - self.cqModel.add_script_parameter( - InputParameter.create(value_node, var_name, NumberParameterType, value_node.n)) - elif type(value_node) == ast.Str: - self.cqModel.add_script_parameter( - InputParameter.create(value_node, var_name, StringParameterType, value_node.s)) - elif type(value_node == ast.Name): - if value_node.id == 'True': - self.cqModel.add_script_parameter( - InputParameter.create(value_node, var_name, BooleanParameterType, True)) - elif value_node.id == 'False': - self.cqModel.add_script_parameter( - InputParameter.create(value_node, var_name, BooleanParameterType, True)) - except: - print "Unable to handle assignment for variable '%s'" % var_name - pass - - def visit_Assign(self, node): - - try: - left_side = node.targets[0] - - #do not handle attribute assignments - if isinstance(left_side,ast.Attribute): - return - - if type(node.value) in [ast.Num, ast.Str, ast.Name]: - self.handle_assignment(left_side.id, node.value) - elif type(node.value) == ast.Tuple: - # we have a multi-value assignment - for n, v in zip(left_side.elts, node.value.elts): - self.handle_assignment(n.id, v) - except: - traceback.print_exc() - print "Unable to handle assignment for node '%s'" % ast.dump(left_side) - - return node diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/README.txt b/Libs/cadquery-lib/cadquery/freecad_impl/README.txt deleted file mode 100644 index 34ea788..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -It is ok for files in this directory to import FreeCAD, FreeCAD.Base, and FreeCAD.Part. - -Other modules should _not_ depend on FreeCAD \ No newline at end of file diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/__init__.py b/Libs/cadquery-lib/cadquery/freecad_impl/__init__.py deleted file mode 100644 index 05ed957..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/__init__.py +++ /dev/null @@ -1,106 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see -""" -import os -import sys - - -def _fc_path(): - """Find FreeCAD""" - # Look for FREECAD_LIB env variable - _PATH = os.environ.get('FREECAD_LIB', '') - if _PATH and os.path.exists(_PATH): - return _PATH - - if sys.platform.startswith('linux'): - # Make some dangerous assumptions... - for _PATH in [ - os.path.join(os.path.expanduser("~"), "lib/freecad/lib"), - "/usr/local/lib/freecad/lib", - "/usr/lib/freecad/lib", - "/opt/freecad/lib/", - "/usr/bin/freecad/lib", - "/usr/lib/freecad", - "/usr/lib64/freecad/lib", - ]: - if os.path.exists(_PATH): - return _PATH - - elif sys.platform.startswith('win'): - # Try all the usual suspects - for _PATH in [ - "c:/Program Files/FreeCAD0.12/bin", - "c:/Program Files/FreeCAD0.13/bin", - "c:/Program Files/FreeCAD0.14/bin", - "c:/Program Files/FreeCAD0.15/bin", - "c:/Program Files/FreeCAD0.16/bin", - "c:/Program Files/FreeCAD0.17/bin", - "c:/Program Files (x86)/FreeCAD0.12/bin", - "c:/Program Files (x86)/FreeCAD0.13/bin", - "c:/Program Files (x86)/FreeCAD0.14/bin", - "c:/Program Files (x86)/FreeCAD0.15/bin", - "c:/Program Files (x86)/FreeCAD0.16/bin", - "c:/Program Files (x86)/FreeCAD0.17/bin", - "c:/apps/FreeCAD0.12/bin", - "c:/apps/FreeCAD0.13/bin", - "c:/apps/FreeCAD0.14/bin", - "c:/apps/FreeCAD0.15/bin", - "c:/apps/FreeCAD0.16/bin", - "c:/apps/FreeCAD0.17/bin", - "c:/Program Files/FreeCAD 0.12/bin", - "c:/Program Files/FreeCAD 0.13/bin", - "c:/Program Files/FreeCAD 0.14/bin", - "c:/Program Files/FreeCAD 0.15/bin", - "c:/Program Files/FreeCAD 0.16/bin", - "c:/Program Files/FreeCAD 0.17/bin", - "c:/Program Files (x86)/FreeCAD 0.12/bin", - "c:/Program Files (x86)/FreeCAD 0.13/bin", - "c:/Program Files (x86)/FreeCAD 0.14/bin", - "c:/Program Files (x86)/FreeCAD 0.15/bin", - "c:/Program Files (x86)/FreeCAD 0.16/bin", - "c:/Program Files (x86)/FreeCAD 0.17/bin", - "c:/apps/FreeCAD 0.12/bin", - "c:/apps/FreeCAD 0.13/bin", - "c:/apps/FreeCAD 0.14/bin", - "c:/apps/FreeCAD 0.15/bin", - "c:/apps/FreeCAD 0.16/bin", - "c:/apps/FreeCAD 0.17/bin", - ]: - if os.path.exists(_PATH): - return _PATH - - elif sys.platform.startswith('darwin'): - # Assume we're dealing with a Mac - for _PATH in [ - "/Applications/FreeCAD.app/Contents/lib", - os.path.join(os.path.expanduser("~"), - "Library/Application Support/FreeCAD/lib"), - ]: - if os.path.exists(_PATH): - return _PATH - - raise ImportError('cadquery was unable to determine freecad library path') - - -# Make sure that the correct FreeCAD path shows up in Python's system path -try: - import FreeCAD -except ImportError: - path = _fc_path() - sys.path.insert(0, path) - import FreeCAD diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/exporters.py b/Libs/cadquery-lib/cadquery/freecad_impl/exporters.py deleted file mode 100644 index c4b097a..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/exporters.py +++ /dev/null @@ -1,392 +0,0 @@ -import cadquery - -import FreeCAD -import Drawing - -import tempfile, os, StringIO - - -try: - import xml.etree.cElementTree as ET -except ImportError: - import xml.etree.ElementTree as ET - - -class ExportTypes: - STL = "STL" - STEP = "STEP" - AMF = "AMF" - SVG = "SVG" - TJS = "TJS" - - -class UNITS: - MM = "mm" - IN = "in" - - -def toString(shape, exportType, tolerance=0.1): - s = StringIO.StringIO() - exportShape(shape, exportType, s, tolerance) - return s.getvalue() - - -def exportShape(shape,exportType,fileLike,tolerance=0.1): - """ - :param shape: the shape to export. it can be a shape object, or a cadquery object. If a cadquery - object, the first value is exported - :param exportFormat: the exportFormat to use - :param tolerance: the tolerance, in model units - :param fileLike: a file like object to which the content will be written. - The object should be already open and ready to write. The caller is responsible - for closing the object - """ - - - if isinstance(shape,cadquery.CQ): - shape = shape.val() - - if exportType == ExportTypes.TJS: - #tessellate the model - tess = shape.tessellate(tolerance) - - mesher = JsonMesh() #warning: needs to be changed to remove buildTime and exportTime!!! - #add vertices - for vec in tess[0]: - mesher.addVertex(vec.x, vec.y, vec.z) - - #add faces - for f in tess[1]: - mesher.addTriangleFace(f[0],f[1], f[2]) - fileLike.write( mesher.toJson()) - elif exportType == ExportTypes.SVG: - fileLike.write(getSVG(shape.wrapped)) - elif exportType == ExportTypes.AMF: - tess = shape.tessellate(tolerance) - aw = AmfWriter(tess).writeAmf(fileLike) - else: - - #all these types required writing to a file and then - #re-reading. this is due to the fact that FreeCAD writes these - (h, outFileName) = tempfile.mkstemp() - #weird, but we need to close this file. the next step is going to write to - #it from c code, so it needs to be closed. - os.close(h) - - if exportType == ExportTypes.STEP: - shape.exportStep(outFileName) - elif exportType == ExportTypes.STL: - shape.wrapped.exportStl(outFileName) - else: - raise ValueError("No idea how i got here") - - res = readAndDeleteFile(outFileName) - fileLike.write(res) - -def readAndDeleteFile(fileName): - """ - read data from file provided, and delete it when done - return the contents as a string - """ - res = "" - with open(fileName,'r') as f: - res = f.read() - - os.remove(fileName) - return res - - -def guessUnitOfMeasure(shape): - """ - Guess the unit of measure of a shape. - """ - bb = shape.BoundBox - - dimList = [ bb.XLength, bb.YLength,bb.ZLength ] - #no real part would likely be bigger than 10 inches on any side - if max(dimList) > 10: - return UNITS.MM - - #no real part would likely be smaller than 0.1 mm on all dimensions - if min(dimList) < 0.1: - return UNITS.IN - - #no real part would have the sum of its dimensions less than about 5mm - if sum(dimList) < 10: - return UNITS.IN - - return UNITS.MM - - -class AmfWriter(object): - def __init__(self,tessellation): - - self.units = "mm" - self.tessellation = tessellation - - def writeAmf(self,outFile): - amf = ET.Element('amf',units=self.units) - #TODO: if result is a compound, we need to loop through them - object = ET.SubElement(amf,'object',id="0") - mesh = ET.SubElement(object,'mesh') - vertices = ET.SubElement(mesh,'vertices') - volume = ET.SubElement(mesh,'volume') - - #add vertices - for v in self.tessellation[0]: - vtx = ET.SubElement(vertices,'vertex') - coord = ET.SubElement(vtx,'coordinates') - x = ET.SubElement(coord,'x') - x.text = str(v.x) - y = ET.SubElement(coord,'y') - y.text = str(v.y) - z = ET.SubElement(coord,'z') - z.text = str(v.z) - - #add triangles - for t in self.tessellation[1]: - triangle = ET.SubElement(volume,'triangle') - v1 = ET.SubElement(triangle,'v1') - v1.text = str(t[0]) - v2 = ET.SubElement(triangle,'v2') - v2.text = str(t[1]) - v3 = ET.SubElement(triangle,'v3') - v3.text = str(t[2]) - - - ET.ElementTree(amf).write(outFile,encoding='ISO-8859-1') - -""" - Objects that represent - three.js JSON object notation - https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3.0 -""" -class JsonMesh(object): - def __init__(self): - - self.vertices = []; - self.faces = []; - self.nVertices = 0; - self.nFaces = 0; - - def addVertex(self,x,y,z): - self.nVertices += 1; - self.vertices.extend([x,y,z]); - - #add triangle composed of the three provided vertex indices - def addTriangleFace(self, i,j,k): - #first position means justa simple triangle - self.nFaces += 1; - self.faces.extend([0,int(i),int(j),int(k)]); - - """ - Get a json model from this model. - For now we'll forget about colors, vertex normals, and all that stuff - """ - def toJson(self): - return JSON_TEMPLATE % { - 'vertices' : str(self.vertices), - 'faces' : str(self.faces), - 'nVertices': self.nVertices, - 'nFaces' : self.nFaces - }; - - -def getPaths(freeCadSVG): - """ - freeCad svg is worthless-- except for paths, which are fairly useful - this method accepts svg from fReeCAD and returns a list of strings suitable for inclusion in a path element - returns two lists-- one list of visible lines, and one list of hidden lines - - HACK ALERT!!!!! - FreeCAD does not give a way to determine which lines are hidden and which are not - the only way to tell is that hidden lines are in a with 0.15 stroke and visible are 0.35 stroke. - so we actually look for that as a way to parse. - - to make it worse, elementTree xpath attribute selectors do not work in python 2.6, and we - cannot use python 2.7 due to freecad. So its necessary to look for the pure strings! ick! - """ - - hiddenPaths = [] - visiblePaths = [] - if len(freeCadSVG) > 0: - #yuk, freecad returns svg fragments. stupid stupid - fullDoc = "%s" % freeCadSVG - e = ET.ElementTree(ET.fromstring(fullDoc)) - segments = e.findall(".//g") - for s in segments: - paths = s.findall("path") - - if s.get("stroke-width") == "0.15": #hidden line HACK HACK HACK - mylist = hiddenPaths - else: - mylist = visiblePaths - - for p in paths: - mylist.append(p.get("d")) - return (hiddenPaths,visiblePaths) - else: - return ([],[]) - - -def getSVG(shape,opts=None): - """ - Export a shape to SVG - """ - - d = {'width':800,'height':240,'marginLeft':200,'marginTop':20} - - if opts: - d.update(opts) - - #need to guess the scale and the coordinate center - uom = guessUnitOfMeasure(shape) - - width=float(d['width']) - height=float(d['height']) - marginLeft=float(d['marginLeft']) - marginTop=float(d['marginTop']) - - #TODO: provide option to give 3 views - viewVector = FreeCAD.Base.Vector(-1.75,1.1,5) - (visibleG0,visibleG1,hiddenG0,hiddenG1) = Drawing.project(shape,viewVector) - - (hiddenPaths,visiblePaths) = getPaths(Drawing.projectToSVG(shape,viewVector,"ShowHiddenLines")) #this param is totally undocumented! - - #get bounding box -- these are all in 2-d space - bb = visibleG0.BoundBox - bb.add(visibleG1.BoundBox) - bb.add(hiddenG0.BoundBox) - bb.add(hiddenG1.BoundBox) - - #width pixels for x, height pixesl for y - unitScale = min( width / bb.XLength * 0.75 , height / bb.YLength * 0.75 ) - - #compute amount to translate-- move the top left into view - (xTranslate,yTranslate) = ( (0 - bb.XMin) + marginLeft/unitScale ,(0- bb.YMax) - marginTop/unitScale) - - #compute paths ( again -- had to strip out freecad crap ) - hiddenContent = "" - for p in hiddenPaths: - hiddenContent += PATHTEMPLATE % p - - visibleContent = "" - for p in visiblePaths: - visibleContent += PATHTEMPLATE % p - - svg = SVG_TEMPLATE % ( - { - "unitScale" : str(unitScale), - "strokeWidth" : str(1.0/unitScale), - "hiddenContent" : hiddenContent , - "visibleContent" :visibleContent, - "xTranslate" : str(xTranslate), - "yTranslate" : str(yTranslate), - "width" : str(width), - "height" : str(height), - "textboxY" :str(height - 30), - "uom" : str(uom) - } - ) - #svg = SVG_TEMPLATE % ( - # {"content": projectedContent} - #) - return svg - - -def exportSVG(shape, fileName): - """ - accept a cadquery shape, and export it to the provided file - TODO: should use file-like objects, not a fileName, and/or be able to return a string instead - export a view of a part to svg - """ - - svg = getSVG(shape.val().wrapped) - f = open(fileName,'w') - f.write(svg) - f.close() - - - -JSON_TEMPLATE= """\ -{ - "metadata" : - { - "formatVersion" : 3, - "generatedBy" : "ParametricParts", - "vertices" : %(nVertices)d, - "faces" : %(nFaces)d, - "normals" : 0, - "colors" : 0, - "uvs" : 0, - "materials" : 1, - "morphTargets" : 0 - }, - - "scale" : 1.0, - - "materials": [ { - "DbgColor" : 15658734, - "DbgIndex" : 0, - "DbgName" : "Material", - "colorAmbient" : [0.0, 0.0, 0.0], - "colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], - "colorSpecular" : [0.5, 0.5, 0.5], - "shading" : "Lambert", - "specularCoef" : 50, - "transparency" : 1.0, - "vertexColors" : false - }], - - "vertices": %(vertices)s, - - "morphTargets": [], - - "normals": [], - - "colors": [], - - "uvs": [[]], - - "faces": %(faces)s -} -""" - -SVG_TEMPLATE = """ - - - - -%(hiddenContent)s - - - - -%(visibleContent)s - - - - - X - - - Y - - - Z - - - -""" - -PATHTEMPLATE="\t\t\t\n" - diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/geom.py b/Libs/cadquery-lib/cadquery/freecad_impl/geom.py deleted file mode 100644 index 2bd8c3a..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/geom.py +++ /dev/null @@ -1,647 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see -""" - -import math -import cadquery -import FreeCAD -import Part as FreeCADPart - - -def sortWiresByBuildOrder(wireList, plane, result=[]): - """Tries to determine how wires should be combined into faces. - - Assume: - The wires make up one or more faces, which could have 'holes' - Outer wires are listed ahead of inner wires - there are no wires inside wires inside wires - ( IE, islands -- we can deal with that later on ) - none of the wires are construction wires - - Compute: - one or more sets of wires, with the outer wire listed first, and inner - ones - - Returns, list of lists. - """ - result = [] - - remainingWires = list(wireList) - while remainingWires: - outerWire = remainingWires.pop(0) - group = [outerWire] - otherWires = list(remainingWires) - for w in otherWires: - if plane.isWireInside(outerWire, w): - group.append(w) - remainingWires.remove(w) - result.append(group) - - return result - - -class Vector(object): - """Create a 3-dimensional vector - - :param args: a 3-d vector, with x-y-z parts. - - you can either provide: - * nothing (in which case the null vector is return) - * a FreeCAD vector - * a vector ( in which case it is copied ) - * a 3-tuple - * three float values, x, y, and z - """ - def __init__(self, *args): - if len(args) == 3: - fV = FreeCAD.Base.Vector(args[0], args[1], args[2]) - elif len(args) == 1: - if isinstance(args[0], Vector): - fV = args[0].wrapped - elif isinstance(args[0], tuple): - fV = FreeCAD.Base.Vector(args[0][0], args[0][1], args[0][2]) - elif isinstance(args[0], FreeCAD.Base.Vector): - fV = args[0] - else: - fV = args[0] - elif len(args) == 0: - fV = FreeCAD.Base.Vector(0, 0, 0) - else: - raise ValueError("Expected three floats, FreeCAD Vector, or 3-tuple") - - self._wrapped = fV - - @property - def x(self): - return self.wrapped.x - - @property - def y(self): - return self.wrapped.y - - @property - def z(self): - return self.wrapped.z - - @property - def Length(self): - return self.wrapped.Length - - @property - def wrapped(self): - return self._wrapped - - def toTuple(self): - return (self.x, self.y, self.z) - - # TODO: is it possible to create a dynamic proxy without all this code? - def cross(self, v): - return Vector(self.wrapped.cross(v.wrapped)) - - def dot(self, v): - return self.wrapped.dot(v.wrapped) - - def sub(self, v): - return Vector(self.wrapped.sub(v.wrapped)) - - def add(self, v): - return Vector(self.wrapped.add(v.wrapped)) - - def multiply(self, scale): - """Return a copy multiplied by the provided scalar""" - tmp_fc_vector = FreeCAD.Base.Vector(self.wrapped) - return Vector(tmp_fc_vector.multiply(scale)) - - def normalized(self): - """Return a normalized version of this vector""" - tmp_fc_vector = FreeCAD.Base.Vector(self.wrapped) - tmp_fc_vector.normalize() - return Vector(tmp_fc_vector) - - def Center(self): - """Return the vector itself - - The center of myself is myself. - Provided so that vectors, vertexes, and other shapes all support a - common interface, when Center() is requested for all objects on the - stack. - """ - return self - - def getAngle(self, v): - return self.wrapped.getAngle(v.wrapped) - - def distanceToLine(self): - raise NotImplementedError("Have not needed this yet, but FreeCAD supports it!") - - def projectToLine(self): - raise NotImplementedError("Have not needed this yet, but FreeCAD supports it!") - - def distanceToPlane(self): - raise NotImplementedError("Have not needed this yet, but FreeCAD supports it!") - - def projectToPlane(self): - raise NotImplementedError("Have not needed this yet, but FreeCAD supports it!") - - def __add__(self, v): - return self.add(v) - - def __repr__(self): - return self.wrapped.__repr__() - - def __str__(self): - return self.wrapped.__str__() - - def __ne__(self, other): - return self.wrapped.__ne__(other) - - def __eq__(self, other): - return self.wrapped.__eq__(other) - - -class Matrix: - """A 3d , 4x4 transformation matrix. - - Used to move geometry in space. - """ - def __init__(self, matrix=None): - if matrix is None: - self.wrapped = FreeCAD.Base.Matrix() - else: - self.wrapped = matrix - - def rotateX(self, angle): - self.wrapped.rotateX(angle) - - def rotateY(self, angle): - self.wrapped.rotateY(angle) - - -class Plane(object): - """A 2D coordinate system in space - - A 2D coordinate system in space, with the x-y axes on the plane, and a - particular point as the origin. - - A plane allows the use of 2-d coordinates, which are later converted to - global, 3d coordinates when the operations are complete. - - Frequently, it is not necessary to create work planes, as they can be - created automatically from faces. - """ - - @classmethod - def named(cls, stdName, origin=(0, 0, 0)): - """Create a predefined Plane based on the conventional names. - - :param stdName: one of (XY|YZ|ZX|XZ|YX|ZY|front|back|left|right|top|bottom) - :type stdName: string - :param origin: the desired origin, specified in global coordinates - :type origin: 3-tuple of the origin of the new plane, in global coorindates. - - Available named planes are as follows. Direction references refer to - the global directions. - - =========== ======= ======= ====== - Name xDir yDir zDir - =========== ======= ======= ====== - XY +x +y +z - YZ +y +z +x - ZX +z +x +y - XZ +x +z -y - YX +y +x -z - ZY +z +y -x - front +x +y +z - back -x +y -z - left +z +y -x - right -z +y +x - top +x -z +y - bottom +x +z -y - =========== ======= ======= ====== - """ - - namedPlanes = { - # origin, xDir, normal - 'XY': Plane(origin, (1, 0, 0), (0, 0, 1)), - 'YZ': Plane(origin, (0, 1, 0), (1, 0, 0)), - 'ZX': Plane(origin, (0, 0, 1), (0, 1, 0)), - 'XZ': Plane(origin, (1, 0, 0), (0, -1, 0)), - 'YX': Plane(origin, (0, 1, 0), (0, 0, -1)), - 'ZY': Plane(origin, (0, 0, 1), (-1, 0, 0)), - 'front': Plane(origin, (1, 0, 0), (0, 0, 1)), - 'back': Plane(origin, (-1, 0, 0), (0, 0, -1)), - 'left': Plane(origin, (0, 0, 1), (-1, 0, 0)), - 'right': Plane(origin, (0, 0, -1), (1, 0, 0)), - 'top': Plane(origin, (1, 0, 0), (0, 1, 0)), - 'bottom': Plane(origin, (1, 0, 0), (0, -1, 0)) - } - - try: - return namedPlanes[stdName] - except KeyError: - raise ValueError('Supported names are {}'.format( - namedPlanes.keys())) - - @classmethod - def XY(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)): - plane = Plane.named('XY', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def YZ(cls, origin=(0, 0, 0), xDir=Vector(0, 1, 0)): - plane = Plane.named('YZ', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def ZX(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)): - plane = Plane.named('ZX', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def XZ(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)): - plane = Plane.named('XZ', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def YX(cls, origin=(0, 0, 0), xDir=Vector(0, 1, 0)): - plane = Plane.named('YX', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def ZY(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)): - plane = Plane.named('ZY', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def front(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)): - plane = Plane.named('front', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def back(cls, origin=(0, 0, 0), xDir=Vector(-1, 0, 0)): - plane = Plane.named('back', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def left(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)): - plane = Plane.named('left', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def right(cls, origin=(0, 0, 0), xDir=Vector(0, 0, -1)): - plane = Plane.named('right', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def top(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)): - plane = Plane.named('top', origin) - plane._setPlaneDir(xDir) - return plane - - @classmethod - def bottom(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)): - plane = Plane.named('bottom', origin) - plane._setPlaneDir(xDir) - return plane - - def __init__(self, origin, xDir, normal): - """Create a Plane with an arbitrary orientation - - TODO: project x and y vectors so they work even if not orthogonal - :param origin: the origin - :type origin: a three-tuple of the origin, in global coordinates - :param xDir: a vector representing the xDirection. - :type xDir: a three-tuple representing a vector, or a FreeCAD Vector - :param normal: the normal direction for the new plane - :type normal: a FreeCAD Vector - :raises: ValueError if the specified xDir is not orthogonal to the provided normal. - :return: a plane in the global space, with the xDirection of the plane in the specified direction. - """ - normal = Vector(normal) - if (normal.Length == 0.0): - raise ValueError('normal should be non null') - self.zDir = normal.normalized() - xDir = Vector(xDir) - if (xDir.Length == 0.0): - raise ValueError('xDir should be non null') - self._setPlaneDir(xDir) - - self.invZDir = self.zDir.multiply(-1.0) - - self.origin = origin - - @property - def origin(self): - return self._origin - - @origin.setter - def origin(self, value): - self._origin = Vector(value) - self._calcTransforms() - - def setOrigin2d(self, x, y): - """ - Set a new origin in the plane itself - - Set a new origin in the plane itself. The plane's orientation and - xDrection are unaffected. - - :param float x: offset in the x direction - :param float y: offset in the y direction - :return: void - - The new coordinates are specified in terms of the current 2-d system. - As an example: - - p = Plane.XY() - p.setOrigin2d(2, 2) - p.setOrigin2d(2, 2) - - results in a plane with its origin at (x, y) = (4, 4) in global - coordinates. Both operations were relative to local coordinates of the - plane. - """ - self.origin = self.toWorldCoords((x, y)) - - def isWireInside(self, baseWire, testWire): - """Determine if testWire is inside baseWire - - Determine if testWire is inside baseWire, after both wires are projected - into the current plane. - - :param baseWire: a reference wire - :type baseWire: a FreeCAD wire - :param testWire: another wire - :type testWire: a FreeCAD wire - :return: True if testWire is inside baseWire, otherwise False - - If either wire does not lie in the current plane, it is projected into - the plane first. - - *WARNING*: This method is not 100% reliable. It uses bounding box - tests, but needs more work to check for cases when curves are complex. - - Future Enhancements: - * Discretizing points along each curve to provide a more reliable - test. - """ - # TODO: also use a set of points along the wire to test as well. - # TODO: would it be more efficient to create objects in the local - # coordinate system, and then transform to global - # coordinates upon extrusion? - - tBaseWire = baseWire.transformGeometry(self.fG) - tTestWire = testWire.transformGeometry(self.fG) - - # These bounding boxes will have z=0, since we transformed them into the - # space of the plane. - bb = tBaseWire.BoundingBox() - tb = tTestWire.BoundingBox() - - # findOutsideBox actually inspects both ways, here we only want to - # know if one is inside the other - return bb == BoundBox.findOutsideBox2D(bb, tb) - - def toLocalCoords(self, obj): - """Project the provided coordinates onto this plane - - :param obj: an object or vector to convert - :type vector: a vector or shape - :return: an object of the same type, but converted to local coordinates - - - Most of the time, the z-coordinate returned will be zero, because most - operations based on a plane are all 2-d. Occasionally, though, 3-d - points outside of the current plane are transformed. One such example is - :py:meth:`Workplane.box`, where 3-d corners of a box are transformed to - orient the box in space correctly. - - """ - if isinstance(obj, Vector): - return Vector(self.fG.multiply(obj.wrapped)) - elif isinstance(obj, cadquery.Shape): - return obj.transformShape(self.rG) - else: - raise ValueError( - "Don't know how to convert type {} to local coordinates".format( - type(obj))) - - def toWorldCoords(self, tuplePoint): - """Convert a point in local coordinates to global coordinates - - :param tuplePoint: point in local coordinates to convert. - :type tuplePoint: a 2 or three tuple of float. The third value is taken to be zero if not supplied. - :return: a Vector in global coordinates - """ - if isinstance(tuplePoint, Vector): - v = tuplePoint - elif len(tuplePoint) == 2: - v = Vector(tuplePoint[0], tuplePoint[1], 0) - else: - v = Vector(tuplePoint) - return Vector(self.rG.multiply(v.wrapped)) - - def rotated(self, rotate=(0, 0, 0)): - """Returns a copy of this plane, rotated about the specified axes - - Since the z axis is always normal the plane, rotating around Z will - always produce a plane that is parallel to this one. - - The origin of the workplane is unaffected by the rotation. - - Rotations are done in order x, y, z. If you need a different order, - manually chain together multiple rotate() commands. - - :param rotate: Vector [xDegrees, yDegrees, zDegrees] - :return: a copy of this plane rotated as requested. - """ - rotate = Vector(rotate) - # Convert to radians. - rotate = rotate.multiply(math.pi / 180.0) - - # Compute rotation matrix. - m = FreeCAD.Base.Matrix() - m.rotateX(rotate.x) - m.rotateY(rotate.y) - m.rotateZ(rotate.z) - - # Compute the new plane. - newXdir = Vector(m.multiply(self.xDir.wrapped)) - newZdir = Vector(m.multiply(self.zDir.wrapped)) - - return Plane(self.origin, newXdir, newZdir) - - def rotateShapes(self, listOfShapes, rotationMatrix): - """Rotate the listOfShapes by the supplied rotationMatrix - - @param listOfShapes is a list of shape objects - @param rotationMatrix is a geom.Matrix object. - returns a list of shape objects rotated according to the rotationMatrix. - """ - # Compute rotation matrix (global --> local --> rotate --> global). - # rm = self.plane.fG.multiply(matrix).multiply(self.plane.rG) - # rm = self.computeTransform(rotationMatrix) - - # There might be a better way, but to do this rotation takes 3 steps: - # - transform geometry to local coordinates - # - then rotate about x - # - then transform back to global coordinates. - - resultWires = [] - for w in listOfShapes: - mirrored = w.transformGeometry(rotationMatrix.wrapped) - - # If the first vertex of the second wire is not coincident with the - # first or last vertices of the first wire we have to fix the wire - # so that it will mirror correctly. - if ((mirrored.wrapped.Vertexes[0].X == w.wrapped.Vertexes[0].X and - mirrored.wrapped.Vertexes[0].Y == w.wrapped.Vertexes[0].Y and - mirrored.wrapped.Vertexes[0].Z == w.wrapped.Vertexes[0].Z) or - (mirrored.wrapped.Vertexes[0].X == w.wrapped.Vertexes[-1].X and - mirrored.wrapped.Vertexes[0].Y == w.wrapped.Vertexes[-1].Y and - mirrored.wrapped.Vertexes[0].Z == w.wrapped.Vertexes[-1].Z)): - - resultWires.append(mirrored) - else: - # Make sure that our mirrored edges meet up and are ordered - # properly. - aEdges = w.wrapped.Edges - aEdges.extend(mirrored.wrapped.Edges) - comp = FreeCADPart.Compound(aEdges) - mirroredWire = comp.connectEdgesToWires(False).Wires[0] - - resultWires.append(cadquery.Shape.cast(mirroredWire)) - - return resultWires - - def _setPlaneDir(self, xDir): - """Set the vectors parallel to the plane, i.e. xDir and yDir""" - if (self.zDir.dot(xDir) > 1e-5): - raise ValueError('xDir must be parralel to the plane') - xDir = Vector(xDir) - self.xDir = xDir.normalized() - self.yDir = self.zDir.cross(self.xDir).normalized() - - def _calcTransforms(self): - """Computes transformation matrices to convert between coordinates - - Computes transformation matrices to convert between local and global - coordinates. - """ - # r is the forward transformation matrix from world to local coordinates - # ok i will be really honest, i cannot understand exactly why this works - # something bout the order of the translation and the rotation. - # the double-inverting is strange, and I don't understand it. - r = FreeCAD.Base.Matrix() - - # Forward transform must rotate and adjust for origin. - (r.A11, r.A12, r.A13) = (self.xDir.x, self.xDir.y, self.xDir.z) - (r.A21, r.A22, r.A23) = (self.yDir.x, self.yDir.y, self.yDir.z) - (r.A31, r.A32, r.A33) = (self.zDir.x, self.zDir.y, self.zDir.z) - - invR = r.inverse() - invR.A14 = self.origin.x - invR.A24 = self.origin.y - invR.A34 = self.origin.z - - self.rG = invR - self.fG = invR.inverse() - - def computeTransform(self, tMatrix): - """Computes the 2-d projection of the supplied matrix""" - - return Matrix(self.fG.multiply(tMatrix.wrapped).multiply(self.rG)) - - -class BoundBox(object): - """A BoundingBox for an object or set of objects. Wraps the FreeCAD one""" - def __init__(self, bb): - self.wrapped = bb - self.xmin = bb.XMin - self.xmax = bb.XMax - self.xlen = bb.XLength - self.ymin = bb.YMin - self.ymax = bb.YMax - self.ylen = bb.YLength - self.zmin = bb.ZMin - self.zmax = bb.ZMax - self.zlen = bb.ZLength - self.center = Vector(bb.Center) - self.DiagonalLength = bb.DiagonalLength - - def add(self, obj): - """Returns a modified (expanded) bounding box - - obj can be one of several things: - 1. a 3-tuple corresponding to x,y, and z amounts to add - 2. a vector, containing the x,y,z values to add - 3. another bounding box, where a new box will be created that - encloses both. - - This bounding box is not changed. - """ - tmp = FreeCAD.Base.BoundBox(self.wrapped) - if isinstance(obj, tuple): - tmp.add(obj[0], obj[1], obj[2]) - elif isinstance(obj, Vector): - tmp.add(obj.fV) - elif isinstance(obj, BoundBox): - tmp.add(obj.wrapped) - - return BoundBox(tmp) - - @classmethod - def findOutsideBox2D(cls, b1, b2): - """Compares bounding boxes - - Compares bounding boxes. Returns none if neither is inside the other. - Returns the outer one if either is outside the other. - - BoundBox.isInside works in 3d, but this is a 2d bounding box, so it - doesn't work correctly plus, there was all kinds of rounding error in - the built-in implementation i do not understand. - """ - fc_bb1 = b1.wrapped - fc_bb2 = b2.wrapped - if (fc_bb1.XMin < fc_bb2.XMin and - fc_bb1.XMax > fc_bb2.XMax and - fc_bb1.YMin < fc_bb2.YMin and - fc_bb1.YMax > fc_bb2.YMax): - return b1 - - if (fc_bb2.XMin < fc_bb1.XMin and - fc_bb2.XMax > fc_bb1.XMax and - fc_bb2.YMin < fc_bb1.YMin and - fc_bb2.YMax > fc_bb1.YMax): - return b2 - - return None - - def isInside(self, anotherBox): - """Is the provided bounding box inside this one?""" - return self.wrapped.isInside(anotherBox.wrapped) diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/importers.py b/Libs/cadquery-lib/cadquery/freecad_impl/importers.py deleted file mode 100644 index 7d4f0a9..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/importers.py +++ /dev/null @@ -1,71 +0,0 @@ - -import cadquery -from .shapes import Shape - -import FreeCAD -import Part -import sys -import os -import urllib as urlreader -import tempfile - -class ImportTypes: - STEP = "STEP" - -class UNITS: - MM = "mm" - IN = "in" - - -def importShape(importType, fileName): - """ - Imports a file based on the type (STEP, STL, etc) - :param importType: The type of file that we're importing - :param fileName: THe name of the file that we're importing - """ - - #Check to see what type of file we're working with - if importType == ImportTypes.STEP: - return importStep(fileName) - - -#Loads a STEP file into a CQ.Workplane object -def importStep(fileName): - """ - Accepts a file name and loads the STEP file into a cadquery shape - :param fileName: The path and name of the STEP file to be imported - """ - #Now read and return the shape - try: - #print fileName - rshape = Part.read(fileName) - - #Make sure that we extract all the solids - solids = [] - for solid in rshape.Solids: - solids.append(Shape.cast(solid)) - - return cadquery.Workplane("XY").newObject(solids) - except: - raise ValueError("STEP File Could not be loaded") - -#Loads a STEP file from an URL into a CQ.Workplane object -def importStepFromURL(url): - #Now read and return the shape - try: - webFile = urlreader.urlopen(url) - tempFile = tempfile.NamedTemporaryFile(suffix='.step', delete=False) - tempFile.write(webFile.read()) - webFile.close() - tempFile.close() - - rshape = Part.read(tempFile.name) - - #Make sure that we extract all the solids - solids = [] - for solid in rshape.Solids: - solids.append(Shape.cast(solid)) - - return cadquery.Workplane("XY").newObject(solids) - except: - raise ValueError("STEP File from the URL: " + url + " Could not be loaded") diff --git a/Libs/cadquery-lib/cadquery/freecad_impl/shapes.py b/Libs/cadquery-lib/cadquery/freecad_impl/shapes.py deleted file mode 100644 index 12567e9..0000000 --- a/Libs/cadquery-lib/cadquery/freecad_impl/shapes.py +++ /dev/null @@ -1,1038 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see - - Wrapper Classes for FreeCAD - These classes provide a stable interface for 3d objects, - independent of the FreeCAD interface. - - Future work might include use of pythonOCC, OCC, or even - another CAD kernel directly, so this interface layer is quite important. - - Funny, in java this is one of those few areas where i'd actually spend the time - to make an interface and an implementation, but for new these are just rolled together - - This interface layer provides three distinct values: - - 1. It allows us to avoid changing key api points if we change underlying implementations. - It would be a disaster if script and plugin authors had to change models because we - changed implementations - - 2. Allow better documentation. One of the reasons FreeCAD is no more popular is because - its docs are terrible. This allows us to provide good documentation via docstrings - for each wrapper - - 3. Work around bugs. there are a quite a feb bugs in free this layer allows fixing them - - 4. allows for enhanced functionality. Many objects are missing features we need. For example - we need a 'forConstruction' flag on the Wire object. this allows adding those kinds of things - - 5. allow changing interfaces when we'd like. there are few cases where the FreeCAD api is not - very user friendly: we like to change those when necessary. As an example, in the FreeCAD api, - all factory methods are on the 'Part' object, but it is very useful to know what kind of - object each one returns, so these are better grouped by the type of object they return. - (who would know that Part.makeCircle() returns an Edge, but Part.makePolygon() returns a Wire ? -""" -from cadquery import Vector, BoundBox -import FreeCAD -import Part as FreeCADPart - - -class Shape(object): - """ - Represents a shape in the system. - Wrappers the FreeCAD api - """ - - def __init__(self, obj): - self.wrapped = obj - self.forConstruction = False - - # Helps identify this solid through the use of an ID - self.label = "" - - @classmethod - def cast(cls, obj, forConstruction=False): - "Returns the right type of wrapper, given a FreeCAD object" - s = obj.ShapeType - if type(obj) == FreeCAD.Base.Vector: - return Vector(obj) - tr = None - - # TODO: there is a clever way to do this i'm sure with a lookup - # but it is not a perfect mapping, because we are trying to hide - # a bit of the complexity of Compounds in FreeCAD. - if s == 'Vertex': - tr = Vertex(obj) - elif s == 'Edge': - tr = Edge(obj) - elif s == 'Wire': - tr = Wire(obj) - elif s == 'Face': - tr = Face(obj) - elif s == 'Shell': - tr = Shell(obj) - elif s == 'Solid': - tr = Solid(obj) - elif s == 'Compound': - #compound of solids, lets return a solid instead - if len(obj.Solids) > 1: - tr = Solid(obj) - elif len(obj.Solids) == 1: - tr = Solid(obj.Solids[0]) - elif len(obj.Wires) > 0: - tr = Wire(obj) - else: - tr = Compound(obj) - else: - raise ValueError("cast:unknown shape type %s" % s) - - tr.forConstruction = forConstruction - return tr - - # TODO: all these should move into the exporters folder. - # we dont need a bunch of exporting code stored in here! - # - def exportStl(self, fileName): - self.wrapped.exportStl(fileName) - - def exportStep(self, fileName): - self.wrapped.exportStep(fileName) - - def exportShape(self, fileName, fileFormat): - if fileFormat == ExportFormats.STL: - self.wrapped.exportStl(fileName) - elif fileFormat == ExportFormats.BREP: - self.wrapped.exportBrep(fileName) - elif fileFormat == ExportFormats.STEP: - self.wrapped.exportStep(fileName) - elif fileFormat == ExportFormats.AMF: - # not built into FreeCAD - #TODO: user selected tolerance - tess = self.wrapped.tessellate(0.1) - aw = amfUtils.AMFWriter(tess) - aw.writeAmf(fileName) - elif fileFormat == ExportFormats.IGES: - self.wrapped.exportIges(fileName) - else: - raise ValueError("Unknown export format: %s" % format) - - def geomType(self): - """ - Gets the underlying geometry type - :return: a string according to the geometry type. - - Implementations can return any values desired, but the - values the user uses in type filters should correspond to these. - - As an example, if a user does:: - - CQ(object).faces("%mytype") - - The expectation is that the geomType attribute will return 'mytype' - - The return values depend on the type of the shape: - - Vertex: always 'Vertex' - Edge: LINE, ARC, CIRCLE, SPLINE - Face: PLANE, SPHERE, CONE - Solid: 'Solid' - Shell: 'Shell' - Compound: 'Compound' - Wire: 'Wire' - """ - return self.wrapped.ShapeType - - def isType(self, obj, strType): - """ - Returns True if the shape is the specified type, false otherwise - - contrast with ShapeType, which will raise an exception - if the provide object is not a shape at all - """ - if hasattr(obj, 'ShapeType'): - return obj.ShapeType == strType - else: - return False - - def hashCode(self): - return self.wrapped.hashCode() - - def isNull(self): - return self.wrapped.isNull() - - def isSame(self, other): - return self.wrapped.isSame(other.wrapped) - - def isEqual(self, other): - return self.wrapped.isEqual(other.wrapped) - - def isValid(self): - return self.wrapped.isValid() - - def BoundingBox(self, tolerance=0.1): - self.wrapped.tessellate(tolerance) - return BoundBox(self.wrapped.BoundBox) - - def mirror(self, mirrorPlane="XY", basePointVector=(0, 0, 0)): - if mirrorPlane == "XY" or mirrorPlane== "YX": - mirrorPlaneNormalVector = FreeCAD.Base.Vector(0, 0, 1) - elif mirrorPlane == "XZ" or mirrorPlane == "ZX": - mirrorPlaneNormalVector = FreeCAD.Base.Vector(0, 1, 0) - elif mirrorPlane == "YZ" or mirrorPlane == "ZY": - mirrorPlaneNormalVector = FreeCAD.Base.Vector(1, 0, 0) - - if type(basePointVector) == tuple: - basePointVector = Vector(basePointVector) - - return Shape.cast(self.wrapped.mirror(basePointVector.wrapped, mirrorPlaneNormalVector)) - - def Center(self): - # A Part.Shape object doesn't have the CenterOfMass function, but it's wrapped Solid(s) does - if isinstance(self.wrapped, FreeCADPart.Shape): - # If there are no Solids, we're probably dealing with a Face or something similar - if len(self.Solids()) == 0: - return Vector(self.wrapped.CenterOfMass) - elif len(self.Solids()) == 1: - return Vector(self.Solids()[0].wrapped.CenterOfMass) - elif len(self.Solids()) > 1: - return self.CombinedCenter(self.Solids()) - elif isinstance(self.wrapped, FreeCADPart.Solid): - return Vector(self.wrapped.CenterOfMass) - else: - raise ValueError("Cannot find the center of %s object type" % str(type(self.Solids()[0].wrapped))) - - def CenterOfBoundBox(self, tolerance = 0.1): - self.wrapped.tessellate(tolerance) - if isinstance(self.wrapped, FreeCADPart.Shape): - # If there are no Solids, we're probably dealing with a Face or something similar - if len(self.Solids()) == 0: - return Vector(self.wrapped.BoundBox.Center) - elif len(self.Solids()) == 1: - return Vector(self.Solids()[0].wrapped.BoundBox.Center) - elif len(self.Solids()) > 1: - return self.CombinedCenterOfBoundBox(self.Solids()) - elif isinstance(self.wrapped, FreeCADPart.Solid): - return Vector(self.wrapped.BoundBox.Center) - else: - raise ValueError("Cannot find the center(BoundBox's) of %s object type" % str(type(self.Solids()[0].wrapped))) - - @staticmethod - def CombinedCenter(objects): - """ - Calculates the center of mass of multiple objects. - - :param objects: a list of objects with mass - """ - total_mass = sum(Shape.computeMass(o) for o in objects) - weighted_centers = [o.wrapped.CenterOfMass.multiply(Shape.computeMass(o)) for o in objects] - - sum_wc = weighted_centers[0] - for wc in weighted_centers[1:] : - sum_wc = sum_wc.add(wc) - - return Vector(sum_wc.multiply(1./total_mass)) - - @staticmethod - def computeMass(object): - """ - Calculates the 'mass' of an object. in FreeCAD < 15, all objects had a mass. - in FreeCAD >=15, faces no longer have mass, but instead have area. - """ - if object.wrapped.ShapeType == 'Face': - return object.wrapped.Area - else: - return object.wrapped.Mass - - @staticmethod - def CombinedCenterOfBoundBox(objects, tolerance = 0.1): - """ - Calculates the center of BoundBox of multiple objects. - - :param objects: a list of objects with mass 1 - """ - total_mass = len(objects) - - weighted_centers = [] - for o in objects: - o.wrapped.tessellate(tolerance) - weighted_centers.append(o.wrapped.BoundBox.Center.multiply(1.0)) - - sum_wc = weighted_centers[0] - for wc in weighted_centers[1:] : - sum_wc = sum_wc.add(wc) - - return Vector(sum_wc.multiply(1./total_mass)) - - def Closed(self): - return self.wrapped.Closed - - def ShapeType(self): - return self.wrapped.ShapeType - - def Vertices(self): - return [Vertex(i) for i in self.wrapped.Vertexes] - - def Edges(self): - return [Edge(i) for i in self.wrapped.Edges] - - def Compounds(self): - return [Compound(i) for i in self.wrapped.Compounds] - - def Wires(self): - return [Wire(i) for i in self.wrapped.Wires] - - def Faces(self): - return [Face(i) for i in self.wrapped.Faces] - - def Shells(self): - return [Shell(i) for i in self.wrapped.Shells] - - def Solids(self): - return [Solid(i) for i in self.wrapped.Solids] - - def Area(self): - return self.wrapped.Area - - def Length(self): - return self.wrapped.Length - - def rotate(self, startVector, endVector, angleDegrees): - """ - Rotates a shape around an axis - :param startVector: start point of rotation axis either a 3-tuple or a Vector - :param endVector: end point of rotation axis, either a 3-tuple or a Vector - :param angleDegrees: angle to rotate, in degrees - :return: a copy of the shape, rotated - """ - if type(startVector) == tuple: - startVector = Vector(startVector) - - if type(endVector) == tuple: - endVector = Vector(endVector) - - tmp = self.wrapped.copy() - tmp.rotate(startVector.wrapped, endVector.wrapped, angleDegrees) - return Shape.cast(tmp) - - def translate(self, vector): - - if type(vector) == tuple: - vector = Vector(vector) - tmp = self.wrapped.copy() - tmp.translate(vector.wrapped) - return Shape.cast(tmp) - - def scale(self, factor): - tmp = self.wrapped.copy() - tmp.scale(factor) - return Shape.cast(tmp) - - def copy(self): - return Shape.cast(self.wrapped.copy()) - - def transformShape(self, tMatrix): - """ - tMatrix is a matrix object. - returns a copy of the ojbect, transformed by the provided matrix, - with all objects keeping their type - """ - tmp = self.wrapped.copy() - tmp.transformShape(tMatrix) - r = Shape.cast(tmp) - r.forConstruction = self.forConstruction - return r - - def transformGeometry(self, tMatrix): - """ - tMatrix is a matrix object. - - returns a copy of the object, but with geometry transformed insetad of just - rotated. - - WARNING: transformGeometry will sometimes convert lines and circles to splines, - but it also has the ability to handle skew and stretching transformations. - - If your transformation is only translation and rotation, it is safer to use transformShape, - which doesnt change the underlying type of the geometry, but cannot handle skew transformations - """ - tmp = self.wrapped.copy() - tmp = tmp.transformGeometry(tMatrix) - return Shape.cast(tmp) - - def __hash__(self): - return self.wrapped.hashCode() - - -class Vertex(Shape): - """ - A Single Point in Space - """ - - def __init__(self, obj, forConstruction=False): - """ - Create a vertex from a FreeCAD Vertex - """ - self.wrapped = obj - self.forConstruction = forConstruction - self.X = obj.X - self.Y = obj.Y - self.Z = obj.Z - - # Helps identify this solid through the use of an ID - self.label = "" - - def toTuple(self): - return (self.X, self.Y, self.Z) - - def Center(self): - """ - The center of a vertex is itself! - """ - return Vector(self.wrapped.Point) - - -class Edge(Shape): - """ - A trimmed curve that represents the border of a face - """ - - def __init__(self, obj): - """ - An Edge - """ - self.wrapped = obj - # self.startPoint = None - # self.endPoint = None - - self.edgetypes = { - FreeCADPart.Line: 'LINE', - FreeCADPart.ArcOfCircle: 'ARC', - FreeCADPart.Circle: 'CIRCLE' - } - - # Helps identify this solid through the use of an ID - self.label = "" - - def geomType(self): - t = type(self.wrapped.Curve) - if self.edgetypes.has_key(t): - return self.edgetypes[t] - else: - return "Unknown Edge Curve Type: %s" % str(t) - - def startPoint(self): - """ - - :return: a vector representing the start poing of this edge - - Note, circles may have the start and end points the same - """ - # work around freecad bug where valueAt is unreliable - curve = self.wrapped.Curve - return Vector(curve.value(self.wrapped.ParameterRange[0])) - - def endPoint(self): - """ - - :return: a vector representing the end point of this edge. - - Note, circles may have the start and end points the same - - """ - # warning: easier syntax in freecad of .valueAt(.ParameterRange[1]) has - # a bug with curves other than arcs, but using the underlying curve directly seems to work - # that's the solution i'm using below - curve = self.wrapped.Curve - v = Vector(curve.value(self.wrapped.ParameterRange[1])) - return v - - def tangentAt(self, locationVector=None): - """ - Compute tangent vector at the specified location. - :param locationVector: location to use. Use the center point if None - :return: tangent vector - """ - if locationVector is None: - locationVector = self.Center() - - p = self.wrapped.Curve.parameter(locationVector.wrapped) - return Vector(self.wrapped.tangentAt(p)) - - @classmethod - def makeCircle(cls, radius, pnt=(0, 0, 0), dir=(0, 0, 1), angle1=360.0, angle2=360): - center = Vector(pnt) - normal = Vector(dir) - return Edge(FreeCADPart.makeCircle(radius, center.wrapped, normal.wrapped, angle1, angle2)) - - @classmethod - def makeSpline(cls, listOfVector): - """ - Interpolate a spline through the provided points. - :param cls: - :param listOfVector: a list of Vectors that represent the points - :return: an Edge - """ - vecs = [v.wrapped for v in listOfVector] - - spline = FreeCADPart.BSplineCurve() - spline.interpolate(vecs, False) - return Edge(spline.toShape()) - - @classmethod - def makeThreePointArc(cls, v1, v2, v3): - """ - Makes a three point arc through the provided points - :param cls: - :param v1: start vector - :param v2: middle vector - :param v3: end vector - :return: an edge object through the three points - """ - arc = FreeCADPart.Arc(v1.wrapped, v2.wrapped, v3.wrapped) - e = Edge(arc.toShape()) - return e # arcane and undocumented, this creates an Edge object - - @classmethod - def makeLine(cls, v1, v2): - """ - Create a line between two points - :param v1: Vector that represents the first point - :param v2: Vector that represents the second point - :return: A linear edge between the two provided points - """ - return Edge(FreeCADPart.makeLine(v1.toTuple(), v2.toTuple())) - - -class Wire(Shape): - """ - A series of connected, ordered Edges, that typically bounds a Face - """ - - def __init__(self, obj): - """ - A Wire - """ - self.wrapped = obj - - # Helps identify this solid through the use of an ID - self.label = "" - - @classmethod - def combine(cls, listOfWires): - """ - Attempt to combine a list of wires into a new wire. - the wires are returned in a list. - :param cls: - :param listOfWires: - :return: - """ - return Shape.cast(FreeCADPart.Wire([w.wrapped for w in listOfWires])) - - @classmethod - def assembleEdges(cls, listOfEdges): - """ - Attempts to build a wire that consists of the edges in the provided list - :param cls: - :param listOfEdges: a list of Edge objects - :return: a wire with the edges assembled - """ - fCEdges = [a.wrapped for a in listOfEdges] - - wa = Wire(FreeCADPart.Wire(fCEdges)) - return wa - - @classmethod - def makeCircle(cls, radius, center, normal): - """ - Makes a Circle centered at the provided point, having normal in the provided direction - :param radius: floating point radius of the circle, must be > 0 - :param center: vector representing the center of the circle - :param normal: vector representing the direction of the plane the circle should lie in - :return: - """ - w = Wire(FreeCADPart.Wire([FreeCADPart.makeCircle(radius, center.wrapped, normal.wrapped)])) - return w - - @classmethod - def makePolygon(cls, listOfVertices, forConstruction=False): - # convert list of tuples into Vectors. - w = Wire(FreeCADPart.makePolygon([i.wrapped for i in listOfVertices])) - w.forConstruction = forConstruction - return w - - @classmethod - def makeHelix(cls, pitch, height, radius, angle=360.0): - """ - Make a helix with a given pitch, height and radius - By default a cylindrical surface is used to create the helix. If - the fourth parameter is set (the apex given in degree) a conical surface is used instead' - """ - return Wire(FreeCADPart.makeHelix(pitch, height, radius, angle)) - - def clean(self): - """This method is not implemented yet.""" - return self - -class Face(Shape): - """ - a bounded surface that represents part of the boundary of a solid - """ - def __init__(self, obj): - - self.wrapped = obj - - self.facetypes = { - # TODO: bezier,bspline etc - FreeCADPart.Plane: 'PLANE', - FreeCADPart.Sphere: 'SPHERE', - FreeCADPart.Cone: 'CONE' - } - - # Helps identify this solid through the use of an ID - self.label = "" - - def geomType(self): - t = type(self.wrapped.Surface) - if self.facetypes.has_key(t): - return self.facetypes[t] - else: - return "Unknown Face Surface Type: %s" % str(t) - - def normalAt(self, locationVector=None): - """ - Computes the normal vector at the desired location on the face. - - :returns: a vector representing the direction - :param locationVector: the location to compute the normal at. If none, the center of the face is used. - :type locationVector: a vector that lies on the surface. - """ - if locationVector == None: - locationVector = self.Center() - (u, v) = self.wrapped.Surface.parameter(locationVector.wrapped) - - return Vector(self.wrapped.normalAt(u, v).normalize()) - - @classmethod - def makePlane(cls, length, width, basePnt=(0, 0, 0), dir=(0, 0, 1)): - basePnt = Vector(basePnt) - dir = Vector(dir) - return Face(FreeCADPart.makePlane(length, width, basePnt.wrapped, dir.wrapped)) - - @classmethod - def makeRuledSurface(cls, edgeOrWire1, edgeOrWire2, dist=None): - """ - 'makeRuledSurface(Edge|Wire,Edge|Wire) -- Make a ruled surface - Create a ruled surface out of two edges or wires. If wires are used then - these must have the same - """ - return Shape.cast(FreeCADPart.makeRuledSurface(edgeOrWire1.obj, edgeOrWire2.obj, dist)) - - def cut(self, faceToCut): - "Remove a face from another one" - return Shape.cast(self.obj.cut(faceToCut.obj)) - - def fuse(self, faceToJoin): - return Shape.cast(self.obj.fuse(faceToJoin.obj)) - - def intersect(self, faceToIntersect): - """ - computes the intersection between the face and the supplied one. - The result could be a face or a compound of faces - """ - return Shape.cast(self.obj.common(faceToIntersect.obj)) - - -class Shell(Shape): - """ - the outer boundary of a surface - """ - def __init__(self, wrapped): - """ - A Shell - """ - self.wrapped = wrapped - - # Helps identify this solid through the use of an ID - self.label = "" - - @classmethod - def makeShell(cls, listOfFaces): - return Shell(FreeCADPart.makeShell([i.obj for i in listOfFaces])) - - -class Solid(Shape): - """ - a single solid - """ - def __init__(self, obj): - """ - A Solid - """ - self.wrapped = obj - - # Helps identify this solid through the use of an ID - self.label = "" - - @classmethod - def isSolid(cls, obj): - """ - Returns true if the object is a FreeCAD solid, false otherwise - """ - if hasattr(obj, 'ShapeType'): - if obj.ShapeType == 'Solid' or \ - (obj.ShapeType == 'Compound' and len(obj.Solids) > 0): - return True - return False - - @classmethod - def makeBox(cls, length, width, height, pnt=Vector(0, 0, 0), dir=Vector(0, 0, 1)): - """ - makeBox(length,width,height,[pnt,dir]) -- Make a box located in pnt with the dimensions (length,width,height) - By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)' - """ - return Shape.cast(FreeCADPart.makeBox(length, width, height, pnt.wrapped, dir.wrapped)) - - @classmethod - def makeCone(cls, radius1, radius2, height, pnt=Vector(0, 0, 0), dir=Vector(0, 0, 1), angleDegrees=360): - """ - Make a cone with given radii and height - By default pnt=Vector(0,0,0), - dir=Vector(0,0,1) and angle=360' - """ - return Shape.cast(FreeCADPart.makeCone(radius1, radius2, height, pnt.wrapped, dir.wrapped, angleDegrees)) - - @classmethod - def makeCylinder(cls, radius, height, pnt=Vector(0, 0, 0), dir=Vector(0, 0, 1), angleDegrees=360): - """ - makeCylinder(radius,height,[pnt,dir,angle]) -- - Make a cylinder with a given radius and height - By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360' - """ - return Shape.cast(FreeCADPart.makeCylinder(radius, height, pnt.wrapped, dir.wrapped, angleDegrees)) - - @classmethod - def makeTorus(cls, radius1, radius2, pnt=None, dir=None, angleDegrees1=None, angleDegrees2=None): - """ - makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- - Make a torus with agiven radii and angles - By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0 - ,angle1=360 and angle=360' - """ - return Shape.cast(FreeCADPart.makeTorus(radius1, radius2, pnt, dir, angleDegrees1, angleDegrees2)) - - @classmethod - def sweep(cls, profileWire, pathWire): - """ - make a solid by sweeping the profileWire along the specified path - :param cls: - :param profileWire: - :param pathWire: - :return: - """ - # needs to use freecad wire.makePipe or makePipeShell - # needs to allow free-space wires ( those not made from a workplane ) - - @classmethod - def makeLoft(cls, listOfWire, ruled=False): - """ - makes a loft from a list of wires - The wires will be converted into faces when possible-- it is presumed that nobody ever actually - wants to make an infinitely thin shell for a real FreeCADPart. - """ - # the True flag requests building a solid instead of a shell. - - return Shape.cast(FreeCADPart.makeLoft([i.wrapped for i in listOfWire], True, ruled)) - - @classmethod - def makeWedge(cls, xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max, pnt=None, dir=None): - """ - Make a wedge located in pnt - By default pnt=Vector(0,0,0) and dir=Vector(0,0,1) - """ - return Shape.cast( - FreeCADPart.makeWedge(xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max, pnt, dir)) - - @classmethod - def makeSphere(cls, radius, pnt=None, dir=None, angleDegrees1=None, angleDegrees2=None, angleDegrees3=None): - """ - Make a sphere with a given radius - By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360 - """ - return Shape.cast(FreeCADPart.makeSphere(radius, pnt.wrapped, dir.wrapped, angleDegrees1, angleDegrees2, angleDegrees3)) - - @classmethod - def extrudeLinearWithRotation(cls, outerWire, innerWires, vecCenter, vecNormal, angleDegrees): - """ - Creates a 'twisted prism' by extruding, while simultaneously rotating around the extrusion vector. - - Though the signature may appear to be similar enough to extrudeLinear to merit combining them, the - construction methods used here are different enough that they should be separate. - - At a high level, the steps followed are: - (1) accept a set of wires - (2) create another set of wires like this one, but which are transformed and rotated - (3) create a ruledSurface between the sets of wires - (4) create a shell and compute the resulting object - - :param outerWire: the outermost wire, a cad.Wire - :param innerWires: a list of inner wires, a list of cad.Wire - :param vecCenter: the center point about which to rotate. the axis of rotation is defined by - vecNormal, located at vecCenter. ( a cad.Vector ) - :param vecNormal: a vector along which to extrude the wires ( a cad.Vector ) - :param angleDegrees: the angle to rotate through while extruding - :return: a cad.Solid object - """ - - # from this point down we are dealing with FreeCAD wires not cad.wires - startWires = [outerWire.wrapped] + [i.wrapped for i in innerWires] - endWires = [] - p1 = vecCenter.wrapped - p2 = vecCenter.add(vecNormal).wrapped - - # make translated and rotated copy of each wire - for w in startWires: - w2 = w.copy() - w2.translate(vecNormal.wrapped) - w2.rotate(p1, p2, angleDegrees) - endWires.append(w2) - - # make a ruled surface for each set of wires - sides = [] - for w1, w2 in zip(startWires, endWires): - rs = FreeCADPart.makeRuledSurface(w1, w2) - sides.append(rs) - - #make faces for the top and bottom - startFace = FreeCADPart.Face(startWires) - endFace = FreeCADPart.Face(endWires) - - #collect all the faces from the sides - faceList = [startFace] - for s in sides: - faceList.extend(s.Faces) - faceList.append(endFace) - - shell = FreeCADPart.makeShell(faceList) - solid = FreeCADPart.makeSolid(shell) - return Shape.cast(solid) - - @classmethod - def extrudeLinear(cls, outerWire, innerWires, vecNormal): - """ - Attempt to extrude the list of wires into a prismatic solid in the provided direction - - :param outerWire: the outermost wire - :param innerWires: a list of inner wires - :param vecNormal: a vector along which to extrude the wires - :return: a Solid object - - The wires must not intersect - - Extruding wires is very non-trivial. Nested wires imply very different geometry, and - there are many geometries that are invalid. In general, the following conditions must be met: - - * all wires must be closed - * there cannot be any intersecting or self-intersecting wires - * wires must be listed from outside in - * more than one levels of nesting is not supported reliably - - This method will attempt to sort the wires, but there is much work remaining to make this method - reliable. - """ - - # one would think that fusing faces into a compound and then extruding would work, - # but it doesnt-- the resulting compound appears to look right, ( right number of faces, etc), - # but then cutting it from the main solid fails with BRep_NotDone. - #the work around is to extrude each and then join the resulting solids, which seems to work - - #FreeCAD allows this in one operation, but others might not - freeCADWires = [outerWire.wrapped] - for w in innerWires: - freeCADWires.append(w.wrapped) - - f = FreeCADPart.Face(freeCADWires) - result = f.extrude(vecNormal.wrapped) - - return Shape.cast(result) - - @classmethod - def revolve(cls, outerWire, innerWires, angleDegrees, axisStart, axisEnd): - """ - Attempt to revolve the list of wires into a solid in the provided direction - - :param outerWire: the outermost wire - :param innerWires: a list of inner wires - :param angleDegrees: the angle to revolve through. - :type angleDegrees: float, anything less than 360 degrees will leave the shape open - :param axisStart: the start point of the axis of rotation - :type axisStart: tuple, a two tuple - :param axisEnd: the end point of the axis of rotation - :type axisEnd: tuple, a two tuple - :return: a Solid object - - The wires must not intersect - - * all wires must be closed - * there cannot be any intersecting or self-intersecting wires - * wires must be listed from outside in - * more than one levels of nesting is not supported reliably - * the wire(s) that you're revolving cannot be centered - - This method will attempt to sort the wires, but there is much work remaining to make this method - reliable. - """ - freeCADWires = [outerWire.wrapped] - - for w in innerWires: - freeCADWires.append(w.wrapped) - - f = FreeCADPart.Face(freeCADWires) - - rotateCenter = FreeCAD.Base.Vector(axisStart) - rotateAxis = FreeCAD.Base.Vector(axisEnd) - - #Convert our axis end vector into to something FreeCAD will understand (an axis specification vector) - rotateAxis = rotateCenter.sub(rotateAxis) - - #FreeCAD wants a rotation center and then an axis to rotate around rather than an axis of rotation - result = f.revolve(rotateCenter, rotateAxis, angleDegrees) - - return Shape.cast(result) - - @classmethod - def sweep(cls, outerWire, innerWires, path, makeSolid=True, isFrenet=False): - """ - Attempt to sweep the list of wires into a prismatic solid along the provided path - - :param outerWire: the outermost wire - :param innerWires: a list of inner wires - :param path: The wire to sweep the face resulting from the wires over - :return: a Solid object - """ - - # FreeCAD allows this in one operation, but others might not - freeCADWires = [outerWire.wrapped] - for w in innerWires: - freeCADWires.append(w.wrapped) - - # f = FreeCADPart.Face(freeCADWires) - wire = FreeCADPart.Wire([path.wrapped]) - result = wire.makePipeShell(freeCADWires, makeSolid, isFrenet) - - return Shape.cast(result) - - def tessellate(self, tolerance): - return self.wrapped.tessellate(tolerance) - - def intersect(self, toIntersect): - """ - computes the intersection between this solid and the supplied one - The result could be a face or a compound of faces - """ - return Shape.cast(self.wrapped.common(toIntersect.wrapped)) - - def cut(self, solidToCut): - "Remove a solid from another one" - return Shape.cast(self.wrapped.cut(solidToCut.wrapped)) - - def fuse(self, solidToJoin): - return Shape.cast(self.wrapped.fuse(solidToJoin.wrapped)) - - def clean(self): - """Clean faces by removing splitter edges.""" - r = self.wrapped.removeSplitter() - # removeSplitter() returns a generic Shape type, cast to actual type of object - r = FreeCADPart.cast_to_shape(r) - return Shape.cast(r) - - def fillet(self, radius, edgeList): - """ - Fillets the specified edges of this solid. - :param radius: float > 0, the radius of the fillet - :param edgeList: a list of Edge objects, which must belong to this solid - :return: Filleted solid - """ - nativeEdges = [e.wrapped for e in edgeList] - return Shape.cast(self.wrapped.makeFillet(radius, nativeEdges)) - - def chamfer(self, length, length2, edgeList): - """ - Chamfers the specified edges of this solid. - :param length: length > 0, the length (length) of the chamfer - :param length2: length2 > 0, optional parameter for asymmetrical chamfer. Should be `None` if not required. - :param edgeList: a list of Edge objects, which must belong to this solid - :return: Chamfered solid - """ - nativeEdges = [e.wrapped for e in edgeList] - # note: we prefer 'length' word to 'radius' as opposed to FreeCAD's API - if length2: - return Shape.cast(self.wrapped.makeChamfer(length, length2, nativeEdges)) - else: - return Shape.cast(self.wrapped.makeChamfer(length, nativeEdges)) - - def shell(self, faceList, thickness, tolerance=0.0001): - """ - make a shelled solid of given by removing the list of faces - - :param faceList: list of face objects, which must be part of the solid. - :param thickness: floating point thickness. positive shells outwards, negative shells inwards - :param tolerance: modelling tolerance of the method, default=0.0001 - :return: a shelled solid - - **WARNING** The underlying FreeCAD implementation can very frequently have problems - with shelling complex geometries! - """ - nativeFaces = [f.wrapped for f in faceList] - return Shape.cast(self.wrapped.makeThickness(nativeFaces, thickness, tolerance)) - - -class Compound(Shape): - """ - a collection of disconnected solids - """ - - def __init__(self, obj): - """ - An Edge - """ - self.wrapped = obj - - # Helps identify this solid through the use of an ID - self.label = "" - - def Center(self): - return self.Center() - - @classmethod - def makeCompound(cls, listOfShapes): - """ - Create a compound out of a list of shapes - """ - solids = [s.wrapped for s in listOfShapes] - c = FreeCADPart.Compound(solids) - return Shape.cast(c) - - def fuse(self, toJoin): - return Shape.cast(self.wrapped.fuse(toJoin.wrapped)) - - def tessellate(self, tolerance): - return self.wrapped.tessellate(tolerance) - - def clean(self): - """This method is not implemented yet.""" - return self diff --git a/Libs/cadquery-lib/cadquery/plugins/__init__.py b/Libs/cadquery-lib/cadquery/plugins/__init__.py deleted file mode 100644 index 3697b9f..0000000 --- a/Libs/cadquery-lib/cadquery/plugins/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -""" - CadQuery - Copyright (C) 2015 Parametric Products Intellectual Holdings, LLC - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -""" diff --git a/Libs/cadquery-lib/cadquery/selectors.py b/Libs/cadquery-lib/cadquery/selectors.py deleted file mode 100644 index 72174e1..0000000 --- a/Libs/cadquery-lib/cadquery/selectors.py +++ /dev/null @@ -1,671 +0,0 @@ -""" - Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC - - This file is part of CadQuery. - - CadQuery is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - CadQuery is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; If not, see -""" - -import re -import math -from cadquery import Vector,Edge,Vertex,Face,Solid,Shell,Compound -from pyparsing import Literal,Word,nums,Optional,Combine,oneOf,upcaseTokens,\ - CaselessLiteral,Group,infixNotation,opAssoc,Forward,\ - ZeroOrMore,Keyword - - -class Selector(object): - """ - Filters a list of objects - - Filters must provide a single method that filters objects. - """ - def filter(self,objectList): - """ - Filter the provided list - :param objectList: list to filter - :type objectList: list of FreeCAD primatives - :return: filtered list - - The default implementation returns the original list unfiltered - - """ - return objectList - - def __and__(self, other): - return AndSelector(self, other) - - def __add__(self, other): - return SumSelector(self, other) - - def __sub__(self, other): - return SubtractSelector(self, other) - - def __neg__(self): - return InverseSelector(self) - -class NearestToPointSelector(Selector): - """ - Selects object nearest the provided point. - - If the object is a vertex or point, the distance - is used. For other kinds of shapes, the center of mass - is used to to compute which is closest. - - Applicability: All Types of Shapes - - Example:: - - CQ(aCube).vertices(NearestToPointSelector((0,1,0)) - - returns the vertex of the unit cube closest to the point x=0,y=1,z=0 - - """ - def __init__(self,pnt ): - self.pnt = pnt - def filter(self,objectList): - - def dist(tShape): - return tShape.Center().sub(Vector(*self.pnt)).Length - #if tShape.ShapeType == 'Vertex': - # return tShape.Point.sub(toVector(self.pnt)).Length - #else: - # return tShape.CenterOfMass.sub(toVector(self.pnt)).Length - - return [ min(objectList,key=dist) ] - -class BoxSelector(Selector): - """ - Selects objects inside the 3D box defined by 2 points. - - If `boundingbox` is True only the objects that have their bounding - box inside the given box is selected. Otherwise only center point - of the object is tested. - - Applicability: all types of shapes - - Example:: - - CQ(aCube).edges(BoxSelector((0,1,0), (1,2,1)) - """ - def __init__(self, point0, point1, boundingbox=False): - self.p0 = Vector(*point0) - self.p1 = Vector(*point1) - self.test_boundingbox = boundingbox - - def filter(self, objectList): - - result = [] - x0, y0, z0 = self.p0.toTuple() - x1, y1, z1 = self.p1.toTuple() - - def isInsideBox(p): - # using XOR for checking if x/y/z is in between regardless - # of order of x/y/z0 and x/y/z1 - return ((p.x < x0) ^ (p.x < x1)) and \ - ((p.y < y0) ^ (p.y < y1)) and \ - ((p.z < z0) ^ (p.z < z1)) - - for o in objectList: - if self.test_boundingbox: - bb = o.BoundingBox() - if isInsideBox(Vector(bb.xmin, bb.ymin, bb.zmin)) and \ - isInsideBox(Vector(bb.xmax, bb.ymax, bb.zmax)): - result.append(o) - else: - if isInsideBox(o.Center()): - result.append(o) - - return result - -class BaseDirSelector(Selector): - """ - A selector that handles selection on the basis of a single - direction vector - """ - def __init__(self,vector,tolerance=0.0001 ): - self.direction = vector - self.TOLERANCE = tolerance - - def test(self,vec): - "Test a specified vector. Subclasses override to provide other implementations" - return True - - def filter(self,objectList): - """ - There are lots of kinds of filters, but - for planes they are always based on the normal of the plane, - and for edges on the tangent vector along the edge - """ - r = [] - for o in objectList: - #no really good way to avoid a switch here, edges and faces are simply different! - - if type(o) == Face: - # a face is only parallell to a direction if it is a plane, and its normal is parallel to the dir - normal = o.normalAt(None) - - if self.test(normal): - r.append(o) - elif type(o) == Edge and o.geomType() == 'LINE': - #an edge is parallel to a direction if it is a line, and the line is parallel to the dir - tangent = o.tangentAt(None) - if self.test(tangent): - r.append(o) - - return r - -class ParallelDirSelector(BaseDirSelector): - """ - Selects objects parallel with the provided direction - - Applicability: - Linear Edges - Planar Faces - - Use the string syntax shortcut \|(X|Y|Z) if you want to select - based on a cardinal direction. - - Example:: - - CQ(aCube).faces(ParallelDirSelector((0,0,1)) - - selects faces with a normals in the z direction, and is equivalent to:: - - CQ(aCube).faces("|Z") - """ - - def test(self,vec): - return self.direction.cross(vec).Length < self.TOLERANCE - -class DirectionSelector(BaseDirSelector): - """ - Selects objects aligned with the provided direction - - Applicability: - Linear Edges - Planar Faces - - Use the string syntax shortcut +/-(X|Y|Z) if you want to select - based on a cardinal direction. - - Example:: - - CQ(aCube).faces(DirectionSelector((0,0,1)) - - selects faces with a normals in the z direction, and is equivalent to:: - - CQ(aCube).faces("+Z") - """ - - def test(self,vec): - return abs(self.direction.getAngle(vec) < self.TOLERANCE) - -class PerpendicularDirSelector(BaseDirSelector): - """ - Selects objects perpendicular with the provided direction - - Applicability: - Linear Edges - Planar Faces - - Use the string syntax shortcut #(X|Y|Z) if you want to select - based on a cardinal direction. - - Example:: - - CQ(aCube).faces(PerpendicularDirSelector((0,0,1)) - - selects faces with a normals perpendicular to the z direction, and is equivalent to:: - - CQ(aCube).faces("#Z") - """ - - def test(self,vec): - angle = self.direction.getAngle(vec) - r = (abs(angle) < self.TOLERANCE) or (abs(angle - math.pi) < self.TOLERANCE ) - return not r - - -class TypeSelector(Selector): - """ - Selects objects of the prescribed topological type. - - Applicability: - Faces: Plane,Cylinder,Sphere - Edges: Line,Circle,Arc - - You can use the shortcut selector %(PLANE|SPHERE|CONE) for faces, - and %(LINE|ARC|CIRCLE) for edges. - - For example this:: - - CQ(aCube).faces ( TypeSelector("PLANE") ) - - will select 6 faces, and is equivalent to:: - - CQ(aCube).faces( "%PLANE" ) - - """ - def __init__(self,typeString): - self.typeString = typeString.upper() - - def filter(self,objectList): - r = [] - for o in objectList: - if o.geomType() == self.typeString: - r.append(o) - return r - -class DirectionMinMaxSelector(Selector): - """ - Selects objects closest or farthest in the specified direction - Used for faces, points, and edges - - Applicability: - All object types. for a vertex, its point is used. for all other kinds - of objects, the center of mass of the object is used. - - You can use the string shortcuts >(X|Y|Z) or <(X|Y|Z) if you want to - select based on a cardinal direction. - - For example this:: - - CQ(aCube).faces ( DirectionMinMaxSelector((0,0,1),True ) - - Means to select the face having the center of mass farthest in the positive z direction, - and is the same as: - - CQ(aCube).faces( ">Z" ) - - """ - def __init__(self, vector, directionMax=True, tolerance=0.0001): - self.vector = vector - self.max = max - self.directionMax = directionMax - self.TOLERANCE = tolerance - def filter(self,objectList): - - def distance(tShape): - return tShape.Center().dot(self.vector) - #if tShape.ShapeType == 'Vertex': - # pnt = tShape.Point - #else: - # pnt = tShape.Center() - #return pnt.dot(self.vector) - - # import OrderedDict - from collections import OrderedDict - #make and distance to object dict - objectDict = {distance(el) : el for el in objectList} - #transform it into an ordered dict - objectDict = OrderedDict(sorted(objectDict.items(), - key=lambda x: x[0])) - - # find out the max/min distance - if self.directionMax: - d = objectDict.keys()[-1] - else: - d = objectDict.keys()[0] - - # return all objects at the max/min distance (within a tolerance) - return filter(lambda o: abs(d - distance(o)) < self.TOLERANCE, objectList) - -class DirectionNthSelector(ParallelDirSelector): - """ - Selects nth object parallel (or normal) to the specified direction - Used for faces and edges - - Applicability: - Linear Edges - Planar Faces - """ - def __init__(self, vector, n, directionMax=True, tolerance=0.0001): - self.direction = vector - self.max = max - self.directionMax = directionMax - self.TOLERANCE = tolerance - if directionMax: - self.N = n #do we want indexing from 0 or from 1? - else: - self.N = -n - - def filter(self,objectList): - #select first the objects that are normal/parallel to a given dir - objectList = super(DirectionNthSelector,self).filter(objectList) - - def distance(tShape): - return tShape.Center().dot(self.direction) - #if tShape.ShapeType == 'Vertex': - # pnt = tShape.Point - #else: - # pnt = tShape.Center() - #return pnt.dot(self.vector) - - #make and distance to object dict - objectDict = {distance(el) : el for el in objectList} - #calculate how many digits of precision do we need - digits = int(1/self.TOLERANCE) - # create a rounded distance to original distance mapping (implicitly perfroms unique operation) - dist_round_dist = {round(d,digits) : d for d in objectDict.keys()} - # choose the Nth unique rounded distance - nth_d = dist_round_dist[sorted(dist_round_dist.keys())[self.N]] - - # map back to original objects and return - return [objectDict[d] for d in objectDict.keys() if abs(d-nth_d) < self.TOLERANCE] - -class BinarySelector(Selector): - """ - Base class for selectors that operates with two other - selectors. Subclass must implement the :filterResults(): method. - """ - def __init__(self, left, right): - self.left = left - self.right = right - - def filter(self, objectList): - return self.filterResults(self.left.filter(objectList), - self.right.filter(objectList)) - - def filterResults(self, r_left, r_right): - raise NotImplementedError - -class AndSelector(BinarySelector): - """ - Intersection selector. Returns objects that is selected by both selectors. - """ - def filterResults(self, r_left, r_right): - # return intersection of lists - return list(set(r_left) & set(r_right)) - -class SumSelector(BinarySelector): - """ - Union selector. Returns the sum of two selectors results. - """ - def filterResults(self, r_left, r_right): - # return the union (no duplicates) of lists - return list(set(r_left + r_right)) - -class SubtractSelector(BinarySelector): - """ - Difference selector. Substract results of a selector from another - selectors results. - """ - def filterResults(self, r_left, r_right): - return list(set(r_left) - set(r_right)) - -class InverseSelector(Selector): - """ - Inverts the selection of given selector. In other words, selects - all objects that is not selected by given selector. - """ - def __init__(self, selector): - self.selector = selector - - def filter(self, objectList): - # note that Selector() selects everything - return SubtractSelector(Selector(), self.selector).filter(objectList) - - -def _makeGrammar(): - """ - Define the simple string selector grammar using PyParsing - """ - - #float definition - point = Literal('.') - plusmin = Literal('+') | Literal('-') - number = Word(nums) - integer = Combine(Optional(plusmin) + number) - floatn = Combine(integer + Optional(point + Optional(number))) - - #vector definition - lbracket = Literal('(') - rbracket = Literal(')') - comma = Literal(',') - vector = Combine(lbracket + floatn('x') + comma + \ - floatn('y') + comma + floatn('z') + rbracket) - - #direction definition - simple_dir = oneOf(['X','Y','Z','XY','XZ','YZ']) - direction = simple_dir('simple_dir') | vector('vector_dir') - - #CQ type definition - cqtype = oneOf(['Plane','Cylinder','Sphere','Cone','Line','Circle','Arc'], - caseless=True) - cqtype = cqtype.setParseAction(upcaseTokens) - - #type operator - type_op = Literal('%') - - #direction operator - direction_op = oneOf(['>','<']) - - #index definition - ix_number = Group(Optional('-')+Word(nums)) - lsqbracket = Literal('[').suppress() - rsqbracket = Literal(']').suppress() - - index = lsqbracket + ix_number('index') + rsqbracket - - #other operators - other_op = oneOf(['|','#','+','-']) - - #named view - named_view = oneOf(['front','back','left','right','top','bottom']) - - return direction('only_dir') | \ - (type_op('type_op') + cqtype('cq_type')) | \ - (direction_op('dir_op') + direction('dir') + Optional(index)) | \ - (other_op('other_op') + direction('dir')) | \ - named_view('named_view') - -_grammar = _makeGrammar() #make a grammar instance - -class _SimpleStringSyntaxSelector(Selector): - """ - This is a private class that converts a parseResults object into a simple - selector object - """ - def __init__(self,parseResults): - - #define all token to object mappings - self.axes = { - 'X': Vector(1,0,0), - 'Y': Vector(0,1,0), - 'Z': Vector(0,0,1), - 'XY': Vector(1,1,0), - 'YZ': Vector(0,1,1), - 'XZ': Vector(1,0,1) - } - - self.namedViews = { - 'front' : (Vector(0,0,1),True), - 'back' : (Vector(0,0,1),False), - 'left' : (Vector(1,0,0),False), - 'right' : (Vector(1,0,0),True), - 'top' : (Vector(0,1,0),True), - 'bottom': (Vector(0,1,0),False) - } - - self.operatorMinMax = { - '>' : True, - '<' : False, - '+' : True, - '-' : False - } - - self.operator = { - '+' : DirectionSelector, - '-' : DirectionSelector, - '#' : PerpendicularDirSelector, - '|' : ParallelDirSelector} - - self.parseResults = parseResults - self.mySelector = self._chooseSelector(parseResults) - - def _chooseSelector(self,pr): - """ - Sets up the underlying filters accordingly - """ - if 'only_dir' in pr: - vec = self._getVector(pr) - return DirectionSelector(vec) - - elif 'type_op' in pr: - return TypeSelector(pr.cq_type) - - elif 'dir_op' in pr: - vec = self._getVector(pr) - minmax = self.operatorMinMax[pr.dir_op] - - if 'index' in pr: - return DirectionNthSelector(vec,int(''.join(pr.index.asList())),minmax) - else: - return DirectionMinMaxSelector(vec,minmax) - - elif 'other_op' in pr: - vec = self._getVector(pr) - return self.operator[pr.other_op](vec) - - else: - args = self.namedViews[pr.named_view] - return DirectionMinMaxSelector(*args) - - def _getVector(self,pr): - """ - Translate parsed vector string into a CQ Vector - """ - if 'vector_dir' in pr: - vec = pr.vector_dir - return Vector(float(vec.x),float(vec.y),float(vec.z)) - else: - return self.axes[pr.simple_dir] - - def filter(self,objectList): - """ - selects minimum, maximum, positive or negative values relative to a direction - [+\|-\|<\|>\|] \ - """ - return self.mySelector.filter(objectList) - -def _makeExpressionGrammar(atom): - """ - Define the complex string selector grammar using PyParsing (which supports - logical operations and nesting) - """ - - #define operators - and_op = Literal('and') - or_op = Literal('or') - delta_op = oneOf(['exc','except']) - not_op = Literal('not') - - def atom_callback(res): - return _SimpleStringSyntaxSelector(res) - - atom.setParseAction(atom_callback) #construct a simple selector from every matched - - #define callback functions for all operations - def and_callback(res): - items = res.asList()[0][::2] #take every secend items, i.e. all operands - return reduce(AndSelector,items) - - def or_callback(res): - items = res.asList()[0][::2] #take every secend items, i.e. all operands - return reduce(SumSelector,items) - - def exc_callback(res): - items = res.asList()[0][::2] #take every secend items, i.e. all operands - return reduce(SubtractSelector,items) - - def not_callback(res): - right = res.asList()[0][1] #take second item, i.e. the operand - return InverseSelector(right) - - #construct the final grammar and set all the callbacks - expr = infixNotation(atom, - [(and_op,2,opAssoc.LEFT,and_callback), - (or_op,2,opAssoc.LEFT,or_callback), - (delta_op,2,opAssoc.LEFT,exc_callback), - (not_op,1,opAssoc.RIGHT,not_callback)]) - - return expr - -_expression_grammar = _makeExpressionGrammar(_grammar) - -class StringSyntaxSelector(Selector): - """ - Filter lists objects using a simple string syntax. All of the filters available in the string syntax - are also available ( usually with more functionality ) through the creation of full-fledged - selector objects. see :py:class:`Selector` and its subclasses - - Filtering works differently depending on the type of object list being filtered. - - :param selectorString: A two-part selector string, [selector][axis] - - :return: objects that match the specified selector - - ***Modfiers*** are ``('|','+','-','<','>','%')`` - - :\|: - parallel to ( same as :py:class:`ParallelDirSelector` ). Can return multiple objects. - :#: - perpendicular to (same as :py:class:`PerpendicularDirSelector` ) - :+: - positive direction (same as :py:class:`DirectionSelector` ) - :-: - negative direction (same as :py:class:`DirectionSelector` ) - :>: - maximize (same as :py:class:`DirectionMinMaxSelector` with directionMax=True) - :<: - minimize (same as :py:class:`DirectionMinMaxSelector` with directionMax=False ) - :%: - curve/surface type (same as :py:class:`TypeSelector`) - - ***axisStrings*** are: ``X,Y,Z,XY,YZ,XZ`` or ``(x,y,z)`` which defines an arbitrary direction - - It is possible to combine simple selectors together using logical operations. - The following operations are suuported - - :and: - Logical AND, e.g. >X and >Y - :or: - Logical OR, e.g. |X or |Y - :not: - Logical NOT, e.g. not #XY - :exc(ept): - Set difference (equivalent to AND NOT): |X exc >Z - - Finally, it is also possible to use even more complex expressions with nesting - and arbitrary number of terms, e.g. - - (not >X[0] and #XY) or >XY[0] - - Selectors are a complex topic: see :ref:`selector_reference` for more information - """ - def __init__(self,selectorString): - """ - Feed the input string through the parser and construct an relevant complex selector object - """ - self.selectorString = selectorString - parse_result = _expression_grammar.parseString(selectorString, - parseAll=True) - self.mySelector = parse_result.asList()[0] - - def filter(self,objectList): - """ - Filter give object list through th already constructed complex selector object - """ - return self.mySelector.filter(objectList) \ No newline at end of file diff --git a/Libs/cadquery-lib/changes.md b/Libs/cadquery-lib/changes.md deleted file mode 100644 index 24d08ab..0000000 --- a/Libs/cadquery-lib/changes.md +++ /dev/null @@ -1,100 +0,0 @@ -Changes -======= - - -v0.1 ------ - * Initial Version - -v0.1.6 ------ - * Added STEP import and supporting tests - -v0.1.7 ------ - * Added revolve operation and supporting tests - * Fixed minor documentation errors - -v0.1.8 ------ - * Added toFreecad() function as a convenience for val().wrapped - * Converted all examples to use toFreecad() - * Updated all version numbers that were missed before - * Fixed import issues in Windows caused by fc_import - * Added/fixed Mac OS support - * Improved STEP import - * Fixed bug in rotateAboutCenter that negated its effect on solids - * Added Travis config (thanks @krasin) - * Removed redundant workplane.py file left over from the PParts.com migration - * Fixed toWorldCoordinates bug in moveTo (thanks @xix-xeaon) - * Added new tests for 2D drawing functions - * Integrated Coveralls.io, with a badge in README.md - * Integrated version badge in README.md - -v0.2.0 ------ - * Fixed versioning to match the semantic versioning scheme - * Added license badge in changes.md - * Fixed Solid.makeSphere implementation - * Added CQ.sphere operation that mirrors CQ.box - * Updated copyright dates - * Cleaned up spelling and misc errors in docstrings - * Fixed FreeCAD import error on Arch Linux (thanks @moeb) - * Made FreeCAD import report import error instead of silently failing (thanks @moeb) - * Added ruled option for the loft operation (thanks @hyOzd) - * Fixed close() not working in planes other than XY (thanks @hyOzd) - * Added box selector with bounding box option (thanks @hyOzd) - * CQ.translate and CQ.rotate documentation fixes (thanks @hyOzd) - * Fixed centering of a sphere - * Increased test coverage - * Added a clean function to keep some operations from failing on solids that need simplified (thanks @hyOzd) - * Added a mention of the new Google Group to the readme - -v0.3.0 ------ - * Fixed a bug where clean() could not be called on appropriate objects other than solids (thanks @hyOzd) #108 - * Implemented new selectors that allow existing selectors to be combined with arithmetic/boolean operations (thanks @hyOzd) #110 - * Fixed a bug where only 1 random edge was returned with multiple min/max selector matches (thanks @hyOzd) #111 - * Implemented the creation of a workplane from multiple co-planar faces (thanks @hyOzd) #113 - * Fixed the operation of Center() when called on a compound with multiple solids - * Add the named planes ZX YX ZY to define different normals (thanks @galou) #115 - * Code cleanup in accordance with PEP 8 (thanks @galou) - * Fixed a bug with the close function not resetting the first point of the context correctly (thanks @huskier) - * Fixed the findSolid function so that it handles compounds #107 - * Changed the polyline function so that it adds edges to the stack instead of a wire #102 - * Add the ability to find the center of the bounding box, rather than the center of mass (thanks @huskier) #122 - * Changed normalize function to normalized to match OCC/PythonOCC nomenclature #124 - * Added a label attribute to all freecad_impl.shapes so that they can have IDs attached to them #124 - -v0.4.0 ------- - * Added Documentation, which is available on dcowden.github.io/cadquery - * Added CQGI, an adapter API that standardizes use of cadquery from within structured execution environments - * Added ability to import STEP files from a web URL (thanks @huskier ) #128 - -v0.4.1 ------- - * Minor CQGI updates - -v0.5.0-stable ------- - * Configuring Travis to push to PyPI on version releases. - -v0.5.1 ------- - * Mirroring fixes (thanks @huskier) - * Added a mirroring example (thanks @huskier) - -v0.5.2 ------- - * Added the sweep operation #33 - -v1.0.0 ------- - * Added an option to do symmetric extrusion about the workplane (thanks @adam-urbanczyk) - * Extended selector syntax to include Nth selector and re-implemented selectors using pyparsing (thanks @adam-urbanczyk) - * Added logical operations to string selectors (thanks @adam-urbanczyk) - * Cleanup of README.md and changes.md (thanks @baoboa) - * Fixed bugs with toVector and Face 'Not Defined' errors (thanks @huskier) - * Refactor of the initialization code for PEP8 compliance and Python 3 compatibility (thanks @Peque) - * Making sure that the new pyparsing library dependency is handled properly (thanks @Peque) diff --git a/Libs/cadquery-lib/doc/README b/Libs/cadquery-lib/doc/README deleted file mode 100644 index b89ab3d..0000000 --- a/Libs/cadquery-lib/doc/README +++ /dev/null @@ -1,2 +0,0 @@ -This documentation should be generated with sphinxdoc. -see ../build-docs.sh diff --git a/Libs/cadquery-lib/doc/_static/ParametricPulley.PNG b/Libs/cadquery-lib/doc/_static/ParametricPulley.PNG deleted file mode 100644 index c5e6e87..0000000 Binary files a/Libs/cadquery-lib/doc/_static/ParametricPulley.PNG and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/block.png b/Libs/cadquery-lib/doc/_static/block.png deleted file mode 100644 index d3e63a6..0000000 Binary files a/Libs/cadquery-lib/doc/_static/block.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/cadquery_cheatsheet.html b/Libs/cadquery-lib/doc/_static/cadquery_cheatsheet.html deleted file mode 100644 index bb58252..0000000 --- a/Libs/cadquery-lib/doc/_static/cadquery_cheatsheet.html +++ /dev/null @@ -1,404 +0,0 @@ - - - - CadQuery Cheatsheet - - - - - -
- -
-

BREP Terminology


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vertexA single point in space
edgeA connection between two or more vertices along a particular path (called a curve)
wireA collection of edges that are connected together
faceA set of edges or wires that enclose a surface
shellA collection of faces that are connected together along some of their edges
solidA shell that has a closed interior
compoundA collection of solids
-
-
-

Named Planes


- Available named planes are as follows. Direction references refer to the global directions. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NamexDiryDirzDir
XY+x+y+z
YZ+y+z+x
XZ+x+z-y
front+x+y+z
back-x+y-z
left+z+y-x
right-z+y+x
top+x-z+y
bottom+x+z-y
-
-
-

Core Classes


- - - - - - - - - - - - - - - - - -
ClassDescription
CQ(obj)Provides enhanced functionality for a wrapped CAD primitive.
Plane(origin, xDir, normal)A 2d coordinate system in space, with the x-y axes on the a plane, and a particular point as the origin.
Workplane(inPlane[origin, obj])Defines a coordinate system in space, in which 2-d coordinates can be used.
-
-
-
-
-

Selector Methods


- CadQuery selector strings allow filtering various types of object lists. - Most commonly, Edges, Faces, and Vertices are used, but all objects types can be filtered.
- - - - - - - - - - - - - - - - - - - - - - - - -
Selector MethodDescription
CQ.faces(selector=None)Select the faces of objects on the stack, optionally filtering the selection.
CQ.edges(selector=None)Select the edges of objects on the stack, optionally filtering the selection.
CQ.vertices(selector=None)Select the vertices of objects on the stack, optionally filtering the selection.
CQ.solids(selector=None)Select the solids of objects on the stack, optionally filtering the selection.
CQ.shells(selector=None)Select the shells of objects on the stack, optionally filtering the selection.
-
-
-

Selector Classes


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ClassDescription
NearestToPointSelector(pnt)Selects object nearest the provided point.
ParallelDirSelector(vector[tolerance])Selects objects parallel with the provided direction.
DirectionSelector(vector[tolerance])Selects objects aligned with the provided direction.
PerpendicularDirSelector(vector[tolerance])Selects objects perpendicular with the provided direction.
TypeSelector(typeString)Selects objects of the prescribed topological type.
DirectionMinMaxSelector(vector[directionMax])Selects objects closest or farthest in the specified direction.
StringSyntaxSelector(selectorString)Filter lists objects using a simple string syntax.
-
-
-

Selector String Modifiers


- Selectors are a complex topic: see CadQuery String Selectors for more information.
- Axis Strings are: X, Y, Z, XY, YZ, XZ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ModifierDescription
|Parallel to (same as ParallelDirSelector). Can return multiple objects.
#Perpendicular to (same as PerpendicularDirSelector)
+Positive direction (same as DirectionSelector)
-Negative direction (same as DirectionSelector)
>Maximize (same as DirectionMinMaxSelector with directionMax=True)
<Minimize (same as DirectionMinMaxSelector with directionMax=False)
%Curve/surface type (same as TypeSelector)
-
-
-

Examples of Filtering Faces


- All types of filters work on faces. In most cases, the selector refers to the direction of the normal vector of the face. - If a face is not planar, selectors are evaluated at the center of mass of the face. This can lead to results that are quite unexpected. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SelectorSelector ClassSelects# Objects Returned
+ZDirectionSelectorFaces with normal in +z direction0 or 1
|ZParallelDirSelectorFaces parallel to xy plane0..many
-XDirectionSelectorFaces with normal in neg x direction0..many
#ZPerpendicularDirSelectorFaces perpendicular to z direction0..many
%PlaneTypeSelectorFaces of type plane0..many
>YDirectionMinMaxSelectorFace farthest in the positive y dir0 or 1
<YDirectionMinMaxSelectorFace farthest in the negative y dir0 or 1
-
-
-

Examples of Filtering Edges


- Some filter types are not supported for edges. The selector usually refers to the direction of the edge. - Non-linear edges are not selected for any selectors except type (%). Non-linear edges are never returned when these filters are applied. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SelectorSelector ClassSelects# Objects Returned
+ZDirectionSelectorEdges aligned in the Z direction0..many
|ZParallelDirSelectorEdges parallel to z direction0..many
-XDirectionSelectorEdges aligned in neg x direction0..many
#ZPerpendicularDirSelectorEdges perpendicular to z direction0..many
%PlaneTypeSelectorEdges type line0..many
>YDirectionMinMaxSelectorEdges farthest in the positive y dir0 or 1
<YDirectionMinMaxSelectorEdges farthest in the negative y dir0 or 1
-
-
-

Examples of Filtering Vertices


- Only a few of the filter types apply to vertices. The location of the vertex is the subject of the filter. - - - - - - - - - - - - - - - - - - - -
SelectorSelector ClassSelects# Objects Returned
>YDirectionMinMaxSelectorVertices farthest in the positive y dir0 or 1
<YDirectionMinMaxSelectorVertices farthest in the negative y dir0 or 1
-
-
- - diff --git a/Libs/cadquery-lib/doc/_static/cqlogo.png b/Libs/cadquery-lib/doc/_static/cqlogo.png deleted file mode 100644 index 529ffef..0000000 Binary files a/Libs/cadquery-lib/doc/_static/cqlogo.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/hyOzd-cablefix.png b/Libs/cadquery-lib/doc/_static/hyOzd-cablefix.png deleted file mode 100644 index 2831731..0000000 Binary files a/Libs/cadquery-lib/doc/_static/hyOzd-cablefix.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/hyOzd-finished.jpg b/Libs/cadquery-lib/doc/_static/hyOzd-finished.jpg deleted file mode 100644 index ec56567..0000000 Binary files a/Libs/cadquery-lib/doc/_static/hyOzd-finished.jpg and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/new_badge.png b/Libs/cadquery-lib/doc/_static/new_badge.png deleted file mode 100644 index 7a2a1fe..0000000 Binary files a/Libs/cadquery-lib/doc/_static/new_badge.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/parametric-cup-screencap.PNG b/Libs/cadquery-lib/doc/_static/parametric-cup-screencap.PNG deleted file mode 100644 index b9ee082..0000000 Binary files a/Libs/cadquery-lib/doc/_static/parametric-cup-screencap.PNG and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/parametric-pillowblock-screencap.png b/Libs/cadquery-lib/doc/_static/parametric-pillowblock-screencap.png deleted file mode 100644 index 76d5e38..0000000 Binary files a/Libs/cadquery-lib/doc/_static/parametric-pillowblock-screencap.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/pillowblock.png b/Libs/cadquery-lib/doc/_static/pillowblock.png deleted file mode 100644 index 00f5c62..0000000 Binary files a/Libs/cadquery-lib/doc/_static/pillowblock.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart-1.png b/Libs/cadquery-lib/doc/_static/quickstart-1.png deleted file mode 100644 index 6dd6e9a..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart-1.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart-2.png b/Libs/cadquery-lib/doc/_static/quickstart-2.png deleted file mode 100644 index 6dd6e9a..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart-2.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart-3.png b/Libs/cadquery-lib/doc/_static/quickstart-3.png deleted file mode 100644 index e4997f0..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart-3.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart-4.png b/Libs/cadquery-lib/doc/_static/quickstart-4.png deleted file mode 100644 index e3d7568..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart-4.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart-5.png b/Libs/cadquery-lib/doc/_static/quickstart-5.png deleted file mode 100644 index 45430d9..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart-5.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart.png b/Libs/cadquery-lib/doc/_static/quickstart.png deleted file mode 100644 index 467b9c7..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/000.png b/Libs/cadquery-lib/doc/_static/quickstart/000.png deleted file mode 100644 index 6b03524..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/000.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/001.png b/Libs/cadquery-lib/doc/_static/quickstart/001.png deleted file mode 100644 index 76d8796..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/001.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/002.png b/Libs/cadquery-lib/doc/_static/quickstart/002.png deleted file mode 100644 index 8b8ab36..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/002.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/003.png b/Libs/cadquery-lib/doc/_static/quickstart/003.png deleted file mode 100644 index 8aaa128..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/003.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/004.png b/Libs/cadquery-lib/doc/_static/quickstart/004.png deleted file mode 100644 index 880ffd0..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/004.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/quickstart/005.png b/Libs/cadquery-lib/doc/_static/quickstart/005.png deleted file mode 100644 index 0dbbb12..0000000 Binary files a/Libs/cadquery-lib/doc/_static/quickstart/005.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/_static/simpleblock.png b/Libs/cadquery-lib/doc/_static/simpleblock.png deleted file mode 100644 index 5ac6905..0000000 Binary files a/Libs/cadquery-lib/doc/_static/simpleblock.png and /dev/null differ diff --git a/Libs/cadquery-lib/doc/apireference.rst b/Libs/cadquery-lib/doc/apireference.rst deleted file mode 100644 index 55aea7d..0000000 --- a/Libs/cadquery-lib/doc/apireference.rst +++ /dev/null @@ -1,168 +0,0 @@ -.. _apireference: - -*********************** -CadQuery API Reference -*********************** - -The CadQuery API is made up of 3 main objects: - -* **CQ** - An object that wraps a topological entity. -* **Workplane** -- A subclass of CQ, that applies in a 2-D modelling context. -* **Selector** -- Filter and select things - -This page lists methods of these objects grouped by **functional area** - -.. seealso:: - This page lists api methods grouped by functional area. - Use :ref:`classreference` to see methods alphabetically by class. - - -Initialization ----------------- - -.. currentmodule:: cadquery - -Creating new workplanes and object chains - -.. autosummary:: - CQ - Workplane - - -.. _2dOperations: - -2-d Operations ------------------ - -Creating 2-d constructs that can be used to create 3 d features. - -All 2-d operations require a **Workplane** object to be created. - -.. currentmodule:: cadquery - -.. autosummary:: - Workplane.center - Workplane.lineTo - Workplane.line - Workplane.vLine - Workplane.vLineTo - Workplane.hLine - Workplane.moveTo - Workplane.move - Workplane.spline - Workplane.threePointArc - Workplane.rotateAndCopy - Workplane.mirrorY - Workplane.mirrorX - Workplane.wire - Workplane.rect - Workplane.circle - Workplane.polyline - Workplane.close - Workplane.rarray - -.. _3doperations: - -3-d Operations ------------------ - -Some 3-d operations also require an active 2-d workplane, but some do not. - -3-d operations that require a 2-d workplane to be active: - -.. autosummary:: - Workplane.cboreHole - Workplane.cskHole - Workplane.hole - Workplane.extrude - Workplane.cut - Workplane.cutBlind - Workplane.cutThruAll - Workplane.box - Workplane.union - Workplane.combine - -3-d operations that do NOT require a 2-d workplane to be active: - -.. autosummary:: - CQ.shell - CQ.fillet - CQ.split - CQ.rotate - CQ.rotateAboutCenter - CQ.translate - -File Management and Export ---------------------------------- - -.. autosummary:: - CQ.toSvg - CQ.exportSvg - - -.. autosummary:: - importers.importStep - exporters.exportShape - - -Iteration Methods ------------------- - -Methods that allow iteration over the stack or objects - -.. autosummary:: - Workplane.each - Workplane.eachpoint - - -.. _stackMethods: - -Stack and Selector Methods ------------------------------- - -CadQuery methods that operate on the stack - -.. autosummary:: - CQ.all - CQ.size - CQ.vals - CQ.add - CQ.val - CQ.first - CQ.item - CQ.last - CQ.end - CQ.vertices - CQ.faces - CQ.edges - CQ.wires - CQ.solids - CQ.shells - CQ.compounds - -.. _selectors: - -Selectors ------------------------- - -Objects that filter and select CAD objects. Selectors are used to select existing geometry -as a basis for futher operations. - -.. currentmodule:: cadquery - -.. autosummary:: - - NearestToPointSelector - BoxSelector - BaseDirSelector - ParallelDirSelector - DirectionSelector - PerpendicularDirSelector - TypeSelector - DirectionMinMaxSelector - BinarySelector - AndSelector - SumSelector - SubtractSelector - InverseSelector - StringSyntaxSelector diff --git a/Libs/cadquery-lib/doc/classreference.rst b/Libs/cadquery-lib/doc/classreference.rst deleted file mode 100644 index b072b39..0000000 --- a/Libs/cadquery-lib/doc/classreference.rst +++ /dev/null @@ -1,70 +0,0 @@ -.. _classreference: - -************************* -CadQuery Class Summary -************************* - -This page documents all of the methods and functions of the CadQuery classes, organized alphabatically. - -.. seealso:: - - For a listing organized by functional area, see the :ref:`apireference` - -.. currentmodule:: cadquery - -Core Classes ---------------------- - -.. autosummary:: - CQ - Workplane - -Topological Classes ----------------------- - -.. autosummary:: - Shape - Vertex - Edge - Wire - Face - Shell - Solid - Compound - -Geometry Classes ------------------- - -.. autosummary:: - Vector - Matrix - Plane - -Selector Classes ---------------------- - - -.. autosummary:: - - Selector - NearestToPointSelector - BoxSelector - BaseDirSelector - ParallelDirSelector - DirectionSelector - PerpendicularDirSelector - TypeSelector - DirectionMinMaxSelector - BinarySelector - AndSelector - SumSelector - SubtractSelector - InverseSelector - StringSyntaxSelector - - -Class Details ---------------- - -.. automodule:: cadquery - :members: diff --git a/Libs/cadquery-lib/doc/conf.py b/Libs/cadquery-lib/doc/conf.py deleted file mode 100644 index fb76407..0000000 --- a/Libs/cadquery-lib/doc/conf.py +++ /dev/null @@ -1,276 +0,0 @@ -# -*- coding: utf-8 -*- -# -# CadQuery documentation build configuration file, created by -# sphinx-quickstart on Sat Aug 25 21:10:53 2012. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os -import os.path -#print "working path is %s" % os.getcwd() -#sys.path.append("../cadquery") -import cadquery - -#settings._target = None - - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary','cadquery.cq_directive'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'CadQuery' -copyright = u'Parametric Products Intellectual Holdings LLC, All Rights Reserved' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '1.0' -# The full version, including alpha/beta/rc tags. -release = '1.0.0' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -#html_theme = 'timlinux-linfiniti-sphinx' -html_theme = 'sphinx_rtd_theme' - - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = { -# "headerfont": "'Open Sans',Arial,sans-serif", -# #"bodyfont:": "'Open Sans',Arial,sans-serif", -# #"headerbg" : "{image: url('/img/bg/body.jpg');color:#000000;}", -# "headerbg" : "color:black;", -# "footerbg" : "{color:#13171A;}", -# "linkcolor": "#84B51E;", -## "headercolor1": "#13171A;", -# "headercolor2": "#444;", -# "headerlinkcolor" : "#13171A;", -#} - -#agogo options -""" - bodyfont (CSS font family): Font for normal text. - headerfont (CSS font family): Font for headings. - pagewidth (CSS length): Width of the page content, default 70em. - documentwidth (CSS length): Width of the document (without sidebar), default 50em. - sidebarwidth (CSS length): Width of the sidebar, default 20em. - bgcolor (CSS color): Background color. - headerbg (CSS value for “background”): background for the header area, default a grayish gradient. - footerbg (CSS value for “background”): background for the footer area, default a light gray gradient. - linkcolor (CSS color): Body link color. - headercolor1, headercolor2 (CSS color): colors for

and

headings. - headerlinkcolor (CSS color): Color for the backreference link in headings. - textalign (CSS text-align value): Text alignment for the body, default is justify. -""" -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -html_title = "CadQuery Documentation" - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -html_logo = "_static/cqlogo.png" - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -html_show_sourcelink = False - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -html_show_sphinx = False - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'CadQuerydoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'CadQuery.tex', u'CadQuery Documentation', - u'David Cowden', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'cadquery', u'CadQuery Documentation', - [u'David Cowden'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'CadQuery', u'CadQuery Documentation', - u'David Cowden', 'CadQuery', 'A Fluent CAD api', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' diff --git a/Libs/cadquery-lib/doc/cqgi.rst b/Libs/cadquery-lib/doc/cqgi.rst deleted file mode 100644 index 310f7d2..0000000 --- a/Libs/cadquery-lib/doc/cqgi.rst +++ /dev/null @@ -1,164 +0,0 @@ -.. _cqgi: - -The CadQuery Gateway Interface -==================================== - - -CadQuery is first and foremost designed as a library, which can be used as a part of any project. -In this context, there is no need for a standard script format or gateway api. - -Though the embedded use case is the most common, several tools have been created which run -cadquery scripts on behalf of the user, and then render the result of the script visually. - -These execution environments (EE) generally accept a script and user input values for -script parameters, and then display the resulting objects visually to the user. - -Today, three execution environments exist: - - * `The CadQuery Freecad Module `_, which runs scripts - inside of the FreeCAD IDE, and displays objects in the display window - * the cq-directive, which is used to execute scripts inside of sphinx-doc, - producing documented examples that include both a script and an SVG representation of the object that results - * `ParametricParts.com `_, which provides a web-based way to prompt user input for - variables, and then display the result output in a web page. - -The CQGI is distributed with cadquery, and standardizes the interface between execution environments and cadquery scripts. - - -The Script Side ------------------ - -CQGI compliant containers provide an execution environment for scripts. The environment includes: - - * the cadquery library is automatically imported as 'cq'. - * the :py:meth:`cadquery.cqgi.ScriptCallback.build_object()` method is defined that should be used to export a shape to the execution environment - * the :py:meth:`cadquery.cqgi.ScriptCallBack.debug()` method is defined, which can be used by scripts to debug model output during execution. - -Scripts must call build_output at least once. Invoking build_object more than once will send multiple objects to -the container. An error will occur if the script does not return an object using the build_object() method. - -This CQGI compliant script produces a cube with a circle on top, and displays a workplane as well as an intermediate circle as debug output:: - - base_cube = cq.Workplane('XY').rect(1.0,1.0).extrude(1.0) - top_of_cube_plane = base_cube.faces(">Z").workplane() - debug(top_of_cube_plane, { 'color': 'yellow', } ) - debug(top_of_cube_plane.center, { 'color' : 'blue' } ) - - circle=top_of_cube_plane.circle(0.5) - debug(circle, { 'color': 'red' } ) - - build_object( circle.extrude(1.0) ) - -Note that importing cadquery is not required. -At the end of this script, one object will be displayed, in addition to a workplane, a point, and a circle - -Future enhancements will include several other methods, used to provide more metadata for the execution environment: - * :py:meth:`cadquery.cqgi.ScriptCallback.add_error()`, indicates an error with an input parameter - * :py:meth:`cadquery.cqgi.ScriptCallback.describe_parameter()`, provides extra information about a parameter in the script, - - -The execution environment side -------------------------------- - -CQGI makes it easy to run cadquery scripts in a standard way. To run a script from an execution environment, -run code like this:: - - from cadquery import cqgi - - user_script = ... - build_result = cqgi.parse(user_script).build() - -The :py:meth:`cadquery.cqgi.parse()` method returns a :py:class:`cadquery.cqgi.CQModel` object. - -The `metadata`p property of the object contains a `cadquery.cqgi.ScriptMetaData` object, which can be used to discover the -user parameters available. This is useful if the execution environment would like to present a GUI to allow the user to change the -model parameters. Typically, after collecting new values, the environment will supply them in the build() method. - -This code will return a dictionary of parameter values in the model text SCRIPT:: - - parameters = cqgi.parse(SCRIPT).metadata.parameters - -The dictionary you get back is a map where key is the parameter name, and value is an InputParameter object, -which has a name, type, and default value. - -The type is an object which extends ParameterType-- you can use this to determine what kind of widget to render ( checkbox for boolean, for example ). - -The parameter object also has a description, valid values, minimum, and maximum values, if the user has provided them using the -describe_parameter() method. - - - -Calling :py:meth:`cadquery.cqgi.CQModel.build()` returns a :py:class:`cadquery.cqgi.BuildResult` object, -,which includes the script execution time, and a success flag. - -If the script was successful, the results property will include a list of results returned by the script, -as well as any debug the script produced - -If the script failed, the exception property contains the exception object. - -If you have a way to get inputs from a user, you can override any of the constants defined in the user script -with new values:: - - from cadquery import cqgi - - user_script = ... - build_result = cqgi.parse(user_script).build(build_parameters={ 'param': 2 }, build_options={} ) - -If a parameter called 'param' is defined in the model, it will be assigned the value 2 before the script runs. -An error will occur if a value is provided that is not defined in the model, or if the value provided cannot -be assigned to a variable with the given name. - -build_options is used to set server-side settings like timeouts, tesselation tolerances, and other details about -how the model should be built. - - -More about script variables ------------------------------ - -CQGI uses the following rules to find input variables for a script: - - * only top-level statements are considered - * only assignments of constant values to a local name are considered. - -For example, in the following script:: - - h = 1.0 - w = 2.0 - foo = 'bar' - - def some_function(): - x = 1 - -h, w, and foo will be overridable script variables, but x is not. - -You can list the variables defined in the model by using the return value of the parse method:: - - model = cqgi.parse(user_script) - - //a dictionary of InputParameter objects - parameters = model.metadata.parameters - -The key of the dictionary is a string , and the value is a :py:class:`cadquery.cqgi.InputParameter` object -See the CQGI API docs for more details. - -Future enhancments will include a safer sandbox to prevent malicious scripts. - -Important CQGI Methods -------------------------- - -These are the most important Methods and classes of the CQGI - -.. currentmodule:: cadquery.cqgi - -.. autosummary:: - parse - CQModel.build - BuildResult - ScriptCallback.build_object - -Complete CQGI api ------------------ - -.. automodule:: cadquery.cqgi - :members: - diff --git a/Libs/cadquery-lib/doc/designprinciples.rst b/Libs/cadquery-lib/doc/designprinciples.rst deleted file mode 100644 index a74c8c3..0000000 --- a/Libs/cadquery-lib/doc/designprinciples.rst +++ /dev/null @@ -1,74 +0,0 @@ -.. _designprinciples: - - -=========================== -CadQuery Design Principles -=========================== - - -Principle 1: Intuitive Construction -==================================== - -CadQuery aims to make building models using python scripting easy and intuitive. -CadQuery strives to allow scripts to read roughly as a human would describe an object verbally. - -For example, consider this object: - -.. image:: _static/quickstart.png - -A human would describe this as: - - "A block 80mm square x 30mm thick , with countersunk holes for M2 socket head cap screws - at the corners, and a circular pocket 22mm in diameter in the middle for a bearing" - -The goal is to have the CadQuery script that produces this object be as close as possible to the english phrase -a human would use. - - -Principle 2: Capture Design Intent -==================================== - -The features that are **not** part of the part description above are just as important as those that are. For example, most -humans will assume that: - - * The countersunk holes are spaced a uniform distance from the edges - * The circular pocket is in the center of the block, no matter how big the block is - -If you have experience with 3D CAD systems, you also know that there is a key design intent built into this object. -After the base block is created, how the hole is located is key. If it is located from one edge, changing the block -size will have a different affect than if the hole is located from the center. - -Many scripting langauges do not provide a way to capture design intent-- because they require that you always work in -global coordinates. CadQuery is different-- you can locate features relative to others in a relative way-- preserving -the design intent just like a human would when creating a drawing or building an object. - -In fact, though many people know how to use 3D CAD systems, few understand how important the way that an object is built -impact its maintainability and resiliency to design changes. - - -Principle 3: Plugins as first class citizens -============================================ - -Any system for building 3D models will evolve to contain an immense number of libraries and feature builders. It is -important that these can be seamlessly included into the core and used alongside the built in libraries. Plugins -should be easy to install and familiar to use. - - -Principle 4: CAD models as source code makes sense -================================================================== - -It is surprising that the world of 3D CAD is primarily dominated by systems that create opaque binary files. -Just like the world of software, CAD models are very complex. - -CAD models have many things in common with software, and would benefit greatly from the use of tools that are standard -in the software industry, such as: - - 1. Easily re-using features between objects - 2. Storing objects using version control systems - 3. Computing the differences between objects by using source control tools - 4. Share objects on the internet - 5. Automate testing and generation by allowing objects to be built from within libraries - -CadQuery is designed to make 3D content creation easy enough that the above benefits can be attained without more work -than using existing 'opaque', 'point and click' solutions. - diff --git a/Libs/cadquery-lib/doc/examples.rst b/Libs/cadquery-lib/doc/examples.rst deleted file mode 100644 index 06c79aa..0000000 --- a/Libs/cadquery-lib/doc/examples.rst +++ /dev/null @@ -1,1096 +0,0 @@ -.. _examples: - -********************************* -CadQuery Examples -********************************* - - - -The examples on this page can help you learn how to build objects with CadQuery. - -They are organized from simple to complex, so working through them in order is the best way to absorb them. - -Each example lists the api elements used in the example for easy reference. -Items introduced in the example are marked with a **!** - -.. note:: - - You may want to work through these examples by pasting the text into a scratchpad on the live website. - If you do, make sure to take these steps so that they work: - - 1. paste the content into the build() method, properly intented, and - 2. add the line 'return result' at the end. The samples below are autogenerated, but they use a different - syntax than the models on the website need to be. - -.. note:: - - We strongly recommend installing FreeCAD, and the `cadquery-freecad-module `_, - so that you can work along with these examples interactively. See :ref:`installation` for more info. - -.. warning:: - - * You have to have an svg capable browser to view these! - -.. contents:: List of Examples - :backlinks: entry - - -Simple Rectangular Plate ------------------------- - -Just about the simplest possible example, a rectangular box - -.. cq_plot:: - - result = cadquery.Workplane("front").box(2.0, 2.0, 0.5) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane` **!** - * :py:meth:`Workplane.box` **!** - -Plate with Hole ------------------------- - -A rectangular box, but with a hole added. - -"\>Z" selects the top most face of the resulting box. The hole is located in the center because the default origin -of a working plane is at the center of the face. The default hole depth is through the entire part. - -.. cq_plot:: - - # The dimensions of the box. These can be modified rather than changing the - # object's code directly. - length = 80.0 - height = 60.0 - thickness = 10.0 - center_hole_dia = 22.0 - - # Create a box based on the dimensions above and add a 22mm center hole - result = cq.Workplane("XY").box(length, height, thickness) \ - .faces(">Z").workplane().hole(center_hole_dia) - - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.hole` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.box` - -An extruded prismatic solid -------------------------------- - -Build a prismatic solid using extrusion. After a drawing operation, the center of the previous object -is placed on the stack, and is the reference for the next operation. So in this case, the rect() is drawn -centered on the previously draw circle. - -By default, rectangles and circles are centered around the previous working point. - -.. cq_plot:: - - result = cq.Workplane("front").circle(2.0).rect(0.5, 0.75).extrude(0.5) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.circle` **!** - * :py:meth:`Workplane.rect` **!** - * :py:meth:`Workplane.extrude` **!** - * :py:meth:`Workplane` - -Building Profiles using lines and arcs --------------------------------------- - -Sometimes you need to build complex profiles using lines and arcs. This example builds a prismatic -solid from 2-d operations. - -2-d operations maintain a current point, which is initially at the origin. Use close() to finish a -closed curve. - - -.. cq_plot:: - - result = cq.Workplane("front").lineTo(2.0, 0).lineTo(2.0, 1.0).threePointArc((1.0, 1.5),(0.0, 1.0))\ - .close().extrude(0.25) - build_object(result) - - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.threePointArc` **!** - * :py:meth:`Workplane.lineTo` **!** - * :py:meth:`Workplane.extrude` - * :py:meth:`Workplane` - -Moving The Current working point ---------------------------------- - -In this example, a closed profile is required, with some interior features as well. - -This example also demonstrates using multiple lines of code instead of longer chained commands, -though of course in this case it was possible to do it in one long line as well. - -A new work plane center can be established at any point. - -.. cq_plot:: - - result = cq.Workplane("front").circle(3.0) #current point is the center of the circle, at (0,0) - result = result.center(1.5, 0.0).rect(0.5, 0.5) # new work center is (1.5, 0.0) - - result = result.center(-1.5, 1.5).circle(0.25) # new work center is ( 0.0, 1.5). - #the new center is specified relative to the previous center, not global coordinates! - - result = result.extrude(0.25) - build_object(result) - - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.center` **!** - * :py:meth:`Workplane` - * :py:meth:`Workplane.circle` - * :py:meth:`Workplane.rect` - * :py:meth:`Workplane.extrude` - -Using Point Lists ---------------------------- - -Sometimes you need to create a number of features at various locations, and using :py:meth:`Workplane.center` -is too cumbersome. - -You can use a list of points to construct multiple objects at once. Most construction methods, -like :py:meth:`Workplane.circle` and :py:meth:`Workplane.rect`, will operate on multiple points if they are on the stack - -.. cq_plot:: - - r = cq.Workplane("front").circle(2.0) # make base - r = r.pushPoints( [ (1.5, 0),(0, 1.5),(-1.5, 0),(0, -1.5) ] ) # now four points are on the stack - r = r.circle( 0.25 ) # circle will operate on all four points - result = r.extrude(0.125 ) # make prism - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.points` **!** - * :py:meth:`Workplane` - * :py:meth:`Workplane.circle` - * :py:meth:`Workplane.extrude` - -Polygons -------------------------- - -You can create polygons for each stack point if you would like. Useful in 3d printers whos firmware does not -correct for small hole sizes. - -.. cq_plot:: - - result = cq.Workplane("front").box(3.0, 4.0, 0.25).pushPoints ( [ ( 0,0.75 ),(0, -0.75) ]) \ - .polygon(6, 1.0).cutThruAll() - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.polygon` **!** - * :py:meth:`Workplane.pushPoints` - * :py:meth:`Workplane.box` - -Polylines -------------------------- - -:py:meth:`Workplane.polyline` allows creating a shape from a large number of chained points connected by lines. - -This example uses a polyline to create one half of an i-beam shape, which is mirrored to create the final profile. - -.. cq_plot:: - - (L,H,W,t) = ( 100.0, 20.0, 20.0, 1.0) - pts = [ - (0,H/2.0), - (W/2.0,H/2.0), - (W/2.0,(H/2.0 - t)), - (t/2.0,(H/2.0-t)), - (t/2.0,(t - H/2.0)), - (W/2.0,(t -H/2.0)), - (W/2.0,H/-2.0), - (0,H/-2.0) - ] - result = cq.Workplane("front").polyline(pts).mirrorY().extrude(L) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.polyline` **!** - * :py:meth:`Workplane` - * :py:meth:`Workplane.mirrorY` - * :py:meth:`Workplane.extrude` - - - -Defining an Edge with a Spline ------------------------------- - -This example defines a side using a spline curve through a collection of points. Useful when you have an edge that -needs a complex profile - -.. cq_plot:: - - s = cq.Workplane("XY") - sPnts = [ - (2.75, 1.5), - (2.5, 1.75), - (2.0, 1.5), - (1.5, 1.0), - (1.0, 1.25), - (0.5, 1.0), - (0, 1.0) - ] - r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close() - result = r.extrude(0.5) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.spline` **!** - * :py:meth:`Workplane` - * :py:meth:`Workplane.close` - * :py:meth:`Workplane.lineTo` - * :py:meth:`Workplane.extrude` - -Mirroring Symmetric Geometry ------------------------------ - -You can mirror 2-d geometry when your shape is symmetric. In this example we also -introduce horizontal and vertical lines, which make for slightly easier coding. - - -.. cq_plot:: - - r = cq.Workplane("front").hLine(1.0) # 1.0 is the distance, not coordinate - r = r.vLine(0.5).hLine(-0.25).vLine(-0.25).hLineTo(0.0) # hLineTo allows using xCoordinate not distance - result =r.mirrorY().extrude(0.25 ) # mirror the geometry and extrude - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.hLine` **!** - * :py:meth:`Workplane.vLine` **!** - * :py:meth:`Workplane.hLineTo` **!** - * :py:meth:`Workplane.mirrorY` **!** - * :py:meth:`Workplane.mirrorX` **!** - * :py:meth:`Workplane` - * :py:meth:`Workplane.extrude` - -Mirroring 3D Objects ------------------------------ - -.. cq_plot:: - - result0 = (cadquery.Workplane("XY") - .moveTo(10,0) - .lineTo(5,0) - .threePointArc((3.9393,0.4393),(3.5,1.5)) - .threePointArc((3.0607,2.5607),(2,3)) - .lineTo(1.5,3) - .threePointArc((0.4393,3.4393),(0,4.5)) - .lineTo(0,13.5) - .threePointArc((0.4393,14.5607),(1.5,15)) - .lineTo(28,15) - .lineTo(28,13.5) - .lineTo(24,13.5) - .lineTo(24,11.5) - .lineTo(27,11.5) - .lineTo(27,10) - .lineTo(22,10) - .lineTo(22,13.2) - .lineTo(14.5,13.2) - .lineTo(14.5,10) - .lineTo(12.5,10 ) - .lineTo(12.5,13.2) - .lineTo(5.5,13.2) - .lineTo(5.5,2) - .threePointArc((5.793,1.293),(6.5,1)) - .lineTo(10,1) - .close()) - result = result0.extrude(100) - - result = result.rotate((0, 0, 0),(1, 0, 0), 90) - - result = result.translate(result.val().BoundingBox().center.multiply(-1)) - - mirXY_neg = result.mirror(mirrorPlane="XY", basePointVector=(0, 0, -30)) - mirXY_pos = result.mirror(mirrorPlane="XY", basePointVector=(0, 0, 30)) - mirZY_neg = result.mirror(mirrorPlane="ZY", basePointVector=(-30,0,0)) - mirZY_pos = result.mirror(mirrorPlane="ZY", basePointVector=(30,0,0)) - - result = result.union(mirXY_neg).union(mirXY_pos).union(mirZY_neg).union(mirZY_pos) - - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.moveTo` - * :py:meth:`Workplane.lineTo` - * :py:meth:`Workplane.threePointArc` - * :py:meth:`Workplane.extrude` - * :py:meth:`Workplane.mirror` - * :py:meth:`Workplane.union` - * :py:meth:`CQ.rotate` - -Creating Workplanes on Faces ------------------------------ - -This example shows how to locate a new workplane on the face of a previously created feature. - -.. note:: - Using workplanes in this way are a key feature of CadQuery. Unlike typical 3d scripting language, - using work planes frees you from tracking the position of various features in variables, and - allows the model to adjust itself with removing redundant dimensions - -The :py:meth:`Workplane.faces()` method allows you to select the faces of a resulting solid. It accepts -a selector string or object, that allows you to target a single face, and make a workplane oriented on that -face. - -Keep in mind that the origin of new workplanes are located at the center of a face by default. - -.. cq_plot:: - - result = cq.Workplane("front").box(2,3, 0.5) #make a basic prism - result = result.faces(">Z").workplane().hole(0.5) #find the top-most face and make a hole - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.faces` **!** - * :py:meth:`StringSyntaxSelector` **!** - * :ref:`selector_reference` **!** - * :py:meth:`Workplane.workplane` - * :py:meth:`Workplane.box` - * :py:meth:`Workplane` - -Locating a Workplane on a vertex ---------------------------------- - -Normally, the :py:meth:`Workplane.workplane` method requires a face to be selected. But if a vertex is selected -**immediately after a face**, :py:meth:`Workplane.workplane` will locate the workplane on the face, with the origin at the vertex instead -of at the center of the face - -The example also introduces :py:meth:`Workplane.cutThruAll`, which makes a cut through the entire part, no matter -how deep the part is - -.. cq_plot:: - - result = cq.Workplane("front").box(3,2, 0.5) #make a basic prism - result = result.faces(">Z").vertices("Z").workplane() \ - .transformed(offset=cq.Vector(0, -1.5, 1.0),rotate=cq.Vector(60, 0, 0)) \ - .rect(1.5,1.5,forConstruction=True).vertices().hole(0.25) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.transformed` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.rect` - * :py:meth:`Workplane.faces` - -Using construction Geometry ---------------------------- - -You can draw shapes to use the vertices as points to locate other features. Features that are used to -locate other features, rather than to create them, are called ``Construction Geometry`` - -In the example below, a rectangle is drawn, and its vertices are used to locate a set of holes. - -.. cq_plot:: - - result = cq.Workplane("front").box(2, 2, 0.5).faces(">Z").workplane() \ - .rect(1.5, 1.5, forConstruction=True).vertices().hole(0.125 ) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.rect` (forConstruction=True) - * :ref:`selector_reference` - * :py:meth:`Workplane.workplane` - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.hole` - * :py:meth:`Workplane` - -Shelling To Create Thin features --------------------------------- - -Shelling converts a solid object into a shell of uniform thickness. To shell an object, one or more faces -are removed, and then the inside of the solid is 'hollowed out' to make the shell. - - -.. cq_plot:: - - result = cq.Workplane("front").box(2, 2, 2).faces("+Z").shell(0.05) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.shell` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.faces` - * :py:meth:`Workplane` - -Making Lofts --------------------------------------------- - -A loft is a solid swept through a set of wires. This example creates lofted section between a rectangle -and a circular section. - -.. cq_plot:: - - result = cq.Workplane("front").box(4.0, 4.0, 0.25).faces(">Z").circle(1.5) \ - .workplane(offset=3.0).rect(0.75, 0.5).loft(combine=True) - - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.loft` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.faces` - * :py:meth:`Workplane.circle` - * :py:meth:`Workplane.rect` - -Making Counter-bored and counter-sunk holes ----------------------------------------------- - -Counterbored and countersunk holes are so common that CadQuery creates macros to create them in a single step. - -Similar to :py:meth:`Workplane.hole` , these functions operate on a list of points as well as a single point. - -.. cq_plot:: - - result = cq.Workplane(cq.Plane.XY()).box(4,2, 0.5).faces(">Z").workplane().rect(3.5, 1.5, forConstruction=True)\ - .vertices().cboreHole(0.125, 0.25, 0.125, depth=None) - - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.cboreHole` **!** - * :py:meth:`Workplane.cskHole` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.rect` - * :py:meth:`Workplane.workplane` - * :py:meth:`Workplane.vertices` - * :py:meth:`Workplane.faces` - * :py:meth:`Workplane` - -Rounding Corners with Fillet ------------------------------ - -Filleting is done by selecting the edges of a solid, and using the fillet function. - -Here we fillet all of the edges of a simple plate. - -.. cq_plot:: - - result = cq.Workplane("XY" ).box(3, 3, 0.5).edges("|Z").fillet(0.125) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.fillet` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.edges` - * :py:meth:`Workplane` - -A Parametric Bearing Pillow Block ------------------------------------- - -Combining a few basic functions, its possible to make a very good parametric bearing pillow block, -with just a few lines of code. - -.. cq_plot:: - - (length,height,bearing_diam, thickness,padding) = ( 30.0, 40.0, 22.0, 10.0, 8.0) - - result = cq.Workplane("XY").box(length,height,thickness).faces(">Z").workplane().hole(bearing_diam) \ - .faces(">Z").workplane() \ - .rect(length-padding,height-padding,forConstruction=True) \ - .vertices().cboreHole(2.4, 4.4, 2.1) - - build_object(result) - - -Splitting an Object ---------------------- - -You can split an object using a workplane, and retain either or both halves - -.. cq_plot:: - - c = cq.Workplane("XY").box(1,1,1).faces(">Z").workplane().circle(0.25).cutThruAll() - - #now cut it in half sideways - result = c.faces(">Y").workplane(-0.5).split(keepTop=True) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.split` **!** - * :py:meth:`Workplane.box` - * :py:meth:`Workplane.circle` - * :py:meth:`Workplane.cutThruAll` - * :py:meth:`Workplane.workplane` - * :py:meth:`Workplane` - -The Classic OCC Bottle ----------------------- - -CadQuery is based on the OpenCascade.org (OCC) modeling Kernel. Those who are familiar with OCC know about the -famous 'bottle' example. http://www.opencascade.org/org/gettingstarted/appli/ - -A pythonOCC version is listed here - http://code.google.com/p/pythonocc/source/browse/trunk/src/examples/Tools/InteractiveViewer/scripts/Bottle.py?r=1046 - -Of course one difference between this sample and the OCC version is the length. This sample is one of the longer -ones at 13 lines, but that's very short compared to the pythonOCC version, which is 10x longer! - - -.. cq_plot:: - - (L,w,t) = (20.0, 6.0, 3.0) - s = cq.Workplane("XY") - - #draw half the profile of the bottle and extrude it - p = s.center(-L/2.0, 0).vLine(w/2.0) \ - .threePointArc((L/2.0, w/2.0 + t),(L, w/2.0)).vLine(-w/2.0) \ - .mirrorX().extrude(30.0,True) - - #make the neck - p.faces(">Z").workplane().circle(3.0).extrude(2.0,True) - - #make a shell - result = p.faces(">Z").shell(0.3) - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 2 - - * :py:meth:`Workplane.extrude` - * :py:meth:`Workplane.mirrorX` - * :py:meth:`Workplane.threePointArc` - * :py:meth:`Workplane.workplane` - * :py:meth:`Workplane.vertices` - * :py:meth:`Workplane.vLine` - * :py:meth:`Workplane.faces` - * :py:meth:`Workplane` - -A Parametric Enclosure ------------------------ - -.. cq_plot:: - :height: 400 - - #parameter definitions - p_outerWidth = 100.0 #Outer width of box enclosure - p_outerLength = 150.0 #Outer length of box enclosure - p_outerHeight = 50.0 #Outer height of box enclosure - - p_thickness = 3.0 #Thickness of the box walls - p_sideRadius = 10.0 #Radius for the curves around the sides of the bo - p_topAndBottomRadius = 2.0 #Radius for the curves on the top and bottom edges of the box - - p_screwpostInset = 12.0 #How far in from the edges the screwposts should be place. - p_screwpostID = 4.0 #nner Diameter of the screwpost holes, should be roughly screw diameter not including threads - p_screwpostOD = 10.0 #Outer Diameter of the screwposts.\nDetermines overall thickness of the posts - - p_boreDiameter = 8.0 #Diameter of the counterbore hole, if any - p_boreDepth = 1.0 #Depth of the counterbore hole, if - p_countersinkDiameter = 0.0 #Outer diameter of countersink. Should roughly match the outer diameter of the screw head - p_countersinkAngle = 90.0 #Countersink angle (complete angle between opposite sides, not from center to one side) - p_flipLid = True #Whether to place the lid with the top facing down or not. - p_lipHeight = 1.0 #Height of lip on the underside of the lid.\nSits inside the box body for a snug fit. - - #outer shell - oshell = cq.Workplane("XY").rect(p_outerWidth,p_outerLength).extrude(p_outerHeight + p_lipHeight) - - #weird geometry happens if we make the fillets in the wrong order - if p_sideRadius > p_topAndBottomRadius: - oshell.edges("|Z").fillet(p_sideRadius) - oshell.edges("#Z").fillet(p_topAndBottomRadius) - else: - oshell.edges("#Z").fillet(p_topAndBottomRadius) - oshell.edges("|Z").fillet(p_sideRadius) - - #inner shell - ishell = oshell.faces("Z").workplane(-p_thickness)\ - .rect(POSTWIDTH,POSTLENGTH,forConstruction=True)\ - .vertices() - - for v in postCenters.all(): - v.circle(p_screwpostOD/2.0).circle(p_screwpostID/2.0)\ - .extrude((-1.0)*(p_outerHeight + p_lipHeight -p_thickness ),True) - - #split lid into top and bottom parts - (lid,bottom) = box.faces(">Z").workplane(-p_thickness -p_lipHeight ).split(keepTop=True,keepBottom=True).all() #splits into two solids - - #translate the lid, and subtract the bottom from it to produce the lid inset - lowerLid = lid.translate((0,0,-p_lipHeight)) - cutlip = lowerLid.cut(bottom).translate((p_outerWidth + p_thickness ,0,p_thickness - p_outerHeight + p_lipHeight)) - - #compute centers for counterbore/countersink or counterbore - topOfLidCenters = cutlip.faces(">Z").workplane().rect(POSTWIDTH,POSTLENGTH,forConstruction=True).vertices() - - #add holes of the desired type - if p_boreDiameter > 0 and p_boreDepth > 0: - topOfLid = topOfLidCenters.cboreHole(p_screwpostID,p_boreDiameter,p_boreDepth,(2.0)*p_thickness) - elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: - topOfLid = topOfLidCenters.cskHole(p_screwpostID,p_countersinkDiameter,p_countersinkAngle,(2.0)*p_thickness) - else: - topOfLid= topOfLidCenters.hole(p_screwpostID,(2.0)*p_thickness) - - #flip lid upside down if desired - if p_flipLid: - topOfLid.rotateAboutCenter((1,0,0),180) - - #return the combined result - result =topOfLid.combineSolids(bottom) - - build_object(result) - -.. topic:: Api References - - .. hlist:: - :columns: 3 - - * :py:meth:`Workplane.circle` - * :py:meth:`Workplane.rect` - * :py:meth:`Workplane.extrude` - * :py:meth:`Workplane.box` - * :py:meth:`CQ.all` - * :py:meth:`CQ.faces` - * :py:meth:`CQ.vertices` - * :py:meth:`CQ.edges` - * :py:meth:`CQ.workplane` - * :py:meth:`Workplane.fillet` - * :py:meth:`Workplane.cut` - * :py:meth:`Workplane.combineSolids` - * :py:meth:`Workplane.rotateAboutCenter` - * :py:meth:`Workplane.cboreHole` - * :py:meth:`Workplane.cskHole` - * :py:meth:`Workplane.hole` - -Lego Brick -------------------- - -This script will produce any size regular rectangular Lego(TM) brick. Its only tricky because of the logic -regarding the underside of the brick. - -.. cq_plot:: - :height: 400 - - ##### - # Inputs - ###### - lbumps = 6 # number of bumps long - wbumps = 2 # number of bumps wide - thin = True # True for thin, False for thick - - # - # Lego Brick Constants-- these make a lego brick a lego :) - # - pitch = 8.0 - clearance = 0.1 - bumpDiam = 4.8 - bumpHeight = 1.8 - if thin: - height = 3.2 - else: - height = 9.6 - - t = (pitch - (2 * clearance) - bumpDiam) / 2.0 - postDiam = pitch - t # works out to 6.5 - total_length = lbumps*pitch - 2.0*clearance - total_width = wbumps*pitch - 2.0*clearance - - # make the base - s = cq.Workplane("XY").box(total_length, total_width, height) - - # shell inwards not outwards - s = s.faces("Z").workplane(). \ - rarray(pitch, pitch, lbumps, wbumps, True).circle(bumpDiam / 2.0) \ - .extrude(bumpHeight) - - # add posts on the bottom. posts are different diameter depending on geometry - # solid studs for 1 bump, tubes for multiple, none for 1x1 - tmp = s.faces(" 1 and wbumps > 1: - tmp = tmp.rarray(pitch, pitch, lbumps - 1, wbumps - 1, center=True). \ - circle(postDiam / 2.0).circle(bumpDiam / 2.0).extrude(height - t) - elif lbumps > 1: - tmp = tmp.rarray(pitch, pitch, lbumps - 1, 1, center=True). \ - circle(t).extrude(height - t) - elif wbumps > 1: - tmp = tmp.rarray(pitch, pitch, 1, wbumps - 1, center=True). \ - circle(t).extrude(height - t) - else: - tmp = s - - # Render the solid - build_object(tmp) - - -Braille Example ---------------------- - -.. cq_plot:: - :height: 400 - - from __future__ import unicode_literals, division - from collections import namedtuple - - - # text_lines is a list of text lines. - # FreeCAD in braille (converted with braille-converter: - # https://github.com/jpaugh/braille-converter.git). - text_lines = ['⠠ ⠋ ⠗ ⠑ ⠑ ⠠ ⠉ ⠠ ⠁ ⠠ ⠙'] - # See http://www.tiresias.org/research/reports/braille_cell.htm for examples - # of braille cell geometry. - horizontal_interdot = 2.5 - vertical_interdot = 2.5 - horizontal_intercell = 6 - vertical_interline = 10 - dot_height = 0.5 - dot_diameter = 1.3 - - base_thickness = 1.5 - - # End of configuration. - BrailleCellGeometry = namedtuple('BrailleCellGeometry', - ('horizontal_interdot', - 'vertical_interdot', - 'intercell', - 'interline', - 'dot_height', - 'dot_diameter')) - - - class Point(object): - def __init__(self, x, y): - self.x = x - self.y = y - - def __add__(self, other): - return Point(self.x + other.x, self.y + other.y) - - def __len__(self): - return 2 - - def __getitem__(self, index): - return (self.x, self.y)[index] - - def __str__(self): - return '({}, {})'.format(self.x, self.y) - - - def brailleToPoints(text, cell_geometry): - # Unicode bit pattern (cf. https://en.wikipedia.org/wiki/Braille_Patterns). - mask1 = 0b00000001 - mask2 = 0b00000010 - mask3 = 0b00000100 - mask4 = 0b00001000 - mask5 = 0b00010000 - mask6 = 0b00100000 - mask7 = 0b01000000 - mask8 = 0b10000000 - masks = (mask1, mask2, mask3, mask4, mask5, mask6, mask7, mask8) - - # Corresponding dot position - w = cell_geometry.horizontal_interdot - h = cell_geometry.vertical_interdot - pos1 = Point(0, 2 * h) - pos2 = Point(0, h) - pos3 = Point(0, 0) - pos4 = Point(w, 2 * h) - pos5 = Point(w, h) - pos6 = Point(w, 0) - pos7 = Point(0, -h) - pos8 = Point(w, -h) - pos = (pos1, pos2, pos3, pos4, pos5, pos6, pos7, pos8) - - # Braille blank pattern (u'\u2800'). - blank = '⠀' - points = [] - # Position of dot1 along the x-axis (horizontal). - character_origin = 0 - for c in text: - for m, p in zip(masks, pos): - delta_to_blank = ord(c) - ord(blank) - if (m & delta_to_blank): - points.append(p + Point(character_origin, 0)) - character_origin += cell_geometry.intercell - return points - - - def get_plate_height(text_lines, cell_geometry): - # cell_geometry.vertical_interdot is also used as space between base - # borders and characters. - return (2 * cell_geometry.vertical_interdot + - 2 * cell_geometry.vertical_interdot + - (len(text_lines) - 1) * cell_geometry.interline) - - - def get_plate_width(text_lines, cell_geometry): - # cell_geometry.horizontal_interdot is also used as space between base - # borders and characters. - max_len = max([len(t) for t in text_lines]) - return (2 * cell_geometry.horizontal_interdot + - cell_geometry.horizontal_interdot + - (max_len - 1) * cell_geometry.intercell) - - - def get_cylinder_radius(cell_geometry): - """Return the radius the cylinder should have - The cylinder have the same radius as the half-sphere make the dots (the - hidden and the shown part of the dots). - The radius is such that the spherical cap with diameter - cell_geometry.dot_diameter has a height of cell_geometry.dot_height. - """ - h = cell_geometry.dot_height - r = cell_geometry.dot_diameter / 2 - return (r ** 2 + h ** 2) / 2 / h - - - def get_base_plate_thickness(plate_thickness, cell_geometry): - """Return the height on which the half spheres will sit""" - return (plate_thickness + - get_cylinder_radius(cell_geometry) - - cell_geometry.dot_height) - - - def make_base(text_lines, cell_geometry, plate_thickness): - base_width = get_plate_width(text_lines, cell_geometry) - base_height = get_plate_height(text_lines, cell_geometry) - base_thickness = get_base_plate_thickness(plate_thickness, cell_geometry) - base = cq.Workplane('XY').box(base_width, base_height, base_thickness, - centered=(False, False, False)) - return base - - - def make_embossed_plate(text_lines, cell_geometry): - """Make an embossed plate with dots as spherical caps - Method: - - make a thin plate on which sit cylinders - - fillet the upper edge of the cylinders so to get pseudo half-spheres - - make the union with a thicker plate so that only the sphere caps stay - "visible". - """ - base = make_base(text_lines, cell_geometry, base_thickness) - - dot_pos = [] - base_width = get_plate_width(text_lines, cell_geometry) - base_height = get_plate_height(text_lines, cell_geometry) - y = base_height - 3 * cell_geometry.vertical_interdot - line_start_pos = Point(cell_geometry.horizontal_interdot, y) - for text in text_lines: - dots = brailleToPoints(text, cell_geometry) - dots = [p + line_start_pos for p in dots] - dot_pos += dots - line_start_pos += Point(0, -cell_geometry.interline) - - r = get_cylinder_radius(cell_geometry) - base = base.faces('>Z').vertices('Z').edges() \ - .fillet(r - 0.001) - hidding_box = cq.Workplane('XY').box( - base_width, base_height, base_thickness, centered=(False, False, False)) - result = hidding_box.union(base) - return result - - _cell_geometry = BrailleCellGeometry( - horizontal_interdot, - vertical_interdot, - horizontal_intercell, - vertical_interline, - dot_height, - dot_diameter) - - if base_thickness < get_cylinder_radius(_cell_geometry): - raise ValueError('Base thickness should be at least {}'.format(dot_height)) - - build_object(make_embossed_plate(text_lines, _cell_geometry)) - -Panel With Various Connector Holes ------------------------------------ - -.. cq_plot:: - :height: 400 - - # The dimensions of the model. These can be modified rather than changing the - # object's code directly. - width = 400 - height = 500 - thickness = 2 - - # Create a plate with two polygons cut through it - result = cq.Workplane("front").box(width, height, thickness) - - h_sep = 60 - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(157,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(157,-30-idx*h_sep).moveTo(-16.65,0).circle(1.6).moveTo(16.65,0).circle(1.6).moveTo(-10.1889,-5.7).threePointArc((-12.59306,-4.70416),(-13.5889,-2.3)).lineTo(-14.4,2.3).threePointArc((-13.40416,4.70416),(-11,5.7)).lineTo(11,5.7).threePointArc((13.40416,4.70416),(14.4,2.3)).lineTo(13.5889,-2.3).threePointArc((12.59306,-4.70416),(10.1889,-5.7)).close().cutThruAll() - - h_sep4DB9 = 30 - for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(91,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(25,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(25,-30-idx*h_sep).moveTo(-16.65,0).circle(1.6).moveTo(16.65,0).circle(1.6).moveTo(-10.1889,-5.7).threePointArc((-12.59306,-4.70416),(-13.5889,-2.3)).lineTo(-14.4,2.3).threePointArc((-13.40416,4.70416),(-11,5.7)).lineTo(11,5.7).threePointArc((13.40416,4.70416),(14.4,2.3)).lineTo(13.5889,-2.3).threePointArc((12.59306,-4.70416),(10.1889,-5.7)).close().cutThruAll() - - for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-41,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-107,210-idx*h_sep).moveTo(-23.5,0).circle(1.6).moveTo(23.5,0).circle(1.6).moveTo(-17.038896,-5.7).threePointArc((-19.44306,-4.70416),(-20.438896,-2.3)).lineTo(-21.25,2.3).threePointArc((-20.25416,4.70416),(-17.85,5.7)).lineTo(17.85,5.7).threePointArc((20.25416,4.70416),(21.25,2.3)).lineTo(20.438896,-2.3).threePointArc((19.44306,-4.70416),(17.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-107,-30-idx*h_sep).circle(14).rect(24.7487,24.7487, forConstruction=True).vertices().hole(3.2).cutThruAll() - - for idx in range(8): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-173,225-idx*h_sep4DB9).moveTo(-12.5,0).circle(1.6).moveTo(12.5,0).circle(1.6).moveTo(-6.038896,-5.7).threePointArc((-8.44306,-4.70416),(-9.438896,-2.3)).lineTo(-10.25,2.3).threePointArc((-9.25416,4.70416),(-6.85,5.7)).lineTo(6.85,5.7).threePointArc((9.25416,4.70416),(10.25,2.3)).lineTo(9.438896,-2.3).threePointArc((8.44306,-4.70416),(6.038896,-5.7)).close().cutThruAll() - - for idx in range(4): - result = result.workplane(offset=1, centerOption='CenterOfBoundBox').center(-173,-30-idx*h_sep).moveTo(-2.9176,-5.3).threePointArc((-6.05,0),(-2.9176,5.3)).lineTo(2.9176,5.3).threePointArc((6.05,0),(2.9176,-5.3)).close().cutThruAll() - - # Render the solid - build_object(result) diff --git a/Libs/cadquery-lib/doc/extending.rst b/Libs/cadquery-lib/doc/extending.rst deleted file mode 100644 index 8138b18..0000000 --- a/Libs/cadquery-lib/doc/extending.rst +++ /dev/null @@ -1,180 +0,0 @@ -.. _extending: - -Extending CadQuery -====================== - - -If you find that CadQuery doesnt suit your needs, you can easily extend it. CadQuery provides several extension -methods: - - * You can load plugins others have developed. This is by far the easiest way to access other code - * you can define your own plugins. - * you can use FreeCAD script directly - - -Using FreeCAD Script ------------------------ - -The easiest way to extend CadQuery is to simply use FreeCAD script inside of your build method. Just about -any valid FreeCAD script will execute just fine. For example, this simple CadQuery script:: - - return cq.Workplane("XY").box(1.0,2.0,3.0).val() - -is actually equivalent to:: - - return Part.makeBox(1.0,2.0,3.0) - -As long as you return a valid FreeCAD Shape, you can use any FreeCAD methods you like. You can even mix and match the -two. For example, consider this script, which creates a FreeCAD box, but then uses cadquery to select its faces:: - - box = Part.makeBox(1.0,2.0,3.0) - cq = CQ(box).faces(">Z").size() # returns 6 - - -Extending CadQuery: Plugins ----------------------------- - -Though you can get a lot done with FreeCAD, the code gets pretty nasty in a hurry. CadQuery shields you from -a lot of the complexity of the FreeCAD api. - -You can get the best of both worlds by wrapping your freecad script into a CadQuery plugin. - -A CadQuery plugin is simply a function that is attached to the CadQuery :py:meth:`cadquery.CQ` or :py:meth:`cadquery.Workplane` class. -When connected, your plugin can be used in the chain just like the built-in functions. - -There are a few key concepts important to understand when building a plugin - - -The Stack -------------------- - -Every CadQuery object has a local stack, which contains a list of items. The items on the stack will be -one of these types: - - * **A CadQuery SolidReference object**, which holds a reference to a FreeCAD solid - * **A FreeCAD object**, a Vertex, Edge, Wire, Face, Shell, Solid, or Compound - -The stack is available by using self.objects, and will always contain at least one object. - -.. note:: - - Objects and points on the stack are **always** in global coordinates. Similarly, any objects you - create must be created in terms of global coordinates as well! - - -Preserving the Chain ------------------------ - -CadQuery's fluent api relies on the ability to chain calls together one after another. For this to work, -you must return a valid CadQuery object as a return value. If you choose not to return a CadQuery object, -then your plugin will end the chain. Sometimes this is desired for example :py:meth:`cadquery.CQ.size` - -There are two ways you can safely continue the chain: - - 1. **return self** If you simply wish to modify the stack contents, you can simply return a reference to - self. This approach is destructive, because the contents of the stack are modified, but it is also the - simplest. - 2. :py:meth:`cadquery.CQ.newObject` Most of the time, you will want to return a new object. Using newObject will - return a new CQ or Workplane object having the stack you specify, and will link this object to the - previous one. This preserves the original object and its stack. - - -Helper Methods ------------------------ - -When you implement a CadQuery plugin, you are extending CadQuery's base objects. As a result, you can call any -CadQuery or Workplane methods from inside of your extension. You can also call a number of internal methods that -are designed to aid in plugin creation: - - - * :py:meth:`cadquery.Workplane._makeWireAtPoints` will invoke a factory function you supply for all points on the stack, - and return a properly constructed cadquery object. This function takes care of registering wires for you - and everything like that - - * :py:meth:`cadquery.Workplane.newObject` returns a new Workplane object with the provided stack, and with its parent set - to the current object. The preferred way to continue the chain - - * :py:meth:`cadquery.CQ.findSolid` returns the first Solid found in the chain, working from the current object upwards - in the chain. commonly used when your plugin will modify an existing solid, or needs to create objects and - then combine them onto the 'main' part that is in progress - - * :py:meth:`cadquery.Workplane._addPendingWire` must be called if you add a wire. This allows the base class to track all the wires - that are created, so that they can be managed when extrusion occurs. - - * :py:meth:`cadquery.Workplane.wire` gathers up all of the edges that have been drawn ( eg, by line, vline, etc ), and - attempts to combine them into a single wire, which is returned. This should be used when your plugin creates - 2-d edges, and you know it is time to collect them into a single wire. - - * :py:meth:`cadquery.Workplane.plane` provides a reference to the workplane, which allows you to convert between workplane - coordinates and global coordinates: - * :py:meth:`cadquery.freecad_impl.geom.Plane.toWorldCoords` will convert local coordinates to global ones - * :py:meth:`cadquery.freecad_impl.geom.Plane.toLocalCoords` will convet from global coordinates to local coordinates - -Coordinate Systems ------------------------ - -Keep in mind that the user may be using a work plane that has created a local coordinate system. Consequently, -the orientation of shapes that you create are often implicitly defined by the user's workplane. - -Any objects that you create must be fully defined in *global coordinates*, even though some or all of the users' -inputs may be defined in terms of local coordinates. - - -Linking in your plugin ------------------------ - -Your plugin is a single method, which is attached to the main Workplane or CadQuery object. - -Your plugin method's first parameter should be 'self', which will provide a reference to base class functionality. -You can also accept other arguments. - -To install it, simply attach it to the CadQuery or Workplane object, like this:: - - def _yourFunction(self,arg1,arg): - do stuff - return whatever_you_want - - cq.Workplane.yourPlugin = _yourFunction - -That's it! - -CadQueryExample Plugins ------------------------ -Some core cadquery code is intentionally written exactly like a plugin. -If you are writing your own plugins, have a look at these methods for inspiration: - - * :py:meth:`cadquery.Workplane.polygon` - * :py:meth:`cadquery.Workplane.cboreHole` - - -Plugin Example ------------------------ - -This ultra simple plugin makes cubes of the specified size for each stack point. - -(The cubes are off-center because the boxes have their lower left corner at the reference points.) - -.. cq_plot:: - - def makeCubes(self,length): - #self refers to the CQ or Workplane object - - #inner method that creates a cube - def _singleCube(pnt): - #pnt is a location in local coordinates - #since we're using eachpoint with useLocalCoordinates=True - return cq.Solid.makeBox(length,length,length,pnt) - - #use CQ utility method to iterate over the stack, call our - #method, and convert to/from local coordinates. - return self.eachpoint(_singleCube,True) - - #link the plugin into cadQuery - cq.Workplane.makeCubes = makeCubes - - #use the plugin - result = cq.Workplane("XY").box(6.0,8.0,0.5).faces(">Z")\ - .rect(4.0,4.0,forConstruction=True).vertices() \ - .makeCubes(1.0).combineSolids() - build_object(result) - diff --git a/Libs/cadquery-lib/doc/fileformat.rst b/Libs/cadquery-lib/doc/fileformat.rst deleted file mode 100644 index e34afa5..0000000 --- a/Libs/cadquery-lib/doc/fileformat.rst +++ /dev/null @@ -1,24 +0,0 @@ -.. _cadquery_reference: - -CadQuery Scripts and Object Output -====================================== - -CadQuery scripts are pure python scripts, that may follow a few conventions. - -If you are using cadquery as a library, there are no constraints. - -If you are using cadquery scripts inside of a cadquery execution environment, -like `The CadQuery Freecad Module `_ or -`parametricParts.com `_, there are a few conventions you need to be aware of: - - * cadquery is already imported as 'cq' - * to return an object to the container, you need to call the build_object() method. - -Each script generally has three sections: - - * Variable Assignments and metadata definitions - * cadquery and other python code - * object exports, via the export_object() function - - -see the :ref:`cqgi` section for more details. \ No newline at end of file diff --git a/Libs/cadquery-lib/doc/index.rst b/Libs/cadquery-lib/doc/index.rst deleted file mode 100644 index 41e3ce4..0000000 --- a/Libs/cadquery-lib/doc/index.rst +++ /dev/null @@ -1,58 +0,0 @@ - - -CadQuery Documentation -=================================== - -CadQuery is an intuitive, easy-to-use python library for building parametric 3D CAD models. It has several goals: - - * Build models with scripts that are as close as possible to how you'd describe the object to a human, - using a standard, already established programming language - - * Create parametric models that can be very easily customized by end users - - * Output high quality CAD formats like STEP and AMF in addition to traditional STL - - * Provide a non-proprietary, plain text model format that can be edited and executed with only a web browser - -See CadQuery in Action -------------------------- - -This `Getting Started Video `_ will show you what CadQuery can do. - - -Quick Links ------------------- - - * :ref:`quickstart` - * `CadQuery CheatSheet <_static/cadquery_cheatsheet.html>`_ - * :ref:`apireference` - -Table Of Contents -------------------- - -.. toctree:: - :maxdepth: 2 - - intro.rst - installation.rst - quickstart.rst - designprinciples.rst - primer.rst - fileformat.rst - examples.rst - apireference.rst - selectors.rst - classreference.rst - cqgi.rst - extending.rst - roadmap.rst - - - -Indices and tables -------------------- - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/Libs/cadquery-lib/doc/installation.rst b/Libs/cadquery-lib/doc/installation.rst deleted file mode 100644 index 8633a9d..0000000 --- a/Libs/cadquery-lib/doc/installation.rst +++ /dev/null @@ -1,63 +0,0 @@ -.. _installation: - -Installing CadQuery -=================================== - -CadQuery is based on `FreeCAD `_, -which is turn based on the open-source `OpenCascade `_ modelling kernel. - -Prerequisites--FreeCAD and Python 2.6 or 2.7 ----------------------------------------------- -CadQuery requires FreeCAD and Python version 2.6.x or 2.7.x *Python 3.x is NOT supported* - -Ubuntu Command Line Installation ------------------------------------------- - -On Ubuntu, you can type:: - - sudo apt-get install -y freecad freecad-doc - pip install cadquery - -This `Unix Installation Video `_ will walk you through the installation - - -Installation: Other Platforms ------------------------------------------- - - 1. Install FreeCAD using the appropriate installer for your platform, on `www.freecadweb.org `_ - 2. pip install cadquery - -This `Windows Installation video `_ will walk you through the installation on Windows - -Test Your Installation ------------------------- - -If all has gone well, you can open a command line/prompt, and type:: - - $python - $import cadquery - $cadquery.Workplane('XY').box(1,2,3).toSvg() - -Adding a Nicer GUI via the cadquery-freecad-module --------------------------------------------------------- - -If you prefer to have a GUI available, your best option is to use -`The CadQuery Freecad Module `_. - -Simply extract cadquery-freecad-module into your FreeCAD installation. You'll end up -with a cadquery workbench that allows you to interactively run scripts, and then see the results in the FreeCAD GUI - -If you are using Ubuntu, you can also install it via this ppa: - -https://code.launchpad.net/~freecad-community/+archive/ubuntu/ppa/+packages - - -Zero Step Install -------------------------------------------------- - -If you would like to use cadquery with no installation all, you can -use `ParametricParts.com `_, a web-based platform that runs cadquery scripts - -It is free, and allows running and viewing cadquery scripts in your web browser or mobile phone - - diff --git a/Libs/cadquery-lib/doc/intro.rst b/Libs/cadquery-lib/doc/intro.rst deleted file mode 100644 index b2d64fd..0000000 --- a/Libs/cadquery-lib/doc/intro.rst +++ /dev/null @@ -1,95 +0,0 @@ -.. _what_is_cadquery: - -********************* -Introduction -********************* - -What is CadQuery -======================================== - -CadQuery is an intuitive, easy-to-use python library for building parametric 3D CAD models. It has several goals: - - * Build models with scripts that are as close as possible to how you'd describe the object to a human, - using a standard, already established programming language - - * Create parametric models that can be very easily customized by end users - - * Output high quality CAD formats like STEP and AMF in addition to traditional STL - - * Provide a non-proprietary, plain text model format that can be edited and executed with only a web browser - -CadQuery is based on -`FreeCAD `_, -which is turn based on the open-source `OpenCascade `_ modelling kernel. - -Using CadQuery, you can build fully parametric models with a very small amount of code. For example, this simple script -produces a flat plate with a hole in the middle:: - - thickness = 0.5 - width=2.0 - result = Workplane("front").box(width,width,thickness).faces(">Z").hole(thickness) - -.. image:: _static/simpleblock.png - -That's a bit of a dixie-cup example. But it is pretty similar to a more useful part: a parametric pillow block for a -standard 608-size ball bearing:: - - (length,height,diam, thickness,padding) = ( 30.0,40.0,22.0,10.0,8.0) - - result = Workplane("XY").box(length,height,thickness).faces(">Z").workplane().hole(diam)\ - .faces(">Z").workplane() \ - .rect(length-padding,height-padding,forConstruction=True) \ - .vertices().cboreHole(2.4,4.4,2.1) - -.. image:: _static/pillowblock.png - -Lots more examples are available in the :ref:`examples` - -CadQuery is a library, GUIs are separate -============================================== - -CadQuery is a library, that's intentionally designed to be usable as a GUI-less library. This enables -its use in a variety of engineering and scientific applications that create 3d models programmatically. - -If you'd like a GUI, you have a couple of options: - - * Install cadquery as a part of `The CadQuery Freecad Module `_ - * Use `ParametricParts.com `_, a web-based platform that runs cadQuery scripts - - -Why CadQuery instead of OpenSCAD? -============================================ - -Like OpenSCAD, CadQuery is an open-source, script based, parametric model generator. But CadQuery has several key advantages: - - 1. **The scripts use a standard programming language**, python, and thus can benefit from the associated infrastructure. - This includes many standard libraries and IDEs - - 2. **More powerful CAD kernel** OpenCascade is much more powerful than CGAL. Features supported natively - by OCC include NURBS, splines, surface sewing, STL repair, STEP import/export, and other complex operations, - in addition to the standard CSG operations supported by CGAL - - 3. **Ability to import/export STEP** We think the ability to begin with a STEP model, created in a CAD package, - and then add parametric features is key. This is possible in OpenSCAD using STL, but STL is a lossy format - - 4. **Less Code and easier scripting** CadQuery scripts require less code to create most objects, because it is possible to locate - features based on the position of other features, workplanes, vertices, etc. - - 5. **Better Performance** CadQuery scripts can build STL, STEP, and AMF faster than OpenSCAD. - -Where does the name CadQuery come from? -======================================== - -CadQuery is inspired by `jQuery `_ , a popular framework that -revolutionized web development involving javascript. - -CadQuery is for 3D CAD what jQuery is for javascript. -If you are familiar with how jQuery works, you will probably recognize several jQuery features that CadQuery uses: - - * A fluent api to create clean, easy to read code - - * Ability to use the library along side other python libraries - - * Clear and complete documentation, with plenty of samples. - - diff --git a/Libs/cadquery-lib/doc/primer.rst b/Libs/cadquery-lib/doc/primer.rst deleted file mode 100644 index b69af5a..0000000 --- a/Libs/cadquery-lib/doc/primer.rst +++ /dev/null @@ -1,153 +0,0 @@ -.. _3d_cad_primer: - - -CadQuery Concepts -=================================== - - -3D BREP Topology Concepts ---------------------------- -Before talking about CadQuery, it makes sense to talk a little about 3D CAD Topology. CadQuery is based upon the -OpenCascade kernel, which is uses Boundary Representations ( BREP ) for objects. This just means that objects -are defined by their enclosing surfaces. - -When working in a BREP system, these fundamental constructs exist to define a shape ( working up the food chain): - - :vertex: a single point in space - :edge: a connection between two or more vertices along a particular path ( called a curve ) - :wire: a collection of edges that are connected together. - :face: a set of edges or wires that enclose a surface - :shell: a collection of faces that are connected together along some of their edges - :solid: a shell that has a closed interior - :compound: a collection of solids - -When using CadQuery, all of these objects are created, hopefully with the least possible work. In the actual CAD -kernel, there are another set of Geometrical constructs involved as well. For example, an arc-shaped edge will -hold a reference to an underlying curve that is a full cricle, and each linear edge holds underneath it the equation -for a line. CadQuery shields you from these constructs. - - -CQ, the CadQuery Object ---------------------------- - -The CadQuery object wraps a BREP feature, and provides functionality around it. Typical examples include rotating, -transforming, combining objects, and creating workplanes. - -See :ref:`apireference` to learn more. - - -Workplanes ---------------------------- - -Workplanes represent a plane in space, from which other features can be located. They have a center point and a local -coordinate system. - -The most common way to create a workplane is to locate one on the face of a solid. You can also create new workplanes -in space, or relative to other planes using offsets or rotations. - -The most powerful feature of workplanes is that they allow you to work in 2D space in the coordinate system of the -workplane, and then build 3D features based on local coordinates. This makes scripts much easier to create and maintain. - -See :py:class:`cadquery.Workplane` to learn more - - -2D Construction ---------------------------- - -Once you create a workplane, you can work in 2D, and then later use the features you create to make 3D objects. -You'll find all of the 2D constructs you expect-- circles, lines, arcs, mirroring, points, etc. - -See :ref:`2dOperations` to learn more. - - -3D Construction ---------------------------- - -You can construct 3D primatives such as boxes, spheres, wedges, and cylinders directly. You can also sweep, extrude, -and loft 2D geometry to form 3D features. Of course the basic primitive operations are also available. - -See :ref:`3doperations` to learn more. - - - -Selectors ---------------------------- - -Selectors allow you to select one or more features, for use to define new features. As an example, you might -extrude a box, and then select the top face as the location for a new feture. Or, you might extrude a box, and -then select all of the vertical edges so that you can apply a fillet to them. - -You can select Vertices, Edges, Faces, Solids, and Wires using selectors. - -Think of selectors as the equivalent of your hand and mouse, were you to build an object using a conventional CAD system. - -You can learn more about selectors :ref:`selectors` - - -Construction Geometry ---------------------------- -Construction geometry are features that are not part of the object, but are only defined to aid in building the object. -A common example might be to define a rectangle, and then use the corners to define a the location of a set of holes. - -Most CadQuery construction methods provide a forConstruction keyword, which creates a feature that will only be used -to locate other features - - -The Stack ---------------------------- - -As you work in CadQuery, each operation returns a new CadQuery object with the result of that operations. Each CadQuery -object has a list of objects, and a reference to its parent. - -You can always go backwards to older operations by removing the current object from the stack. For example:: - - CQ(someObject).faces(">Z").first().vertices() - -returns a CadQuery object that contains all of the vertices on highest face of someObject. But you can always move -backwards in the stack to get the face as well:: - - CQ(someObject).faces(">Z").first().vertices().end() #returns the same as CQ(someObject).faces(">Z").first() - -You can browse stack access methods here :ref:`stackMethods` - - -Chaining ---------------------------- - -All CadQuery methods return another CadQuery object, so that you can chain the methods together fluently. Use -the core CQ methods to get at the objects that were created. - - -The Context Solid ---------------------------- - -Most of the time, you are building a single object, and adding features to that single object. CadQuery watches -your operations, and defines the first solid object created as the 'context solid'. After that, any features -you create are automatically combined ( unless you specify otherwise) with that solid. This happens even if the -solid was created a long way up in the stack. For example:: - - Workplane('XY').box(1,2,3).faces(">Z").circle(0.25).extrude() - -Will create a 1x2x3 box, with a cylindrical boss extending from the top face. It was not necessary to manually -combine the cylinder created by extruding the circle with the box, because the default behavior for extrude is -to combine the result with the context solid. The hole() method works similarly-- CadQuery presumes that you want -to subtract the hole from the context solid. - -If you want to avoid this, you can specified combine=False, and CadQuery will create the solid separately. - - -Iteration ---------------------------- - -CAD models often have repeated geometry, and its really annoying to resort to for loops to construct features. -Many CadQuery methods operate automatically on each element on the stack, so that you don't have to write loops. -For example, this:: - - Workplane('XY').box(1,2,3).faces(">Z").vertices().circle(0.5) - -Will actually create 4 circles, because vertices() selects 4 vertices of a rectangular face, and the circle() method -iterates on each member of the stack. - -This is really useful to remember when you author your own plugins. :py:meth:`cadquery.CQ.Workplane.each` is useful for this purpose. - - diff --git a/Libs/cadquery-lib/doc/quickstart.rst b/Libs/cadquery-lib/doc/quickstart.rst deleted file mode 100644 index 6701942..0000000 --- a/Libs/cadquery-lib/doc/quickstart.rst +++ /dev/null @@ -1,242 +0,0 @@ -.. _quickstart: - -*********************** -CadQuery QuickStart -*********************** - -.. module:: cadquery - -Want a quick glimpse of what CadQuery can do? This quickstart will demonstrate the basics of cadQuery using a simple example - -Prerequisites: FreeCAD + cadQuery-freeCAD-module in FreeCAD -============================================================== - -If you have not already done so, follow the :ref:`installation`, and to install cadquery, FreeCAD, -and the cadquery-freecad-module - -After installation, open the CadQuery workbench: - -.. image:: _static/quickstart/001.png - -You'll see that we start out with a single block. Find the cadquery Code Window, at the bottom left. - -If you want check out a couple of the examples in the CadQuery->Examples menu. - -What we'll accomplish -======================== - -We will build a fully parametric bearing pillow block in this quickstart. Our finished object will look like this: - -.. image:: _static/quickstart/000.png - -**We would like our block to have these features:** - - 1. It should be sized to hold a single 608 ( 'skate' ) bearing, in the center of the block. - 2. It should have counter sunk holes for M2 socket head cap screws at the corners - 3. The length and width of the block should be configurable by the user to any reasonable size. - -A human would describe this as: - - "A rectangular block 80mm x 60mm x 30mm , with countersunk holes for M2 socket head cap screws - at the corners, and a circular pocket 22mm in diameter in the middle for a bearing" - -Human descriptions are very elegant, right? -Hopefully our finished script will not be too much more complex than this human-oriented description. - -Let's see how we do. - -Start With A single, simple Plate -====================================== - -Lets start with a simple model that makes nothing but a rectangular block, but -with place-holders for the dimensions. Paste this into the CodeWindow: - -.. code-block:: python - :linenos: - - height = 60.0 - width = 80.0 - thickness = 10.0 - - # make the base - result = cq.Workplane("XY").box(height, width, thickness) - - # Render the solid - build_object(result) - -Press F2 to run the script. You should see Our basic base. - -.. image:: _static/quickstart/002.png - -Nothing special, but its a start! - -Add the Holes -================ - -Our pillow block needs to have a 22mm diameter hole in the center of this block to hold the bearing. - -This modification will do the trick: - -.. code-block:: python - :linenos: - :emphasize-lines: 4,8 - - height = 60.0 - width = 80.0 - thickness = 10.0 - diameter = 22.0 - - # make the base - result = cq.Workplane("XY").box(height, width, thickness)\ - .faces(">Z").workplane().hole(diameter) - - # Render the solid - build_object(result) - -Rebuild your model by pressing F2. Your block should look like this: - -.. image:: _static/quickstart/003.png - - -The code is pretty compact, lets step through it. - -**Line 4** adds a new parameter, diameter, for the diamter of the hole - -**Line 8**, we're adding the hole. -:py:meth:`cadquery.CQ.faces` selects the top-most face in the Z direction, and then -:py:meth:`cadquery.CQ.workplane` begins a new workplane located on this face. The center of this workplane -is located at the geometric center of the shape, which in this case is the center of the plate. -Finally, :py:meth:`cadquery.Workplane.hole` drills a hole through the part 22mm in diamter - -.. note:: - - Don't worry about the CadQuery syntax now.. you can learn all about it in the :ref:`apireference` later. - -More Holes -============ - -Ok, that hole was not too hard, but what about the counter-bored holes in the corners? - -An M2 Socket head cap screw has these dimensions: - - * **Head Diameter** : 3.8 mm - * **Head height** : 2.0 mm - * **Clearance Hole** : 2.4 mm - * **CounterBore diameter** : 4.4 mm - -The centers of these holes should be 4mm from the edges of the block. And, -we want the block to work correctly even when the block is re-sized by the user. - -**Don't tell me** we'll have to repeat the steps above 8 times to get counter-bored holes? -Good news!-- we can get the job done with just two lines of code. Here's the code we need: - -.. code-block:: python - :linenos: - :emphasize-lines: 5,10-13 - - height = 60.0 - width = 80.0 - thickness = 10.0 - diameter = 22.0 - padding = 12.0 - - # make the base - result = cq.Workplane("XY").box(height, width, thickness)\ - .faces(">Z").workplane().hole(diameter)\ - .faces(">Z").workplane() \ - .rect(height - padding,width - padding,forConstruction=True)\ - .vertices()\ - .cboreHole(2.4, 4.4, 2.1) - - # Render the solid - build_object(result) - - -After pressing F2 to re-execute the model, you should see something like this: - - .. image:: _static/quickstart/004.png - - -There is quite a bit going on here, so lets break it down a bit. - -**Line 5** creates a new padding parameter that decides how far the holes are from the edges of the plate. - -**Line 10** selects the top-most face of the block, and creates a workplane on the top of that face, which we'll use to -define the centers of the holes in the corners. - -There are a couple of things to note about this line: - - 1. The :py:meth:`cadquery.Workplane.rect` function draws a rectangle. **forConstruction=True** - tells CadQuery that this rectangle will not form a part of the solid, - but we are just using it to help define some other geometry. - 2. The center point of a workplane on a face is always at the center of the face, which works well here - 3. Unless you specifiy otherwise, a rectangle is drawn with its center on the current workplane center-- in - this case, the center of the top face of the block. So this rectangle will be centered on the face - - -**Line 11** draws a rectangle 8mm smaller than the overall length and width of the block,which we will use to -locate the corner holes. We'll use the vertices ( corners ) of this rectangle to locate the holes. The rectangle's -center is at the center of the workplane, which in this case co-incides with the center of the bearing hole. - -**Line 12** selects the vertices of the rectangle, which we will use for the centers of the holes. -The :py:meth:`cadquery.CQ.vertices` function selects the corners of the rectangle - -**Line 13** uses the cboreHole function to draw the holes. -The :py:meth:`cadquery.Workplane.cboreHole` function is a handy CadQuery function that makes a counterbored hole, -like most other CadQuery functions, operate on the values on the stack. In this case, since we -selected the four vertices before calling the function, the function operates on each of the four points-- -which results in a counterbore hole at the corners. - - -Filleting -=========== - -Almost done. Let's just round the corners of the block a bit. That's easy, we just need to select the edges -and then fillet them: - -We can do that using the preset dictionaries in the parameter definition: - -.. code-block:: python - :linenos: - :emphasize-lines: 13 - - height = 60.0 - width = 80.0 - thickness = 10.0 - diameter = 22.0 - padding = 12.0 - - # make the base - result = cq.Workplane("XY").box(height, width, thickness)\ - .faces(">Z").workplane().hole(diameter)\ - .faces(">Z").workplane() \ - .rect(height - padding, width - padding, forConstruction=True)\ - .vertices().cboreHole(2.4, 4.4, 2.1)\ - .edges("|Z").fillet(2.0) - - # Render the solid - build_object(result) - -**Line 13** fillets the edges using the :py:meth:`cadquery.CQ.fillet` method. - -To grab the right edges, the :py:meth:`cadquery.CQ.edges` selects all of the -edges that are parallel to the Z axis ("\|Z"), - -The finished product looks like this: - - .. image:: _static/quickstart/005.png - - -Done! -============ - -You just made a parametric, model that can generate pretty much any bearing pillow block -with < 20 lines of code. - -Want to learn more? -==================== - - * Use the CadQuery->Examples menu of the cadquery workbench to explore a lot of other examples. - * The :ref:`examples` contains lots of examples demonstrating cadquery features - * The :ref:`apireference` is a good overview of language features grouped by function - * The :ref:`classreference` is the hard-core listing of all functions available. \ No newline at end of file diff --git a/Libs/cadquery-lib/doc/roadmap.rst b/Libs/cadquery-lib/doc/roadmap.rst deleted file mode 100644 index 3337ff2..0000000 --- a/Libs/cadquery-lib/doc/roadmap.rst +++ /dev/null @@ -1,166 +0,0 @@ -.. _roadmap: - - -RoadMap: Planned Features -============================== - -**CadQuery is not even close to finished!!!** - -Many features are planned for later versions. This page tracks them. If you find that you need features -not listed here, let us know! - -Core --------------------- - -end(n) - allows moving backwards a fixed number of parents in the chain, eg end(3) is same as end().end().end() - -FreeCAD object wrappers - return CQ wrappers for FreeCAD shapes instead of the native FreeCAD objects. - -Improved iteration tools for plugin developers - make it easier to iterate over points and wires for plugins - -More parameter types (String? ) - -face.outerWire - allow selecting the outerWire of a face, so that it can be used for reference geometry or offsets - -Selectors --------------------- - -Chained Selectors - Space delimited selectors should be unioned to allow multiple selections. For example ">Z >X" - -Ad-hoc axes - for example, >(1,2,1) would select a face with normal in the 1,2,1 direction - -logic inversion - ! or not to invert logic, such as "!(>Z)" to select faces _other_ than the most z facing - -closest to point - support faces, points, or edges closest to a provided point - -tagged entities - support tagging entities when they are created, so they can be selected later on using that tag. - ideally, tags are propagated to features that are created from these features ( ie, an edge tagged with 'foo' - that is later extruded into a face means that face would be tagged with 'foo' as well ) - - -Workplanes --------------------- - -rotated workplanes - support creation of workplanes at an angle to another plane or face - -workplane local rotations - rotate the coordinate system of a workplane by an angle. - -make a workplane from a wire - useful to select outer wire and then operate from there, to allow offsets - -2-d operations -------------------- - -offsets - offset profiles, including circles, rects, and other profiles. - -ellipses - create elipses and portions of elipses - -regular polygons - several construction methods: - * number of sides and side length - * number of sides inscribed in circle - * number of sides circumscribed by circle - -arc construction using relative measures - instead of forcing use of absolute workplane coordinates - -tangent arcs - after a line - -centerpoint arcs - including portions of arcs as well as with end points specified - -trimming - ability to use construction geometry to trim other entities - -construction lines - especially centerlines - -2-d fillets - for a rectangle, or for consecutive selected lines - -2-d chamfers - based on rectangles, polygons, polylines, or adjacent selected lines - -mirror around centerline - using centerline construction geometry - -rectangular array - automate creation of equally spread points - -polar array - create equally spaced copies of a feature around a circle - perhaps based on a construction circle? - -midpoint selection - select midpoints of lines, arcs - -face center - explicit selection of face center - -manipulate spline control points - so that the shape of a spline can be more accurately controlled - -feature snap - project geometry in the rest of the part into the work plane, so that - they can be selected and used as references for other features. - -polyline edges - allow polyline to be combined with other edges/curves - -create text - ideally, in various fonts. - -3-d operations ---------------------- - -rotation/transform that return a copy - The current rotateAboutCenter and translate method modify the object, rather than returning a copy - -primitive creation - Need primitive creation for: - * cone - * sphere - * cylinder - * torus - * wedge - -extrude/cut up to surface - allow a cut or extrude to terminate at another surface, rather than either through all or a fixed distance - -extrude along a path - rather than just normal to the plane. This would include - -STEP import - allow embedding and importing step solids created in other tools, which - can then be further manipulated parametrically - -Dome - very difficult to do otherwise - -primitive boolean operations - * intersect - * union - * subtract - - -Algorithms ---------------------- - -Wire Discretization - Sample wires at point interval to improve closet wire computations - - diff --git a/Libs/cadquery-lib/doc/selectors.rst b/Libs/cadquery-lib/doc/selectors.rst deleted file mode 100644 index b14a02a..0000000 --- a/Libs/cadquery-lib/doc/selectors.rst +++ /dev/null @@ -1,126 +0,0 @@ -.. _selector_reference: - -String Selectors Reference -============================= - - -CadQuery selector strings allow filtering various types of object lists. Most commonly, Edges, Faces, and Vertices are -used, but all objects types can be filtered. - -String selectors are simply shortcuts for using the full object equivalents. If you pass one of the -string patterns in, CadQuery will automatically use the associated selector object. - - * :py:meth:`cadquery.CQ.faces` - * :py:meth:`cadquery.CQ.edges` - * :py:meth:`cadquery.CQ.vertices` - * :py:meth:`cadquery.CQ.solids` - * :py:meth:`cadquery.CQ.shells` - -.. note:: - - String selectors are shortcuts to concrete selector classes, which you can use or extend. See - :ref:`classreference` for more details - - If you find that the built-in selectors are not sufficient, you can easily plug in your own. - See :ref:`extending` to see how. - - -Combining Selectors -========================== - -Selectors can be combined arithmetically and logically, so that it is possible to do intersection, union, and other -combinations. For example:: - - box = cadquery.Workplane("XY").box(10,10,10) - - s = selectors.StringSyntaxSelector - - ### select all edges on right and left faces - #box = box.edges((s("|Z") + s("|Y"))).fillet(1) - - ### select all edges on top and bottom - #box = box.edges(-s("|Z")).fillet(1) - #box = box.edges(s('|X')+s('Y')).fillet(1) - box = box.faces(s('>Z')+s('Z')+s('Y Face farthest in the positive y dir :py:class:`cadquery.DirectionMinMaxSelector` 0 or 1 -Y Edges farthest in the positive y dir :py:class:`cadquery.DirectionMinMaxSelector` 0 or 1 -Y Vertices farthest in the positive y dir :py:class:`cadquery.DirectionMinMaxSelector` 0 or 1 -Z").workplane().hole(center_hole_dia) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex003_Pillow_Block_With_Counterbored_Holes.py b/Libs/cadquery-lib/examples/FreeCAD/Ex003_Pillow_Block_With_Counterbored_Holes.py deleted file mode 100644 index 382f03e..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex003_Pillow_Block_With_Counterbored_Holes.py +++ /dev/null @@ -1,40 +0,0 @@ -#File: Ex003_Pillow_Block_With_Counterbored_Holes.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex003_Pillow_Block_With_Counterbored_Holes - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex003_Pillow_Block_With_Counterbored_Holes) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more in-depth explanation of this example at http://parametricparts.com/docs/quickstart.html - -import cadquery -import Part - -#The dimensions of the box. These can be modified rather than changing the box's code directly. -length = 80.0 -height = 60.0 -thickness = 10.0 -center_hole_dia = 22.0 -cbore_hole_diameter = 2.4 -cbore_diameter = 4.4 -cbore_depth = 2.1 - -#Create a 3D box based on the dimension variables above and add 4 counterbored holes -result = cadquery.Workplane("XY").box(length, height, thickness) \ - .faces(">Z").workplane().hole(center_hole_dia) \ - .faces(">Z").workplane() \ - .rect(length - 8.0, height - 8.0, forConstruction = True) \ - .vertices().cboreHole(cbore_hole_diameter, cbore_diameter, cbore_depth) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex004_Extruded_Cylindrical_Plate.py b/Libs/cadquery-lib/examples/FreeCAD/Ex004_Extruded_Cylindrical_Plate.py deleted file mode 100644 index 8b631ce..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex004_Extruded_Cylindrical_Plate.py +++ /dev/null @@ -1,34 +0,0 @@ -#File: Ex004_Extruded_Cylindrical_Plate.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex004_Extruded_Cylindrical_Plate - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex004_Extruded_Cylindrical_Plate) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the box's code directly. -circle_radius = 50.0 -rectangle_width = 13.0 -rectangle_length = 19.0 -thickness = 13.0 - -#Extrude a cylindrical plate with a rectangular hole in the middle of it -result = cadquery.Workplane("front").circle(circle_radius).rect(rectangle_width, rectangle_length).extrude(thickness) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex005_Extruded_Lines_and_Arcs.py b/Libs/cadquery-lib/examples/FreeCAD/Ex005_Extruded_Lines_and_Arcs.py deleted file mode 100644 index 9994434..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex005_Extruded_Lines_and_Arcs.py +++ /dev/null @@ -1,33 +0,0 @@ -#File: Ex005_Extruded_Lines_and_Arcs.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex005_Extruded_Lines_and_Arcs - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex005_Extruded_Lines_and_Arcs) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -#(Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the box's code directly. -width = 2.0 -thickness = 0.25 - -#Extrude a plate outline made of lines and an arc -result = cadquery.Workplane("front").lineTo(width, 0).lineTo(width, 1.0).threePointArc((1.0, 1.5),(0.0, 1.0)) \ - .close().extrude(thickness) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex006_Moving_the_Current_Working_Point.py b/Libs/cadquery-lib/examples/FreeCAD/Ex006_Moving_the_Current_Working_Point.py deleted file mode 100644 index 892396c..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex006_Moving_the_Current_Working_Point.py +++ /dev/null @@ -1,38 +0,0 @@ -#File: Ex006_Moving_the_Current_Working_Point.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex006_Moving_the_Current_Working_Point - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex006_Moving_the_Current_Working_Point) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the box's code directly. -circle_radius = 3.0 -thickness = 0.25 - -#Make the plate with two cutouts in it -result = cadquery.Workplane("front").circle(circle_radius) # Current point is the center of the circle, at (0,0) -result = result.center(1.5,0.0).rect(0.5,0.5) # New work center is (1.5,0.0) - -result = result.center(-1.5,1.5).circle(0.25) # New work center is ( 0.0,1.5). -#The new center is specified relative to the previous center, not global coordinates! - -result = result.extrude(thickness) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex007_Using_Point_Lists.py b/Libs/cadquery-lib/examples/FreeCAD/Ex007_Using_Point_Lists.py deleted file mode 100644 index 2609d84..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex007_Using_Point_Lists.py +++ /dev/null @@ -1,36 +0,0 @@ -#File: Ex007_Using_Point_Lists.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex007_Using_Point_Lists - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex007_Using_Point_Lists) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the box's code directly. -plate_radius = 2.0 -hole_pattern_radius = 0.25 -thickness = 0.125 - -#Make the plate with 4 holes in it at various points -r = cadquery.Workplane("front").circle(plate_radius) # Make the base -r = r.pushPoints([(1.5, 0), (0, 1.5), (-1.5, 0), (0, -1.5)]) # Now four points are on the stack -r = r.circle(hole_pattern_radius) # Circle will operate on all four points -result = r.extrude(thickness) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex008_Polygon_Creation.py b/Libs/cadquery-lib/examples/FreeCAD/Ex008_Polygon_Creation.py deleted file mode 100644 index 6eefe13..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex008_Polygon_Creation.py +++ /dev/null @@ -1,36 +0,0 @@ -#File: Ex008_Polygon_Creation.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex008_Polygon_Creation - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex008_Polygon_Creation) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the box's code directly. -width = 3.0 -height = 4.0 -thickness = 0.25 -polygon_sides = 6 -polygon_dia = 1.0 - -#Create a plate with two polygons cut through it -result = cadquery.Workplane("front").box(width, height, thickness).pushPoints([(0, 0.75), (0, -0.75)]) \ - .polygon(polygon_sides, polygon_dia).cutThruAll() - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex009_Polylines.py b/Libs/cadquery-lib/examples/FreeCAD/Ex009_Polylines.py deleted file mode 100644 index 73f9259..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex009_Polylines.py +++ /dev/null @@ -1,44 +0,0 @@ -#File: Ex009_Polylines.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex009_Polylines - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex009_Polylines) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Set up our Length, Height, Width, and thickness that will be used to define the locations that the polyline -#is drawn to/thru -(L, H, W, t) = (100.0, 20.0, 20.0, 1.0) - -#Define the locations that the polyline will be drawn to/thru -pts = [ - (0, H/2.0), - (W/2.0, H/2.0), - (W/2.0, (H/2.0 - t)), - (t/2.0, (H/2.0-t)), - (t/2.0, (t - H/2.0)), - (W/2.0, (t - H/2.0)), - (W/2.0, H/-2.0), - (0, H/-2.0) -] - -#We generate half of the I-beam outline and then mirror it to create the full I-beam -result = cadquery.Workplane("front").polyline(pts).mirrorY().extrude(L) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex010_Defining_an_Edge_with_a_Spline.py b/Libs/cadquery-lib/examples/FreeCAD/Ex010_Defining_an_Edge_with_a_Spline.py deleted file mode 100644 index 7a9534a..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex010_Defining_an_Edge_with_a_Spline.py +++ /dev/null @@ -1,45 +0,0 @@ -#File: Ex010_Defining_an_Edge_with_a_Spline.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex010_Defining_an_Edge_with_a_Spline - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex010_Defining_an_Edge_with_a_Spline) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The workplane we want to create the spline on to extrude -s = cadquery.Workplane("XY") - -#The points that the spline will pass through -sPnts = [ - (2.75, 1.5), - (2.5, 1.75), - (2.0, 1.5), - (1.5, 1.0), - (1.0, 1.25), - (0.5, 1.0), - (0, 1.0) -] - -#Generate our plate with the spline feature and make sure it's a closed entity -r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close() - -#Extrude to turn the wire into a plate -result = r.extrude(0.5) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) \ No newline at end of file diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex011_Mirroring_Symmetric_Geometry.py b/Libs/cadquery-lib/examples/FreeCAD/Ex011_Mirroring_Symmetric_Geometry.py deleted file mode 100644 index 54a02b6..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex011_Mirroring_Symmetric_Geometry.py +++ /dev/null @@ -1,34 +0,0 @@ -#File: Ex011_Mirroring_Symmetric_Geometry.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex011_Mirroring_Symmetric_Geometry - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex011_Mirroring_Symmetric_Geometry) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#1.0 is the distance, not coordinate -r = cadquery.Workplane("front").hLine(1.0) - -#hLineTo allows using xCoordinate not distance -r = r.vLine(0.5).hLine(-0.25).vLine(-0.25).hLineTo(0.0) - -#Mirror the geometry and extrude -result = r.mirrorY().extrude(0.25) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex012_Creating_Workplanes_on_Faces.py b/Libs/cadquery-lib/examples/FreeCAD/Ex012_Creating_Workplanes_on_Faces.py deleted file mode 100644 index 50a8ba3..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex012_Creating_Workplanes_on_Faces.py +++ /dev/null @@ -1,31 +0,0 @@ -#File: Ex012_Creating_Workplanes_on_Faces.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex012_Creating_Workplanes_on_Faces - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex012_Creating_Workplanes_on_Faces) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Make a basic prism -result = cadquery.Workplane("front").box(2,3,0.5) - -#Find the top-most face and make a hole -result = result.faces(">Z").workplane().hole(0.5) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex013_Locating_a_Workplane_on_a_Vertex.py b/Libs/cadquery-lib/examples/FreeCAD/Ex013_Locating_a_Workplane_on_a_Vertex.py deleted file mode 100644 index a50f74f..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex013_Locating_a_Workplane_on_a_Vertex.py +++ /dev/null @@ -1,34 +0,0 @@ -#File: Ex013_Locating_a_Workplane_on_a_Vertex.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex013_Locating_a_Workplane_on_a_Vertex - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex013_Locating_a_Workplane_on_a_Vertex) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Make a basic prism -result = cadquery.Workplane("front").box(3, 2, 0.5) - -#Select the lower left vertex and make a workplane -result = result.faces(">Z").vertices("Z").workplane() \ - .transformed(offset=Vector(0, -1.5, 1.0), rotate=Vector(60, 0, 0)) \ - .rect(1.5, 1.5, forConstruction=True).vertices().hole(0.25) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex016_Using_Construction_Geometry.py b/Libs/cadquery-lib/examples/FreeCAD/Ex016_Using_Construction_Geometry.py deleted file mode 100644 index 69ba013..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex016_Using_Construction_Geometry.py +++ /dev/null @@ -1,29 +0,0 @@ -#File: Ex016_Using_Construction_Geometry.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex016_Using_Construction_Geometry - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex016_Using_Construction_Geometry) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a block with holes in each corner of a rectangle on that workplane -result = cadquery.Workplane("front").box(2, 2, 0.5).faces(">Z").workplane() \ - .rect(1.5, 1.5, forConstruction=True).vertices().hole(0.125) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex017_Shelling_to_Create_Thin_Features.py b/Libs/cadquery-lib/examples/FreeCAD/Ex017_Shelling_to_Create_Thin_Features.py deleted file mode 100644 index 7965c44..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex017_Shelling_to_Create_Thin_Features.py +++ /dev/null @@ -1,28 +0,0 @@ -#File: Ex017_Shelling_to_Create_Thin_Features.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex017_Shelling_to_Create_Thin_Features - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex017_Shelling_to_Create_Thin_Features) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a hollow box that's open on both ends with a thin wall -result = cadquery.Workplane("front").box(2, 2, 2).faces("+Z").shell(0.05) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex018_Making_Lofts.py b/Libs/cadquery-lib/examples/FreeCAD/Ex018_Making_Lofts.py deleted file mode 100644 index 847285a..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex018_Making_Lofts.py +++ /dev/null @@ -1,29 +0,0 @@ -#File: Ex018_Making_Lofts.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex018_Making_Lofts - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex018_Making_Lofts) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a lofted section between a rectangle and a circular section -result = cadquery.Workplane("front").box(4.0, 4.0, 0.25).faces(">Z").circle(1.5) \ - .workplane(offset=3.0).rect(0.75, 0.5).loft(combine=True) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex019_Counter_Sunk_Holes.py b/Libs/cadquery-lib/examples/FreeCAD/Ex019_Counter_Sunk_Holes.py deleted file mode 100644 index 4a2590d..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex019_Counter_Sunk_Holes.py +++ /dev/null @@ -1,30 +0,0 @@ -#File: Ex019_Counter_Sunk_Holes.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex019_Counter_Sunk_Holes - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex019_Counter_Sunk_Holes) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a plate with 4 counter-sunk holes in it -result = cadquery.Workplane(cadquery.Plane.XY()).box(4, 2, 0.5).faces(">Z").workplane() \ - .rect(3.5, 1.5, forConstruction=True)\ - .vertices().cskHole(0.125, 0.25, 82.0, depth=None) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex020_Rounding_Corners_with_Fillets.py b/Libs/cadquery-lib/examples/FreeCAD/Ex020_Rounding_Corners_with_Fillets.py deleted file mode 100644 index 2d71322..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex020_Rounding_Corners_with_Fillets.py +++ /dev/null @@ -1,28 +0,0 @@ -#File: Ex020_Rounding_Corners_with_Fillets.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex020_Rounding_Corners_with_Fillets - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex020_Rounding_Corners_with_Fillets) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a plate with 4 rounded corners in the Z-axis -result = cadquery.Workplane("XY").box(3, 3, 0.5).edges("|Z").fillet(0.125) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex021_Splitting_an_Object.py b/Libs/cadquery-lib/examples/FreeCAD/Ex021_Splitting_an_Object.py deleted file mode 100644 index 133104a..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex021_Splitting_an_Object.py +++ /dev/null @@ -1,31 +0,0 @@ -#File: Ex021_Splitting_an_Object.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex021_Splitting_an_Object - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex021_Splitting_an_Object) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Create a simple block with a hole through it that we can split -c = cadquery.Workplane("XY").box(1, 1, 1).faces(">Z").workplane().circle(0.25).cutThruAll() - -#Cut the block in half sideways -result = c.faces(">Y").workplane(-0.5).split(keepTop=True) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex022_Classic_OCC_Bottle.py b/Libs/cadquery-lib/examples/FreeCAD/Ex022_Classic_OCC_Bottle.py deleted file mode 100644 index 8ea52c5..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex022_Classic_OCC_Bottle.py +++ /dev/null @@ -1,40 +0,0 @@ -#File: Ex022_Classic_OCC_Bottle.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex022_Classic_OCC_Bottle - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex022_Classic_OCC_Bottle) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Set up the length, width, and thickness -(L,w,t) = (20.0, 6.0, 3.0) -s = cadquery.Workplane("XY") - -#Draw half the profile of the bottle and extrude it -p = s.center(-L / 2.0, 0).vLine(w / 2.0) \ - .threePointArc((L / 2.0, w / 2.0 + t),(L, w / 2.0)).vLine(-w / 2.0) \ - .mirrorX().extrude(30.0, True) - -#Make the neck -p.faces(">Z").workplane().circle(3.0).extrude(2.0, True) - -#Make a shell -result = p.faces(">Z").shell(0.3) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex023_Parametric_Enclosure.py b/Libs/cadquery-lib/examples/FreeCAD/Ex023_Parametric_Enclosure.py deleted file mode 100644 index ef3308f..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex023_Parametric_Enclosure.py +++ /dev/null @@ -1,102 +0,0 @@ -#File: Ex023_Parametric_Enclosure.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex023_Parametric_Enclosure - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex023_Parametric_Enclosure) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#Parameter definitions -p_outerWidth = 100.0 # Outer width of box enclosure -p_outerLength = 150.0 # Outer length of box enclosure -p_outerHeight = 50.0 # Outer height of box enclosure - -p_thickness = 3.0 # Thickness of the box walls -p_sideRadius = 10.0 # Radius for the curves around the sides of the bo -p_topAndBottomRadius = 2.0 # Radius for the curves on the top and bottom edges of the box - -p_screwpostInset = 12.0 # How far in from the edges the screwposts should be placed -p_screwpostID = 4.0 # Inner diameter of the screwpost holes, should be roughly screw diameter not including threads -p_screwpostOD = 10.0 # Outer diameter of the screwposts. Determines overall thickness of the posts - -p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any -p_boreDepth = 1.0 # Depth of the counterbore hole, if -p_countersinkDiameter = 0.0 # Outer diameter of countersink. Should roughly match the outer diameter of the screw head -p_countersinkAngle = 90.0 # Countersink angle (complete angle between opposite sides, not from center to one side) -p_flipLid = True # Whether to place the lid with the top facing down or not. -p_lipHeight = 1.0 # Height of lip on the underside of the lid. Sits inside the box body for a snug fit. - -#Outer shell -oshell = cadquery.Workplane("XY").rect(p_outerWidth, p_outerLength).extrude(p_outerHeight + p_lipHeight) - -#Weird geometry happens if we make the fillets in the wrong order -if p_sideRadius > p_topAndBottomRadius: - oshell.edges("|Z").fillet(p_sideRadius) - oshell.edges("#Z").fillet(p_topAndBottomRadius) -else: - oshell.edges("#Z").fillet(p_topAndBottomRadius) - oshell.edges("|Z").fillet(p_sideRadius) - -#Inner shell -ishell = oshell.faces("Z").workplane(-p_thickness)\ - .rect(POSTWIDTH, POSTLENGTH, forConstruction=True)\ - .vertices() - -for v in postCenters.all(): - v.circle(p_screwpostOD / 2.0).circle(p_screwpostID / 2.0)\ - .extrude((-1.0) * ((p_outerHeight + p_lipHeight) - (2.0 * p_thickness)), True) - -#Split lid into top and bottom parts -(lid, bottom) = box.faces(">Z").workplane(-p_thickness - p_lipHeight).split(keepTop=True, keepBottom=True).all() - -#Translate the lid, and subtract the bottom from it to produce the lid inset -lowerLid = lid.translate((0, 0, -p_lipHeight)) -cutlip = lowerLid.cut(bottom).translate((p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight)) - -#Compute centers for counterbore/countersink or counterbore -topOfLidCenters = cutlip.faces(">Z").workplane().rect(POSTWIDTH, POSTLENGTH, forConstruction=True).vertices() - -#Add holes of the desired type -if p_boreDiameter > 0 and p_boreDepth > 0: - topOfLid = topOfLidCenters.cboreHole(p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness) -elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: - topOfLid = topOfLidCenters.cskHole(p_screwpostID, p_countersinkDiameter, p_countersinkAngle, (2.0) * p_thickness) -else: - topOfLid= topOfLidCenters.hole(p_screwpostID, 2.0 * p_thickness) - -#Flip lid upside down if desired -if p_flipLid: - topOfLid.rotateAboutCenter((1, 0, 0), 180) - -#Return the combined result -result = topOfLid.combineSolids(bottom) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py b/Libs/cadquery-lib/examples/FreeCAD/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py deleted file mode 100644 index 7a8088f..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py +++ /dev/null @@ -1,41 +0,0 @@ -#File: Ex024_Using_FreeCAD_Solids_as_CQ_Objects.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex024_Using_FreeCAD_Solids_as_CQ_Objects - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex024_Using_FreeCAD_Solids_as_CQ_Objects) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery, FreeCAD, Part - -#Create a new document that we can draw our model on -newDoc = FreeCAD.newDocument() - -#shows a 1x1x1 FreeCAD cube in the display -initialBox = newDoc.addObject("Part::Box","initialBox") -newDoc.recompute() - -#Make a CQ object -cqBox = cadquery.CQ(cadquery.Solid(initialBox.Shape)) - -#Extrude a peg -newThing = cqBox.faces(">Z").workplane().circle(0.5).extrude(0.25) - -#Add a FreeCAD object to the tree and then store a CQ object in it -nextShape = newDoc.addObject("Part::Feature", "nextShape") -nextShape.Shape = newThing.val().wrapped - -#Rerender the doc to see what the new solid looks like -newDoc.recompute() diff --git a/Libs/cadquery-lib/examples/FreeCAD/Ex025_Revolution.py b/Libs/cadquery-lib/examples/FreeCAD/Ex025_Revolution.py deleted file mode 100644 index e0f9364..0000000 --- a/Libs/cadquery-lib/examples/FreeCAD/Ex025_Revolution.py +++ /dev/null @@ -1,41 +0,0 @@ -#File: Ex025_Revolution.py -#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD" -#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad - -#You run this example by typing the following in the FreeCAD python console, making sure to change -#the path to this example, and the name of the example appropriately. -#import sys -#sys.path.append('/home/user/Downloads/cadquery/examples/FreeCAD') -#import Ex025_Revolution - -#If you need to reload the part after making a change, you can use the following lines within the FreeCAD console. -#reload(Ex025_Revolution) - -#You'll need to delete the original shape that was created, and the new shape should be named sequentially -# (Shape001, etc). - -#You can also tie these blocks of code to macros, buttons, and keybindings in FreeCAD for quicker access. -#You can get a more information on this example at -# http://parametricparts.com/docs/examples.html#an-extruded-prismatic-solid - -import cadquery -import Part - -#The dimensions of the model. These can be modified rather than changing the shape's code directly. -rectangle_width = 10.0 -rectangle_length = 10.0 -angle_degrees = 360.0 - -#Revolve a cylinder from a rectangle -#Switch comments around in this section to try the revolve operation with different parameters -result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve() -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve(angle_degrees) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5)) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5, -5),(-5, 5)) -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5),(-5,5), False) - -#Revolve a donut with square walls -#result = cadquery.Workplane("XY").rect(rectangle_width, rectangle_length, True).revolve(angle_degrees, (20, 0), (20, 10)) - -#Boiler plate code to render our solid in FreeCAD's GUI -Part.show(result.toFreecad()) diff --git a/Libs/cadquery-lib/registering.txt b/Libs/cadquery-lib/registering.txt deleted file mode 100644 index 0be612c..0000000 --- a/Libs/cadquery-lib/registering.txt +++ /dev/null @@ -1,11 +0,0 @@ -# -# Registering with Pypy -# -To register with pypy: - - (1) make sure you have python 2.6.x with setuptools installed, - ( source a virtual env ) - - (2) change version number in setup.py if you need - (3) python setup.py register - (4) python setup.py sdist upload \ No newline at end of file diff --git a/Libs/cadquery-lib/requirements-dev.txt b/Libs/cadquery-lib/requirements-dev.txt deleted file mode 100644 index 872a66d..0000000 --- a/Libs/cadquery-lib/requirements-dev.txt +++ /dev/null @@ -1,3 +0,0 @@ -sphinx-rtd-theme==0.1.9 -travis-sphinx==1.1.0 -Sphinx==1.3.1 diff --git a/Libs/cadquery-lib/requirements.txt b/Libs/cadquery-lib/requirements.txt deleted file mode 100644 index d6e1198..0000000 --- a/Libs/cadquery-lib/requirements.txt +++ /dev/null @@ -1 +0,0 @@ --e . diff --git a/Libs/cadquery-lib/runtests.py b/Libs/cadquery-lib/runtests.py deleted file mode 100644 index ee90ce4..0000000 --- a/Libs/cadquery-lib/runtests.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -from tests import * -import cadquery -import unittest - -#if you are on python 2.7, you can use -m uniitest discover. -#but this is required for python 2.6.6 on windows. FreeCAD0.12 will not load -#on py 2.7.x on win -suite = unittest.TestSuite() - -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCQGI.TestCQGI)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCadObjects.TestCadObjects)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestWorkplanes.TestWorkplanes)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCQSelectors.TestCQSelectors)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCadQuery.TestCadQuery)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestExporters.TestExporters)) -suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestImporters.TestImporters)) -unittest.TextTestRunner().run(suite) diff --git a/Libs/cadquery-lib/setup.cfg b/Libs/cadquery-lib/setup.cfg deleted file mode 100644 index e69de29..0000000 diff --git a/Libs/cadquery-lib/setup.py b/Libs/cadquery-lib/setup.py deleted file mode 100644 index 2e7018b..0000000 --- a/Libs/cadquery-lib/setup.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2015 Parametric Products Intellectual Holdings, LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -from setuptools import setup - - -#if we are building in travis, use the build number as the sub-minor version -version = '0.5-SNAPSHOT' -if 'TRAVIS_TAG' in os.environ.keys(): - version= os.environ['TRAVIS_TAG'] - - -setup( - name='cadquery', - version=version, - url='https://github.com/dcowden/cadquery', - license='Apache Public License 2.0', - author='David Cowden', - author_email='dave.cowden@gmail.com', - description='CadQuery is a parametric scripting language for creating and traversing CAD models', - long_description=open('README.md').read(), - packages=['cadquery','cadquery.contrib','cadquery.freecad_impl','cadquery.plugins','tests'], - install_requires=['pyparsing'], - include_package_data=True, - zip_safe=False, - platforms='any', - test_suite='tests', - - classifiers=[ - 'Development Status :: 5 - Production/Stable', - #'Development Status :: 6 - Mature', - #'Development Status :: 7 - Inactive', - 'Intended Audience :: Developers', - 'Intended Audience :: End Users/Desktop', - 'Intended Audience :: Information Technology', - 'Intended Audience :: Science/Research', - 'Intended Audience :: System Administrators', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: POSIX', - 'Operating System :: MacOS', - 'Operating System :: Unix', - 'Programming Language :: Python', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Internet', - 'Topic :: Scientific/Engineering' - ] -) diff --git a/Libs/cadquery-lib/tests/README.txt b/Libs/cadquery-lib/tests/README.txt deleted file mode 100644 index 99c6a4f..0000000 --- a/Libs/cadquery-lib/tests/README.txt +++ /dev/null @@ -1 +0,0 @@ -It is OK for tests to import implementations like FreeCAD directly. \ No newline at end of file diff --git a/Libs/cadquery-lib/tests/TestCQGI.py b/Libs/cadquery-lib/tests/TestCQGI.py deleted file mode 100644 index 7cc967f..0000000 --- a/Libs/cadquery-lib/tests/TestCQGI.py +++ /dev/null @@ -1,216 +0,0 @@ -""" - Tests CQGI functionality - - Currently, this includes: - Parsing a script, and detecting its available variables - Altering the values at runtime - defining a build_object function to return results -""" - -from cadquery import cqgi -from tests import BaseTest -import textwrap - -TESTSCRIPT = textwrap.dedent( - """ - height=2.0 - width=3.0 - (a,b) = (1.0,1.0) - foo="bar" - - result = "%s|%s|%s|%s" % ( str(height) , str(width) , foo , str(a) ) - build_object(result) - """ -) - -TEST_DEBUG_SCRIPT = textwrap.dedent( - """ - height=2.0 - width=3.0 - (a,b) = (1.0,1.0) - foo="bar" - debug(foo, { "color": 'yellow' } ) - result = "%s|%s|%s|%s" % ( str(height) , str(width) , foo , str(a) ) - build_object(result) - debug(height ) - """ -) - -class TestCQGI(BaseTest): - def test_parser(self): - model = cqgi.CQModel(TESTSCRIPT) - metadata = model.metadata - - self.assertEquals(set(metadata.parameters.keys()), {'height', 'width', 'a', 'b', 'foo'}) - - def test_build_with_debug(self): - model = cqgi.CQModel(TEST_DEBUG_SCRIPT) - result = model.build() - debugItems = result.debugObjects - self.assertTrue(len(debugItems) == 2) - self.assertTrue( debugItems[0].object == "bar" ) - self.assertTrue( debugItems[0].args == { "color":'yellow' } ) - self.assertTrue( debugItems[1].object == 2.0 ) - self.assertTrue( debugItems[1].args == {} ) - - def test_build_with_empty_params(self): - model = cqgi.CQModel(TESTSCRIPT) - result = model.build() - - self.assertTrue(result.success) - self.assertTrue(len(result.results) == 1) - self.assertTrue(result.results[0] == "2.0|3.0|bar|1.0") - - def test_build_with_different_params(self): - model = cqgi.CQModel(TESTSCRIPT) - result = model.build({'height': 3.0}) - self.assertTrue(result.results[0] == "3.0|3.0|bar|1.0") - - def test_describe_parameters(self): - script = textwrap.dedent( - """ - a = 2.0 - describe_parameter(a,'FirstLetter') - """ - ) - model = cqgi.CQModel(script) - a_param = model.metadata.parameters['a'] - self.assertTrue(a_param.default_value == 2.0) - self.assertTrue(a_param.desc == 'FirstLetter') - self.assertTrue(a_param.varType == cqgi.NumberParameterType ) - - def test_describe_parameter_invalid_doesnt_fail_script(self): - script = textwrap.dedent( - """ - a = 2.0 - describe_parameter(a, 2 - 1 ) - """ - ) - model = cqgi.CQModel(script) - a_param = model.metadata.parameters['a'] - self.assertTrue(a_param.name == 'a' ) - - def test_build_with_exception(self): - badscript = textwrap.dedent( - """ - raise ValueError("ERROR") - """ - ) - - model = cqgi.CQModel(badscript) - result = model.build({}) - self.assertFalse(result.success) - self.assertIsNotNone(result.exception) - self.assertTrue(result.exception.message == "ERROR") - - def test_that_invalid_syntax_in_script_fails_immediately(self): - badscript = textwrap.dedent( - """ - this doesnt even compile - """ - ) - - with self.assertRaises(Exception) as context: - model = cqgi.CQModel(badscript) - - self.assertTrue('invalid syntax' in context.exception) - - def test_that_two_results_are_returned(self): - script = textwrap.dedent( - """ - h = 1 - build_object(h) - h = 2 - build_object(h) - """ - ) - - model = cqgi.CQModel(script) - result = model.build({}) - self.assertEquals(2, len(result.results)) - self.assertEquals(1, result.results[0]) - self.assertEquals(2, result.results[1]) - - def test_that_assinging_number_to_string_works(self): - script = textwrap.dedent( - """ - h = "this is a string" - build_object(h) - """ - ) - result = cqgi.parse(script).build( {'h': 33.33}) - self.assertEquals(result.results[0], "33.33") - - def test_that_assigning_string_to_number_fails(self): - script = textwrap.dedent( - """ - h = 20.0 - build_object(h) - """ - ) - result = cqgi.parse(script).build( {'h': "a string"}) - self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError)) - - def test_that_assigning_unknown_var_fails(self): - script = textwrap.dedent( - """ - h = 20.0 - build_object(h) - """ - ) - - result = cqgi.parse(script).build( {'w': "var is not there"}) - self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError)) - - def test_that_not_calling_build_object_raises_error(self): - script = textwrap.dedent( - """ - h = 20.0 - """ - ) - result = cqgi.parse(script).build() - self.assertTrue(isinstance(result.exception, cqgi.NoOutputError)) - - def test_that_cq_objects_are_visible(self): - script = textwrap.dedent( - """ - r = cadquery.Workplane('XY').box(1,2,3) - build_object(r) - """ - ) - - result = cqgi.parse(script).build() - self.assertTrue(result.success) - self.assertIsNotNone(result.first_result) - - def test_setting_boolean_variable(self): - script = textwrap.dedent( - """ - h = True - build_object( "*%s*" % str(h) ) - """ - ) - - #result = cqgi.execute(script) - result = cqgi.parse(script).build({'h': False}) - - self.assertTrue(result.success) - self.assertEquals(result.first_result,'*False*') - - def test_that_only_top_level_vars_are_detected(self): - script = textwrap.dedent( - """ - h = 1.0 - w = 2.0 - - def do_stuff(): - x = 1 - y = 2 - - build_object( "result" ) - """ - ) - - model = cqgi.parse(script) - - self.assertEquals(2, len(model.metadata.parameters)) \ No newline at end of file diff --git a/Libs/cadquery-lib/tests/TestCQSelectors.py b/Libs/cadquery-lib/tests/TestCQSelectors.py deleted file mode 100644 index 9b5e12f..0000000 --- a/Libs/cadquery-lib/tests/TestCQSelectors.py +++ /dev/null @@ -1,459 +0,0 @@ -__author__ = 'dcowden' - -""" - Tests for CadQuery Selectors - - These tests do not construct any solids, they test only selectors that query - an existing solid - -""" - -import math -import unittest,sys -import os.path - -#my modules -from tests import BaseTest,makeUnitCube,makeUnitSquareWire -from cadquery import * -from cadquery import selectors - -class TestCQSelectors(BaseTest): - - - def testWorkplaneCenter(self): - "Test Moving workplane center" - s = Workplane(Plane.XY()) - - #current point and world point should be equal - self.assertTupleAlmostEquals((0.0,0.0,0.0),s.plane.origin.toTuple(),3) - - #move origin and confirm center moves - s.center(-2.0,-2.0) - - #current point should be 0,0, but - - self.assertTupleAlmostEquals((-2.0,-2.0,0.0),s.plane.origin.toTuple(),3) - - - def testVertices(self): - t = makeUnitSquareWire() # square box - c = CQ(t) - - self.assertEqual(4,c.vertices().size() ) - self.assertEqual(4,c.edges().size() ) - self.assertEqual(0,c.vertices().edges().size() ) #no edges on any vertices - self.assertEqual(4,c.edges().vertices().size() ) #but selecting all edges still yields all vertices - self.assertEqual(1,c.wires().size()) #just one wire - self.assertEqual(0,c.faces().size()) - self.assertEqual(0,c.vertices().faces().size()) #odd combinations all work but yield no results - self.assertEqual(0,c.edges().faces().size()) - self.assertEqual(0,c.edges().vertices().faces().size()) - - def testEnd(self): - c = CQ(makeUnitSquareWire()) - self.assertEqual(4,c.vertices().size() ) #4 because there are 4 vertices - self.assertEqual(1,c.vertices().end().size() ) #1 because we started with 1 wire - - def testAll(self): - "all returns a list of CQ objects, so that you can iterate over them individually" - c = CQ(makeUnitCube()) - self.assertEqual(6,c.faces().size()) - self.assertEqual(6,len(c.faces().all())) - self.assertEqual(4,c.faces().all()[0].vertices().size() ) - - def testFirst(self): - c = CQ( makeUnitCube()) - self.assertEqual(type(c.vertices().first().val()),Vertex) - self.assertEqual(type(c.vertices().first().first().first().val()),Vertex) - - def testCompounds(self): - c = CQ(makeUnitSquareWire()) - self.assertEqual(0,c.compounds().size() ) - self.assertEqual(0,c.shells().size() ) - self.assertEqual(0,c.solids().size() ) - - def testSolid(self): - c = CQ(makeUnitCube()) - #make sure all the counts are right for a cube - self.assertEqual(1,c.solids().size() ) - self.assertEqual(6,c.faces().size() ) - self.assertEqual(12,c.edges().size()) - self.assertEqual(8,c.vertices().size() ) - self.assertEqual(0,c.compounds().size()) - - #now any particular face should result in 4 edges and four vertices - self.assertEqual(4,c.faces().first().edges().size() ) - self.assertEqual(1,c.faces().first().size() ) - self.assertEqual(4,c.faces().first().vertices().size() ) - - self.assertEqual(4,c.faces().last().edges().size() ) - - - - def testFaceTypesFilter(self): - "Filters by face type" - c = CQ(makeUnitCube()) - self.assertEqual(c.faces().size(), c.faces('%PLANE').size()) - self.assertEqual(c.faces().size(), c.faces('%plane').size()) - self.assertEqual(0, c.faces('%sphere').size()) - self.assertEqual(0, c.faces('%cone').size()) - self.assertEqual(0, c.faces('%SPHERE').size()) - - def testPerpendicularDirFilter(self): - c = CQ(makeUnitCube()) - - self.assertEqual(8,c.edges("#Z").size() ) #8 edges are perp. to z - self.assertEqual(4, c.faces("#Z").size()) #4 faces are perp to z too! - - def testFaceDirFilter(self): - c = CQ(makeUnitCube()) - #a cube has one face in each direction - self.assertEqual(1, c.faces("+Z").size()) - self.assertEqual(1, c.faces("-Z").size()) - self.assertEqual(1, c.faces("+X").size()) - self.assertEqual(1, c.faces("X").size()) #should be same as +X - self.assertEqual(1, c.faces("-X").size()) - self.assertEqual(1, c.faces("+Y").size()) - self.assertEqual(1, c.faces("-Y").size()) - self.assertEqual(0, c.faces("XY").size()) - - def testParallelPlaneFaceFilter(self): - c = CQ(makeUnitCube()) - - #faces parallel to Z axis - self.assertEqual(2, c.faces("|Z").size()) - #TODO: provide short names for ParallelDirSelector - self.assertEqual(2, c.faces(selectors.ParallelDirSelector(Vector((0,0,1)))).size()) #same thing as above - self.assertEqual(2, c.faces(selectors.ParallelDirSelector(Vector((0,0,-1)))).size()) #same thing as above - - #just for fun, vertices on faces parallel to z - self.assertEqual(8, c.faces("|Z").vertices().size()) - - def testParallelEdgeFilter(self): - c = CQ(makeUnitCube()) - self.assertEqual(4, c.edges("|Z").size()) - self.assertEqual(4, c.edges("|X").size()) - self.assertEqual(4, c.edges("|Y").size()) - - def testMaxDistance(self): - c = CQ(makeUnitCube()) - - #should select the topmost face - self.assertEqual(1, c.faces(">Z").size()) - self.assertEqual(4, c.faces(">Z").vertices().size()) - - #vertices should all be at z=1, if this is the top face - self.assertEqual(4, len(c.faces(">Z").vertices().vals() )) - for v in c.faces(">Z").vertices().vals(): - self.assertAlmostEqual(1.0,v.Z,3) - - # test the case of multiple objects at the same distance - el = c.edges("(1,0,0)[1]').val() - self.assertAlmostEqual(val.Center().x,-1.5) - - #2nd face with inversed selection vector - val = c.faces('>(-1,0,0)[1]').val() - self.assertAlmostEqual(val.Center().x,1.5) - - #2nd last face - val = c.faces('>X[-2]').val() - self.assertAlmostEqual(val.Center().x,1.5) - - #Last face - val = c.faces('>X[-1]').val() - self.assertAlmostEqual(val.Center().x,2.5) - - #check if the selected face if normal to the specified Vector - self.assertAlmostEqual(val.normalAt().cross(Vector(1,0,0)).Length,0.0) - - - def testNearestTo(self): - c = CQ(makeUnitCube()) - - #nearest vertex to origin is (0,0,0) - t = (0.1,0.1,0.1) - - v = c.vertices(selectors.NearestToPointSelector(t)).vals()[0] - self.assertTupleAlmostEquals((0.0,0.0,0.0),(v.X,v.Y,v.Z),3) - - t = (0.1,0.1,0.2) - #nearest edge is the vertical side edge, 0,0,0 -> 0,0,1 - e = c.edges(selectors.NearestToPointSelector(t)).vals()[0] - v = c.edges(selectors.NearestToPointSelector(t)).vertices().vals() - self.assertEqual(2,len(v)) - - #nearest solid is myself - s = c.solids(selectors.NearestToPointSelector(t)).vals() - self.assertEqual(1,len(s)) - - def testBox(self): - c = CQ(makeUnitCube()) - - # test vertice selection - test_data_vertices = [ - # box point0, box point1, selected vertice - ((0.9, 0.9, 0.9), (1.1, 1.1, 1.1), (1.0, 1.0, 1.0)), - ((-0.1, 0.9, 0.9), (0.9, 1.1, 1.1), (0.0, 1.0, 1.0)), - ((-0.1, -0.1, 0.9), (0.1, 0.1, 1.1), (0.0, 0.0, 1.0)), - ((-0.1, -0.1, -0.1), (0.1, 0.1, 0.1), (0.0, 0.0, 0.0)), - ((0.9, -0.1, -0.1), (1.1, 0.1, 0.1), (1.0, 0.0, 0.0)), - ((0.9, 0.9, -0.1), (1.1, 1.1, 0.1), (1.0, 1.0, 0.0)), - ((-0.1, 0.9, -0.1), (0.1, 1.1, 0.1), (0.0, 1.0, 0.0)), - ((0.9, -0.1, 0.9), (1.1, 0.1, 1.1), (1.0, 0.0, 1.0)) - ] - - for d in test_data_vertices: - vl = c.vertices(selectors.BoxSelector(d[0], d[1])).vals() - self.assertEqual(1, len(vl)) - v = vl[0] - self.assertTupleAlmostEquals(d[2], (v.X, v.Y, v.Z), 3) - - # this time box points are swapped - vl = c.vertices(selectors.BoxSelector(d[1], d[0])).vals() - self.assertEqual(1, len(vl)) - v = vl[0] - self.assertTupleAlmostEquals(d[2], (v.X, v.Y, v.Z), 3) - - # test multiple vertices selection - vl = c.vertices(selectors.BoxSelector((-0.1, -0.1, 0.9),(0.1, 1.1, 1.1))).vals() - self.assertEqual(2, len(vl)) - vl = c.vertices(selectors.BoxSelector((-0.1, -0.1, -0.1),(0.1, 1.1, 1.1))).vals() - self.assertEqual(4, len(vl)) - - # test edge selection - test_data_edges = [ - # box point0, box point1, edge center - ((0.4, -0.1, -0.1), (0.6, 0.1, 0.1), (0.5, 0.0, 0.0)), - ((-0.1, -0.1, 0.4), (0.1, 0.1, 0.6), (0.0, 0.0, 0.5)), - ((0.9, 0.9, 0.4), (1.1, 1.1, 0.6), (1.0, 1.0, 0.5)), - ((0.4, 0.9, 0.9), (0.6, 1.1, 1.1,), (0.5, 1.0, 1.0)) - ] - - for d in test_data_edges: - el = c.edges(selectors.BoxSelector(d[0], d[1])).vals() - self.assertEqual(1, len(el)) - ec = el[0].Center() - self.assertTupleAlmostEquals(d[2], (ec.x, ec.y, ec.z), 3) - - # test again by swapping box points - el = c.edges(selectors.BoxSelector(d[1], d[0])).vals() - self.assertEqual(1, len(el)) - ec = el[0].Center() - self.assertTupleAlmostEquals(d[2], (ec.x, ec.y, ec.z), 3) - - # test multiple edge selection - el = c.edges(selectors.BoxSelector((-0.1, -0.1, -0.1), (0.6, 0.1, 0.6))).vals() - self.assertEqual(2, len(el)) - el = c.edges(selectors.BoxSelector((-0.1, -0.1, -0.1), (1.1, 0.1, 0.6))).vals() - self.assertEqual(3, len(el)) - - # test face selection - test_data_faces = [ - # box point0, box point1, face center - ((0.4, -0.1, 0.4), (0.6, 0.1, 0.6), (0.5, 0.0, 0.5)), - ((0.9, 0.4, 0.4), (1.1, 0.6, 0.6), (1.0, 0.5, 0.5)), - ((0.4, 0.4, 0.9), (0.6, 0.6, 1.1), (0.5, 0.5, 1.0)), - ((0.4, 0.4, -0.1), (0.6, 0.6, 0.1), (0.5, 0.5, 0.0)) - ] - - for d in test_data_faces: - fl = c.faces(selectors.BoxSelector(d[0], d[1])).vals() - self.assertEqual(1, len(fl)) - fc = fl[0].Center() - self.assertTupleAlmostEquals(d[2], (fc.x, fc.y, fc.z), 3) - - # test again by swapping box points - fl = c.faces(selectors.BoxSelector(d[1], d[0])).vals() - self.assertEqual(1, len(fl)) - fc = fl[0].Center() - self.assertTupleAlmostEquals(d[2], (fc.x, fc.y, fc.z), 3) - - # test multiple face selection - fl = c.faces(selectors.BoxSelector((0.4, 0.4, 0.4), (0.6, 1.1, 1.1))).vals() - self.assertEqual(2, len(fl)) - fl = c.faces(selectors.BoxSelector((0.4, 0.4, 0.4), (1.1, 1.1, 1.1))).vals() - self.assertEqual(3, len(fl)) - - # test boundingbox option - el = c.edges(selectors.BoxSelector((-0.1, -0.1, -0.1), (1.1, 0.1, 0.6), True)).vals() - self.assertEqual(1, len(el)) - fl = c.faces(selectors.BoxSelector((0.4, 0.4, 0.4), (1.1, 1.1, 1.1), True)).vals() - self.assertEqual(0, len(fl)) - fl = c.faces(selectors.BoxSelector((-0.1, 0.4, -0.1), (1.1, 1.1, 1.1), True)).vals() - self.assertEqual(1, len(fl)) - - def testAndSelector(self): - c = CQ(makeUnitCube()) - - S = selectors.StringSyntaxSelector - BS = selectors.BoxSelector - - el = c.edges(selectors.AndSelector(S('|X'), BS((-2,-2,0.1), (2,2,2)))).vals() - self.assertEqual(2, len(el)) - - # test 'and' (intersection) operator - el = c.edges(S('|X') & BS((-2,-2,0.1), (2,2,2))).vals() - self.assertEqual(2, len(el)) - - # test using extended string syntax - v = c.vertices(">X and >Y").vals() - self.assertEqual(2, len(v)) - - def testSumSelector(self): - c = CQ(makeUnitCube()) - - S = selectors.StringSyntaxSelector - - fl = c.faces(selectors.SumSelector(S(">Z"), S("Z") + S("Z or X"))).vals() - self.assertEqual(3, len(fl)) - - # test the subtract operator - fl = c.faces(S("#Z") - S(">X")).vals() - self.assertEqual(3, len(fl)) - - # test using extended string syntax - fl = c.faces("#Z exc >X").vals() - self.assertEqual(3, len(fl)) - - def testInverseSelector(self): - c = CQ(makeUnitCube()) - - S = selectors.StringSyntaxSelector - - fl = c.faces(selectors.InverseSelector(S('>Z'))).vals() - self.assertEqual(5, len(fl)) - el = c.faces('>Z').edges(selectors.InverseSelector(S('>X'))).vals() - self.assertEqual(3, len(el)) - - # test invert operator - fl = c.faces(-S('>Z')).vals() - self.assertEqual(5, len(fl)) - el = c.faces('>Z').edges(-S('>X')).vals() - self.assertEqual(3, len(el)) - - # test using extended string syntax - fl = c.faces('not >Z').vals() - self.assertEqual(5, len(fl)) - el = c.faces('>Z').edges('not >X').vals() - self.assertEqual(3, len(el)) - - def testComplexStringSelector(self): - c = CQ(makeUnitCube()) - - v = c.vertices('(>X and >Y) or (XZ', - '(1,4,55.)[20]', - '|XY', - '(0,0,1) or XY except >(1,1,1)[-1]', - '(not |(1,1,0) and >(0,0,1)) exc XY and (Z or X)', - 'not ( X or Y )'] - - for e in expressions: gram.parseString(e,parseAll=True) - \ No newline at end of file diff --git a/Libs/cadquery-lib/tests/TestCadObjects.py b/Libs/cadquery-lib/tests/TestCadObjects.py deleted file mode 100644 index 3b2f98e..0000000 --- a/Libs/cadquery-lib/tests/TestCadObjects.py +++ /dev/null @@ -1,104 +0,0 @@ -#system modules -import sys -import unittest -from tests import BaseTest -import FreeCAD -import Part - - -from cadquery import * - -class TestCadObjects(BaseTest): - - def testVectorConstructors(self): - v1 = Vector(1, 2, 3) - v2 = Vector((1, 2, 3)) - v3 = Vector(FreeCAD.Base.Vector(1, 2, 3)) - - for v in [v1, v2, v3]: - self.assertTupleAlmostEquals((1, 2, 3), v.toTuple(), 4) - - def testVertex(self): - """ - Tests basic vertex functions - """ - v = Vertex(Part.Vertex(1, 1, 1)) - self.assertEqual(1, v.X) - self.assertEquals(Vector, type(v.Center())) - - def testBasicBoundingBox(self): - v = Vertex(Part.Vertex(1, 1, 1)) - v2 = Vertex(Part.Vertex(2, 2, 2)) - self.assertEquals(BoundBox, type(v.BoundingBox())) - self.assertEquals(BoundBox, type(v2.BoundingBox())) - - bb1 = v.BoundingBox().add(v2.BoundingBox()) - - self.assertEquals(bb1.xlen, 1.0) - - def testEdgeWrapperCenter(self): - e = Edge(Part.makeCircle(2.0, FreeCAD.Base.Vector(1, 2, 3))) - - self.assertTupleAlmostEquals((1.0, 2.0, 3.0), e.Center().toTuple(), 3) - - def testEdgeWrapperMakeCircle(self): - halfCircleEdge = Edge.makeCircle(radius=10, pnt=(0, 0, 0), dir=(0, 0, 1), angle1=0, angle2=180) - - self.assertTupleAlmostEquals((0.0, 5.0, 0.0), halfCircleEdge.CenterOfBoundBox(0.0001).toTuple(),3) - self.assertTupleAlmostEquals((10.0, 0.0, 0.0), halfCircleEdge.startPoint().toTuple(), 3) - self.assertTupleAlmostEquals((-10.0, 0.0, 0.0), halfCircleEdge.endPoint().toTuple(), 3) - - def testFaceWrapperMakePlane(self): - mplane = Face.makePlane(10,10) - - self.assertTupleAlmostEquals((0.0, 0.0, 1.0), mplane.normalAt().toTuple(), 3) - - def testCenterOfBoundBox(self): - pass - - def testCombinedCenterOfBoundBox(self): - pass - - def testCompoundCenter(self): - """ - Tests whether or not a proper weighted center can be found for a compound - """ - def cylinders(self, radius, height): - def _cyl(pnt): - # Inner function to build a cylinder - return Solid.makeCylinder(radius, height, pnt) - - # Combine all the cylinders into a single compound - r = self.eachpoint(_cyl, True).combineSolids() - - return r - - Workplane.cyl = cylinders - - # Now test. here we want weird workplane to see if the objects are transformed right - s = Workplane("XY").rect(2.0, 3.0, forConstruction=True).vertices().cyl(0.25, 0.5) - - self.assertEquals(4, len(s.val().Solids())) - self.assertTupleAlmostEquals((0.0, 0.0, 0.25), s.val().Center().toTuple(), 3) - - def testDot(self): - v1 = Vector(2, 2, 2) - v2 = Vector(1, -1, 1) - self.assertEquals(2.0, v1.dot(v2)) - - def testVectorAdd(self): - result = Vector(1, 2, 0) + Vector(0, 0, 3) - self.assertTupleAlmostEquals((1.0, 2.0, 3.0), result.toTuple(), 3) - - def testTranslate(self): - e = Shape.cast(Part.makeCircle(2.0, FreeCAD.Base.Vector(1, 2, 3))) - e2 = e.translate(Vector(0, 0, 1)) - - self.assertTupleAlmostEquals((1.0, 2.0, 4.0), e2.Center().toTuple(), 3) - - def testVertices(self): - e = Shape.cast(Part.makeLine((0, 0, 0), (1, 1, 0))) - self.assertEquals(2, len(e.Vertices())) - -if __name__ == '__main__': - unittest.main() diff --git a/Libs/cadquery-lib/tests/TestCadQuery.py b/Libs/cadquery-lib/tests/TestCadQuery.py deleted file mode 100644 index f12165a..0000000 --- a/Libs/cadquery-lib/tests/TestCadQuery.py +++ /dev/null @@ -1,1413 +0,0 @@ -""" - This module tests cadquery creation and manipulation functions - -""" -#system modules -import math,sys,os.path,time - -#my modules -from cadquery import * -from cadquery import exporters -from tests import BaseTest,writeStringToFile,makeUnitCube,readFileAsString,makeUnitSquareWire,makeCube - -#where unit test output will be saved -import sys -if sys.platform.startswith("win"): - OUTDIR = "c:/temp" -else: - OUTDIR = "/tmp" -SUMMARY_FILE = os.path.join(OUTDIR,"testSummary.html") - -SUMMARY_TEMPLATE=""" - - - - - - -""" - -TEST_RESULT_TEMPLATE=""" -

%(name)s

- %(svg)s -
- -""" - -#clean up any summary file that is in the output directory. -#i know, this sux, but there is no other way to do this in 2.6, as we cannot do class fixutres till 2.7 -writeStringToFile(SUMMARY_TEMPLATE,SUMMARY_FILE) - - -class TestCadQuery(BaseTest): - - def tearDown(self): - """ - Update summary with data from this test. - This is a really hackey way of doing it-- we get a startup event from module load, - but there is no way in unittest to get a single shutdown event-- except for stuff in 2.7 and above - - So what we do here is to read the existing file, stick in more content, and leave it - """ - svgFile = os.path.join(OUTDIR,self._testMethodName + ".svg") - - #all tests do not produce output - if os.path.exists(svgFile): - existingSummary = readFileAsString(SUMMARY_FILE) - svgText = readFileAsString(svgFile) - svgText = svgText.replace('',"") - - #now write data into the file - #the content we are replacing it with also includes the marker, so it can be replaced again - existingSummary = existingSummary.replace("", TEST_RESULT_TEMPLATE % ( - dict(svg=svgText, name=self._testMethodName))) - - writeStringToFile(existingSummary,SUMMARY_FILE) - - def saveModel(self, shape): - """ - shape must be a CQ object - Save models in SVG and STEP format - """ - shape.exportSvg(os.path.join(OUTDIR,self._testMethodName + ".svg")) - shape.val().exportStep(os.path.join(OUTDIR,self._testMethodName + ".step")) - - def testToFreeCAD(self): - """ - Tests to make sure that a CadQuery object is converted correctly to a FreeCAD object. - """ - r = Workplane('XY').rect(5, 5).extrude(5) - - r = r.toFreecad() - - self.assertEqual(12, len(r.Edges)) - - def testToSVG(self): - """ - Tests to make sure that a CadQuery object is converted correctly to SVG - """ - r = Workplane('XY').rect(5, 5).extrude(5) - - r_str = r.toSvg() - - # Make sure that a couple of sections from the SVG output make sense - self.assertTrue(r_str.index('path d=" M 2.35965 -2.27987 L 4.0114 -3.23936 "') > 0) - self.assertTrue(r_str.index('line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3"') > 0) - - def testCubePlugin(self): - """ - Tests a plugin that combines cubes together with a base - :return: - """ - #make the plugin method - def makeCubes(self,length): - #self refers to the CQ or Workplane object - - #inner method that creates a cube - def _singleCube(pnt): - #pnt is a location in local coordinates - #since we're using eachpoint with useLocalCoordinates=True - return Solid.makeBox(length,length,length,pnt) - - #use CQ utility method to iterate over the stack, call our - #method, and convert to/from local coordinates. - return self.eachpoint(_singleCube,True) - - #link the plugin in - Workplane.makeCubes = makeCubes - - #call it - result = Workplane("XY").box(6.0,8.0,0.5).faces(">Z").rect(4.0,4.0,forConstruction=True).vertices() - result = result.makeCubes(1.0) - result = result.combineSolids() - self.saveModel(result) - self.assertEquals(1,result.solids().size() ) - - - def testCylinderPlugin(self): - """ - Tests a cylinder plugin. - The plugin creates cylinders of the specified radius and height for each item on the stack - - This is a very short plugin that illustrates just about the simplest possible - plugin - """ - - def cylinders(self,radius,height): - - def _cyl(pnt): - #inner function to build a cylinder - return Solid.makeCylinder(radius,height,pnt) - - #combine all the cylinders into a single compound - r = self.eachpoint(_cyl,True).combineSolids() - return r - Workplane.cyl = cylinders - - #now test. here we want weird workplane to see if the objects are transformed right - s = Workplane(Plane(Vector((0,0,0)),Vector((1,-1,0)),Vector((1,1,0)))).rect(2.0,3.0,forConstruction=True).vertices() \ - .cyl(0.25,0.5) - self.assertEquals(1,s.solids().size() ) - self.saveModel(s) - - def testPolygonPlugin(self): - """ - Tests a plugin to make regular polygons around points on the stack - - Demonstratings using eachpoint to allow working in local coordinates - to create geometry - """ - def rPoly(self,nSides,diameter): - - def _makePolygon(center): - #pnt is a vector in local coordinates - angle = 2.0 *math.pi / nSides - pnts = [] - for i in range(nSides+1): - pnts.append( center + Vector((diameter / 2.0 * math.cos(angle*i)),(diameter / 2.0 * math.sin(angle*i)),0)) - return Wire.makePolygon(pnts) - - return self.eachpoint(_makePolygon,True) - - Workplane.rPoly = rPoly - - s = Workplane("XY").box(4.0,4.0,0.25).faces(">Z").workplane().rect(2.0,2.0,forConstruction=True).vertices()\ - .rPoly(5,0.5).cutThruAll() - - self.assertEquals(26,s.faces().size()) #6 base sides, 4 pentagons, 5 sides each = 26 - self.saveModel(s) - - - def testPointList(self): - """ - Tests adding points and using them - """ - c = CQ(makeUnitCube()) - - s = c.faces(">Z").workplane().pushPoints([(-0.3, 0.3), (0.3, 0.3), (0, 0)]) - self.assertEqual(3, s.size()) - #TODO: is the ability to iterate over points with circle really worth it? - #maybe we should just require using all() and a loop for this. the semantics and - #possible combinations got too hard ( ie, .circle().circle() ) was really odd - body = s.circle(0.05).cutThruAll() - self.saveModel(body) - self.assertEqual(9, body.faces().size()) - - # Test the case when using eachpoint with only a blank workplane - def callback_fn(pnt): - self.assertEqual((0.0, 0.0), (pnt.x, pnt.y)) - - r = Workplane('XY') - r.objects = [] - r.eachpoint(callback_fn) - - - def testWorkplaneFromFace(self): - s = CQ(makeUnitCube()).faces(">Z").workplane() #make a workplane on the top face - r = s.circle(0.125).cutBlind(-2.0) - self.saveModel(r) - #the result should have 7 faces - self.assertEqual(7,r.faces().size() ) - self.assertEqual(type(r.val()), Solid) - self.assertEqual(type(r.first().val()),Solid) - - def testFrontReference(self): - s = CQ(makeUnitCube()).faces("front").workplane() #make a workplane on the top face - r = s.circle(0.125).cutBlind(-2.0) - self.saveModel(r) - #the result should have 7 faces - self.assertEqual(7,r.faces().size() ) - self.assertEqual(type(r.val()), Solid) - self.assertEqual(type(r.first().val()),Solid) - - def testRotate(self): - """Test solid rotation at the CQ object level.""" - box = Workplane("XY").box(1, 1, 5) - box.rotate((0, 0, 0), (1, 0, 0), 90) - startPoint = box.faces("Z").circle(1.5)\ - .workplane(offset=3.0).rect(0.75,0.5).loft(combine=True) - self.saveModel(s) - #self.assertEqual(1,s.solids().size() ) - #self.assertEqual(8,s.faces().size() ) - - def testRevolveCylinder(self): - """ - Test creating a solid using the revolve operation. - :return: - """ - # The dimensions of the model. These can be modified rather than changing the - # shape's code directly. - rectangle_width = 10.0 - rectangle_length = 10.0 - angle_degrees = 360.0 - - #Test revolve without any options for making a cylinder - result = Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve() - self.assertEqual(3, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - - #Test revolve when only setting the angle to revolve through - result = Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve(angle_degrees) - self.assertEqual(3, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - result = Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve(270.0) - self.assertEqual(5, result.faces().size()) - self.assertEqual(6, result.vertices().size()) - self.assertEqual(9, result.edges().size()) - - #Test when passing revolve the angle and the axis of revolution's start point - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5)) - self.assertEqual(3, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(270.0,(-5,-5)) - self.assertEqual(5, result.faces().size()) - self.assertEqual(6, result.vertices().size()) - self.assertEqual(9, result.edges().size()) - - #Test when passing revolve the angle and both the start and ends of the axis of revolution - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5, -5),(-5, 5)) - self.assertEqual(3, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(270.0,(-5, -5),(-5, 5)) - self.assertEqual(5, result.faces().size()) - self.assertEqual(6, result.vertices().size()) - self.assertEqual(9, result.edges().size()) - - #Testing all of the above without combine - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5),(-5,5), False) - self.assertEqual(3, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - result = Workplane("XY").rect(rectangle_width, rectangle_length).revolve(270.0,(-5,-5),(-5,5), False) - self.assertEqual(5, result.faces().size()) - self.assertEqual(6, result.vertices().size()) - self.assertEqual(9, result.edges().size()) - - def testRevolveDonut(self): - """ - Test creating a solid donut shape with square walls - :return: - """ - # The dimensions of the model. These can be modified rather than changing the - # shape's code directly. - rectangle_width = 10.0 - rectangle_length = 10.0 - angle_degrees = 360.0 - - result = Workplane("XY").rect(rectangle_width, rectangle_length, True)\ - .revolve(angle_degrees, (20, 0), (20, 10)) - self.assertEqual(4, result.faces().size()) - self.assertEqual(4, result.vertices().size()) - self.assertEqual(6, result.edges().size()) - - def testRevolveCone(self): - """ - Test creating a solid from a revolved triangle - :return: - """ - result = Workplane("XY").lineTo(0,10).lineTo(5,0).close().revolve() - self.assertEqual(2, result.faces().size()) - self.assertEqual(2, result.vertices().size()) - self.assertEqual(3, result.edges().size()) - - def testSweep(self): - """ - Tests the operation of sweeping a wire(s) along a path - """ - pts = [ - (0, 1), - (1, 2), - (2, 4) - ] - - # Spline path - path = Workplane("XZ").spline(pts) - - # Test defaults - result = Workplane("XY").circle(1.0).sweep(path) - self.assertEqual(3, result.faces().size()) - self.assertEqual(3, result.edges().size()) - - # Test with makeSolid False - result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False) - self.assertEqual(1, result.faces().size()) - self.assertEqual(3, result.edges().size()) - - # Test with isFrenet True - result = Workplane("XY").circle(1.0).sweep(path, isFrenet=True) - self.assertEqual(3, result.faces().size()) - self.assertEqual(3, result.edges().size()) - - # Test with makeSolid False and isFrenet True - result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False, isFrenet=True) - self.assertEqual(1, result.faces().size()) - self.assertEqual(3, result.edges().size()) - - # Test rectangle with defaults - result = Workplane("XY").rect(1.0, 1.0).sweep(path) - self.assertEqual(6, result.faces().size()) - self.assertEqual(12, result.edges().size()) - - # Polyline path - path = Workplane("XZ").polyline(pts) - - # Test defaults - result = Workplane("XY").circle(0.1).sweep(path) - self.assertEqual(5, result.faces().size()) - self.assertEqual(7, result.edges().size()) - - # Arc path - path = Workplane("XZ").threePointArc((1.0, 1.5),(0.0, 1.0)) - - # Test defaults - result = Workplane("XY").circle(0.1).sweep(path) - self.assertEqual(3, result.faces().size()) - self.assertEqual(3, result.edges().size()) - - def testTwistExtrude(self): - """ - Tests extrusion while twisting through an angle. - """ - profile = Workplane('XY').rect(10, 10) - r = profile.twistExtrude(10, 45, False) - - self.assertEqual(6, r.faces().size()) - - def testTwistExtrudeCombine(self): - """ - Tests extrusion while twisting through an angle, combining with other solids. - """ - profile = Workplane('XY').rect(10, 10) - r = profile.twistExtrude(10, 45) - - self.assertEqual(6, r.faces().size()) - - def testRectArray(self): - NUMX=3 - NUMY=3 - s = Workplane("XY").box(40,40,5,centered=(True,True,True)).faces(">Z").workplane().rarray(8.0,8.0,NUMX,NUMY,True).circle(2.0).extrude(2.0) - #s = Workplane("XY").box(40,40,5,centered=(True,True,True)).faces(">Z").workplane().circle(2.0).extrude(2.0) - self.saveModel(s) - self.assertEqual(6+NUMX*NUMY*2,s.faces().size()) #6 faces for the box, 2 faces for each cylinder - - def testNestedCircle(self): - s = Workplane("XY").box(40,40,5).pushPoints([(10,0),(0,10)]).circle(4).circle(2).extrude(4) - self.saveModel(s) - self.assertEqual(14,s.faces().size() ) - - def testLegoBrick(self): - #test making a simple lego brick - #which of the below - - #inputs - lbumps = 8 - wbumps = 2 - - #lego brick constants - P = 8.0 #nominal pitch - c = 0.1 #clearance on each brick side - H = 1.2 * P #nominal height of a brick - bumpDiam = 4.8 #the standard bump diameter - t = ( P - ( 2*c) - bumpDiam ) / 2.0 # the nominal thickness of the walls, normally 1.5 - - postDiam = P - t #works out to 6.5 - total_length = lbumps*P - 2.0*c - total_width = wbumps*P - 2.0*c - - #build the brick - s = Workplane("XY").box(total_length,total_width,H) #make the base - s = s.faces("Z").workplane().rarray(P,P,lbumps,wbumps,True).circle(bumpDiam/2.0).extrude(1.8) # make the bumps on the top - - #add posts on the bottom. posts are different diameter depending on geometry - #solid studs for 1 bump, tubes for multiple, none for 1x1 - tmp = s.faces(" 1 and wbumps > 1: - tmp = tmp.rarray(P,P,lbumps - 1,wbumps - 1,center=True).circle(postDiam/2.0).circle(bumpDiam/2.0).extrude(H-t) - elif lbumps > 1: - tmp = tmp.rarray(P,P,lbumps - 1,1,center=True).circle(t).extrude(H-t) - elif wbumps > 1: - tmp = tmp.rarray(P,P,1,wbumps -1,center=True).circle(t).extrude(H-t) - - self.saveModel(s) - - def testAngledHoles(self): - s = Workplane("front").box(4.0,4.0,0.25).faces(">Z").workplane().transformed(offset=Vector(0,-1.5,1.0),rotate=Vector(60,0,0))\ - .rect(1.5,1.5,forConstruction=True).vertices().hole(0.25) - self.saveModel(s) - self.assertEqual(10,s.faces().size()) - - def testTranslateSolid(self): - c = CQ(makeUnitCube()) - self.assertAlmostEqual(0.0,c.faces("Z').workplane().circle(0.125).extrude(0.5,True) #make a boss, not updating the original - self.assertEqual(8,r.faces().size()) #just the boss faces - self.assertEqual(8,c.faces().size()) #original is modified too - - def testSolidReferencesCombineTrue(self): - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).extrude(0.5) - self.assertEqual(6,r.faces().size() ) #the result of course has 6 faces - self.assertEqual(0,s.faces().size() ) # the original workplane does not, because it did not have a solid initially - - t = r.faces(">Z").workplane().rect(0.25,0.25).extrude(0.5,True) - self.assertEqual(11,t.faces().size()) #of course the result has 11 faces - self.assertEqual(11,r.faces().size()) #r does as well. the context solid for r was updated since combine was true - self.saveModel(r) - - def testSolidReferenceCombineFalse(self): - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).extrude(0.5) - self.assertEqual(6,r.faces().size() ) #the result of course has 6 faces - self.assertEqual(0,s.faces().size() ) # the original workplane does not, because it did not have a solid initially - - t = r.faces(">Z").workplane().rect(0.25,0.25).extrude(0.5,False) - self.assertEqual(6,t.faces().size()) #result has 6 faces, becuase it was not combined with the original - self.assertEqual(6,r.faces().size()) #original is unmodified as well - #subseuent opertions use that context solid afterwards - - def testSimpleWorkplane(self): - """ - A simple square part with a hole in it - """ - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).extrude(0.5)\ - .faces(">Z").workplane()\ - .circle(0.25).cutBlind(-1.0) - - self.saveModel(r) - self.assertEqual(7,r.faces().size() ) - - def testMultiFaceWorkplane(self): - """ - Test Creation of workplane from multiple co-planar face - selection. - """ - s = Workplane('XY').box(1,1,1).faces('>Z').rect(1,0.5).cutBlind(-0.2) - - w = s.faces('>Z').workplane() - o = w.objects[0] # origin of the workplane - self.assertAlmostEqual(o.x, 0., 3) - self.assertAlmostEqual(o.y, 0., 3) - self.assertAlmostEqual(o.z, 0.5, 3) - - def testTriangularPrism(self): - s = Workplane("XY").lineTo(1,0).lineTo(1,1).close().extrude(0.2) - self.saveModel(s) - - def testMultiWireWorkplane(self): - """ - A simple square part with a hole in it-- but this time done as a single extrusion - with two wires, as opposed to s cut - """ - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).circle(0.25).extrude(0.5) - - self.saveModel(r) - self.assertEqual(7,r.faces().size() ) - - def testConstructionWire(self): - """ - Tests a wire with several holes, that are based on the vertices of a square - also tests using a workplane plane other than XY - """ - s = Workplane(Plane.YZ()) - r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices().circle(0.125).extrude(0.5) - self.saveModel(r) - self.assertEqual(10,r.faces().size() ) # 10 faces-- 6 plus 4 holes, the vertices of the second rect. - - def testTwoWorkplanes(self): - """ - Tests a model that uses more than one workplane - """ - #base block - s = Workplane(Plane.XY()) - - #TODO: this syntax is nice, but the iteration might not be worth - #the complexity. - #the simpler and slightly longer version would be: - # r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices() - # for c in r.all(): - # c.circle(0.125).extrude(0.5,True) - r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices().circle(0.125).extrude(0.5) - - #side hole, blind deep 1.9 - t = r.faces(">Y").workplane().circle(0.125).cutBlind(-1.9) - self.saveModel(t) - self.assertEqual(12,t.faces().size() ) - - def testCut(self): - """ - Tests the cut function by itself to catch the case where a Solid object is passed. - """ - s = Workplane(Plane.XY()) - currentS = s.rect(2.0,2.0).extrude(0.5) - toCut = s.rect(1.0,1.0).extrude(0.5) - - currentS.cut(toCut.val()) - - self.assertEqual(10,currentS.faces().size()) - - def testBoundingBox(self): - """ - Tests the boudingbox center of a model - """ - result0 = (Workplane("XY") - .moveTo(10,0) - .lineTo(5,0) - .threePointArc((3.9393,0.4393),(3.5,1.5)) - .threePointArc((3.0607,2.5607),(2,3)) - .lineTo(1.5,3) - .threePointArc((0.4393,3.4393),(0,4.5)) - .lineTo(0,13.5) - .threePointArc((0.4393,14.5607),(1.5,15)) - .lineTo(28,15) - .lineTo(28,13.5) - .lineTo(24,13.5) - .lineTo(24,11.5) - .lineTo(27,11.5) - .lineTo(27,10) - .lineTo(22,10) - .lineTo(22,13.2) - .lineTo(14.5,13.2) - .lineTo(14.5,10) - .lineTo(12.5,10 ) - .lineTo(12.5,13.2) - .lineTo(5.5,13.2) - .lineTo(5.5,2) - .threePointArc((5.793,1.293),(6.5,1)) - .lineTo(10,1) - .close()) - result = result0.extrude(100) - bb_center = result.val().BoundingBox().center - self.saveModel(result) - self.assertAlmostEqual(14.0, bb_center.x, 3) - self.assertAlmostEqual(7.5, bb_center.y, 3) - self.assertAlmostEqual(50.0, bb_center.z, 3) - - def testCutThroughAll(self): - """ - Tests a model that uses more than one workplane - """ - #base block - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices().circle(0.125).extrude(0.5) - - #side hole, thru all - t = r.faces(">Y").workplane().circle(0.125).cutThruAll() - self.saveModel(t) - self.assertEqual(11,t.faces().size() ) - - def testCutToFaceOffsetNOTIMPLEMENTEDYET(self): - """ - Tests cutting up to a given face, or an offset from a face - """ - #base block - s = Workplane(Plane.XY()) - r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices().circle(0.125).extrude(0.5) - - #side hole, up to 0.1 from the last face - try: - t = r.faces(">Y").workplane().circle(0.125).cutToOffsetFromFace(r.faces().mminDist(Dir.Y),0.1) - self.assertEqual(10,t.faces().size() ) #should end up being a blind hole - t.first().val().exportStep('c:/temp/testCutToFace.STEP') - except: - pass - #Not Implemented Yet - - def testWorkplaneOnExistingSolid(self): - "Tests extruding on an existing solid" - c = CQ( makeUnitCube()).faces(">Z").workplane().circle(0.25).circle(0.125).extrude(0.25) - self.saveModel(c) - self.assertEqual(10,c.faces().size() ) - - - def testWorkplaneCenterMove(self): - #this workplane is centered at x=0.5,y=0.5, the center of the upper face - s = Workplane("XY").box(1,1,1).faces(">Z").workplane().center(-0.5,-0.5) # move the center to the corner - - t = s.circle(0.25).extrude(0.2) # make a boss - self.assertEqual(9,t.faces().size() ) - self.saveModel(t) - - - def testBasicLines(self): - "Make a triangluar boss" - global OUTDIR - s = Workplane(Plane.XY()) - - #TODO: extrude() should imply wire() if not done already - #most users dont understand what a wire is, they are just drawing - - r = s.lineTo(1.0,0).lineTo(0,1.0).close().wire().extrude(0.25) - r.val().exportStep(os.path.join(OUTDIR, 'testBasicLinesStep1.STEP')) - - self.assertEqual(0,s.faces().size()) #no faces on the original workplane - self.assertEqual(5,r.faces().size() ) # 5 faces on newly created object - - #now add a circle through a side face - r.faces("+XY").workplane().circle(0.08).cutThruAll() - self.assertEqual(6,r.faces().size()) - r.val().exportStep(os.path.join(OUTDIR, 'testBasicLinesXY.STEP')) - - #now add a circle through a top - r.faces("+Z").workplane().circle(0.08).cutThruAll() - self.assertEqual(9,r.faces().size()) - r.val().exportStep(os.path.join(OUTDIR, 'testBasicLinesZ.STEP')) - - self.saveModel(r) - - def test2DDrawing(self): - """ - Draw things like 2D lines and arcs, should be expanded later to include all 2D constructs - """ - s = Workplane(Plane.XY()) - r = s.lineTo(1.0, 0.0) \ - .lineTo(1.0, 1.0) \ - .threePointArc((1.0, 1.5), (0.0, 1.0)) \ - .lineTo(0.0, 0.0) \ - .moveTo(1.0, 0.0) \ - .lineTo(2.0, 0.0) \ - .lineTo(2.0, 2.0) \ - .threePointArc((2.0, 2.5), (0.0, 2.0)) \ - .lineTo(-2.0, 2.0) \ - .lineTo(-2.0, 0.0) \ - .close() - - self.assertEqual(1, r.wires().size()) - - # Test the *LineTo functions - s = Workplane(Plane.XY()) - r = s.hLineTo(1.0).vLineTo(1.0).hLineTo(0.0).close() - - self.assertEqual(1, r.wire().size()) - self.assertEqual(4, r.edges().size()) - - # Test the *Line functions - s = Workplane(Plane.XY()) - r = s.hLine(1.0).vLine(1.0).hLine(-1.0).close() - - self.assertEqual(1, r.wire().size()) - self.assertEqual(4, r.edges().size()) - - # Test the move function - s = Workplane(Plane.XY()) - r = s.move(1.0, 1.0).hLine(1.0).vLine(1.0).hLine(-1.0).close() - - self.assertEqual(1, r.wire().size()) - self.assertEqual(4, r.edges().size()) - self.assertEqual((1.0, 1.0), - (r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0)))\ - .first().val().X, - r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0)))\ - .first().val().Y)) - - def testLargestDimension(self): - """ - Tests the largestDimension function when no solids are on the stack and when there are - """ - r = Workplane('XY').box(1, 1, 1) - dim = r.largestDimension() - - self.assertAlmostEqual(8.66025403784, dim) - - r = Workplane('XY') - dim = r.largestDimension() - - self.assertEqual(-1, dim) - - def testOccBottle(self): - """ - Make the OCC bottle example. - """ - - L = 20.0 - w = 6.0 - t = 3.0 - - s = Workplane(Plane.XY()) - #draw half the profile of the bottle - p = s.center(-L/2.0,0).vLine(w/2.0).threePointArc((L/2.0, w/2.0 + t),(L,w/2.0)).vLine(-w/2.0).mirrorX()\ - .extrude(30.0,True) - - #make the neck - p.faces(">Z").workplane().circle(3.0).extrude(2.0,True) #.edges().fillet(0.05) - - #make a shell - p.faces(">Z").shell(0.3) - self.saveModel(p) - - - def testSplineShape(self): - """ - Tests making a shape with an edge that is a spline - """ - s = Workplane(Plane.XY()) - sPnts = [ - (2.75,1.5), - (2.5,1.75), - (2.0,1.5), - (1.5,1.0), - (1.0,1.25), - (0.5,1.0), - (0,1.0) - ] - r = s.lineTo(3.0,0).lineTo(3.0,1.0).spline(sPnts).close() - r = r.extrude(0.5) - self.saveModel(r) - - def testSimpleMirror(self): - """ - Tests a simple mirroring operation - """ - s = Workplane("XY").lineTo(2, 2).threePointArc((3, 1), (2, 0)) \ - .mirrorX().extrude(0.25) - self.assertEquals(6, s.faces().size()) - self.saveModel(s) - - def testUnorderedMirror(self): - """ - Tests whether or not a wire can be mirrored if its mirror won't connect to it - """ - r = 20 - s = 7 - t = 1.5 - - points = [ - (0, t/2), - (r/2-1.5*t, r/2-t), - (s/2, r/2-t), - (s/2, r/2), - (r/2, r/2), - (r/2, s/2), - (r/2-t, s/2), - (r/2-t, r/2-1.5*t), - (t/2, 0) - ] - - r = Workplane("XY").polyline(points).mirrorX() - - self.assertEquals(1, r.wires().size()) - self.assertEquals(18, r.edges().size()) - - # def testChainedMirror(self): - # """ - # Tests whether or not calling mirrorX().mirrorY() works correctly - # """ - # r = 20 - # s = 7 - # t = 1.5 - # - # points = [ - # (0, t/2), - # (r/2-1.5*t, r/2-t), - # (s/2, r/2-t), - # (s/2, r/2), - # (r/2, r/2), - # (r/2, s/2), - # (r/2-t, s/2), - # (r/2-t, r/2-1.5*t), - # (t/2, 0) - # ] - # - # r = Workplane("XY").polyline(points).mirrorX().mirrorY() - # - # self.assertEquals(1, r.wires().size()) - # self.assertEquals(32, r.edges().size()) - - #TODO: Re-work testIbeam test below now that chaining works - #TODO: Add toLocalCoords and toWorldCoords tests - - def testIbeam(self): - """ - Make an ibeam. demonstrates fancy mirroring - """ - s = Workplane(Plane.XY()) - L = 100.0 - H = 20.0 - W = 20.0 - - t = 1.0 - #TODO: for some reason doing 1/4 of the profile and mirroring twice ( .mirrorX().mirrorY() ) - #did not work, due to a bug in freecad-- it was losing edges when creating a composite wire. - #i just side-stepped it for now - - pts = [ - (0, H/2.0), - (W/2.0, H/2.0), - (W/2.0, (H/2.0 - t)), - (t/2.0, (H/2.0-t)), - (t/2.0, (t - H/2.0)), - (W/2.0, (t - H/2.0)), - (W/2.0, H / -2.0), - (0, H/-2.0) - ] - r = s.polyline(pts).mirrorY() #these other forms also work - res = r.extrude(L) - self.saveModel(res) - - def testCone(self): - """ - Tests that a simple cone works - """ - s = Solid.makeCone(0, 1.0, 2.0) - t = CQ(s) - self.saveModel(t) - self.assertEqual(2, t.faces().size()) - - def testFillet(self): - """ - Tests filleting edges on a solid - """ - c = CQ( makeUnitCube()).faces(">Z").workplane().circle(0.25).extrude(0.25,True).edges("|Z").fillet(0.2) - self.saveModel(c) - self.assertEqual(12,c.faces().size() ) - - def testChamfer(self): - """ - Test chamfer API with a box shape - """ - cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1) - self.saveModel(cube) - self.assertEqual(10, cube.faces().size()) - - def testChamferAsymmetrical(self): - """ - Test chamfer API with a box shape for asymmetrical lengths - """ - cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1, 0.2) - self.saveModel(cube) - self.assertEqual(10, cube.faces().size()) - - # test if edge lengths are different - edge = cube.edges(">Z").vals()[0] - self.assertAlmostEqual(0.6, edge.Length(), 3) - edge = cube.edges("|Z").vals()[0] - self.assertAlmostEqual(0.9, edge.Length(), 3) - - def testChamferCylinder(self): - """ - Test chamfer API with a cylinder shape - """ - cylinder = Workplane("XY").circle(1).extrude(1).faces(">Z").chamfer(0.1) - self.saveModel(cylinder) - self.assertEqual(4, cylinder.faces().size()) - - def testCounterBores(self): - """ - Tests making a set of counterbored holes in a face - """ - c = CQ(makeCube(3.0)) - pnts = [ - (-1.0, -1.0), (0.0, 0.0), (1.0, 1.0) - ] - c.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25, 0.75) - self.assertEquals(18, c.faces().size()) - self.saveModel(c) - - # Tests the case where the depth of the cboreHole is not specified - c2 = CQ(makeCube(3.0)) - pnts = [ - (-1.0, -1.0), (0.0, 0.0), (1.0, 1.0) - ] - c2.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25) - self.assertEquals(15, c2.faces().size()) - - def testCounterSinks(self): - """ - Tests countersinks - """ - s = Workplane(Plane.XY()) - result = s.rect(2.0, 4.0).extrude(0.5).faces(">Z").workplane()\ - .rect(1.5, 3.5, forConstruction=True).vertices().cskHole(0.125, 0.25, 82, depth=None) - self.saveModel(result) - - def testSplitKeepingHalf(self): - """ - Tests splitting a solid - """ - - #drill a hole in the side - c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() - - self.assertEqual(7, c.faces().size()) - - #now cut it in half sideways - c.faces(">Y").workplane(-0.5).split(keepTop=True) - self.saveModel(c) - self.assertEqual(8, c.faces().size()) - - def testSplitKeepingBoth(self): - """ - Tests splitting a solid - """ - - #drill a hole in the side - c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() - self.assertEqual(7, c.faces().size()) - - #now cut it in half sideways - result = c.faces(">Y").workplane(-0.5).split(keepTop=True, keepBottom=True) - - #stack will have both halves, original will be unchanged - self.assertEqual(2, result.solids().size()) # two solids are on the stack, eac - self.assertEqual(8, result.solids().item(0).faces().size()) - self.assertEqual(8, result.solids().item(1).faces().size()) - - def testSplitKeepingBottom(self): - """ - Tests splitting a solid improperly - """ - # Drill a hole in the side - c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() - self.assertEqual(7, c.faces().size()) - - # Now cut it in half sideways - result = c.faces(">Y").workplane(-0.5).split(keepTop=False, keepBottom=True) - - #stack will have both halves, original will be unchanged - self.assertEqual(1, result.solids().size()) # one solid is on the stack - self.assertEqual(8, result.solids().item(0).faces().size()) - - def testBoxDefaults(self): - """ - Tests creating a single box - """ - s = Workplane("XY").box(2, 3, 4) - self.assertEquals(1, s.solids().size()) - self.saveModel(s) - - def testSimpleShell(self): - """ - Create s simple box - """ - s = Workplane("XY").box(2, 2, 2).faces("+Z").shell(0.05) - self.saveModel(s) - self.assertEquals(23, s.faces().size()) - - - def testOpenCornerShell(self): - s = Workplane("XY").box(1, 1, 1) - s1 = s.faces("+Z") - s1.add(s.faces("+Y")).add(s.faces("+X")) - self.saveModel(s1.shell(0.2)) - - # Tests the list option variation of add - s1 = s.faces("+Z") - s1.add(s.faces("+Y")).add([s.faces("+X")]) - - # Tests the raw object option variation of add - s1 = s.faces("+Z") - s1.add(s.faces("+Y")).add(s.faces("+X").val().wrapped) - - def testTopFaceFillet(self): - s = Workplane("XY").box(1, 1, 1).faces("+Z").edges().fillet(0.1) - self.assertEquals(s.faces().size(), 10) - self.saveModel(s) - - def testBoxPointList(self): - """ - Tests creating an array of boxes - """ - s = Workplane("XY").rect(4.0, 4.0, forConstruction=True).vertices().box(0.25, 0.25, 0.25, combine=True) - #1 object, 4 solids because the object is a compound - self.assertEquals(1, s.solids().size()) - self.assertEquals(1, s.size()) - self.saveModel(s) - - s = Workplane("XY").rect(4.0, 4.0, forConstruction=True).vertices().box(0.25, 0.25, 0.25, combine=False) - #4 objects, 4 solids, because each is a separate solid - self.assertEquals(4, s.size()) - self.assertEquals(4, s.solids().size()) - - def testBoxCombine(self): - s = Workplane("XY").box(4, 4, 0.5).faces(">Z").workplane().rect(3, 3, forConstruction=True).vertices().box(0.25, 0.25, 0.25, combine=True) - - self.saveModel(s) - self.assertEquals(1, s.solids().size()) # we should have one big solid - self.assertEquals(26, s.faces().size()) # should have 26 faces. 6 for the box, and 4x5 for the smaller cubes - - def testSphereDefaults(self): - s = Workplane("XY").sphere(10) - #self.saveModel(s) # Until FreeCAD fixes their sphere operation - self.assertEquals(1, s.solids().size()) - self.assertEquals(1, s.faces().size()) - - def testSphereCustom(self): - s = Workplane("XY").sphere(10, angle1=0, angle2=90, angle3=360, centered=(False, False, False)) - self.saveModel(s) - self.assertEquals(1, s.solids().size()) - self.assertEquals(2, s.faces().size()) - - def testSpherePointList(self): - s = Workplane("XY").rect(4.0, 4.0, forConstruction=True).vertices().sphere(0.25, combine=False) - #self.saveModel(s) # Until FreeCAD fixes their sphere operation - self.assertEquals(4, s.solids().size()) - self.assertEquals(4, s.faces().size()) - - def testSphereCombine(self): - s = Workplane("XY").rect(4.0, 4.0, forConstruction=True).vertices().sphere(0.25, combine=True) - #self.saveModel(s) # Until FreeCAD fixes their sphere operation - self.assertEquals(1, s.solids().size()) - self.assertEquals(4, s.faces().size()) - - def testQuickStartXY(self): - s = Workplane(Plane.XY()).box(2, 4, 0.5).faces(">Z").workplane().rect(1.5, 3.5, forConstruction=True)\ - .vertices().cskHole(0.125, 0.25, 82, depth=None) - self.assertEquals(1, s.solids().size()) - self.assertEquals(14, s.faces().size()) - self.saveModel(s) - - def testQuickStartYZ(self): - s = Workplane(Plane.YZ()).box(2, 4, 0.5).faces(">X").workplane().rect(1.5, 3.5, forConstruction=True)\ - .vertices().cskHole(0.125, 0.25, 82, depth=None) - self.assertEquals(1, s.solids().size()) - self.assertEquals(14, s.faces().size()) - self.saveModel(s) - - def testQuickStartXZ(self): - s = Workplane(Plane.XZ()).box(2, 4, 0.5).faces(">Y").workplane().rect(1.5, 3.5, forConstruction=True)\ - .vertices().cskHole(0.125, 0.25, 82, depth=None) - self.assertEquals(1, s.solids().size()) - self.assertEquals(14, s.faces().size()) - self.saveModel(s) - - def testDoubleTwistedLoft(self): - s = Workplane("XY").polygon(8, 20.0).workplane(offset=4.0).transformed(rotate=Vector(0, 0, 15.0)).polygon(8, 20).loft() - s2 = Workplane("XY").polygon(8, 20.0).workplane(offset=-4.0).transformed(rotate=Vector(0, 0, 15.0)).polygon(8, 20).loft() - #self.assertEquals(10,s.faces().size()) - #self.assertEquals(1,s.solids().size()) - s3 = s.combineSolids(s2) - self.saveModel(s3) - - def testTwistedLoft(self): - s = Workplane("XY").polygon(8,20.0).workplane(offset=4.0).transformed(rotate=Vector(0,0,15.0)).polygon(8,20).loft() - self.assertEquals(10,s.faces().size()) - self.assertEquals(1,s.solids().size()) - self.saveModel(s) - - def testUnions(self): - #duplicates a memory problem of some kind reported when combining lots of objects - s = Workplane("XY").rect(0.5,0.5).extrude(5.0) - o = [] - beginTime = time.time() - for i in range(15): - t = Workplane("XY").center(10.0*i,0).rect(0.5,0.5).extrude(5.0) - o.append(t) - - #union stuff - for oo in o: - s = s.union(oo) - print "Total time %0.3f" % (time.time() - beginTime) - - #Test unioning a Solid object - s = Workplane(Plane.XY()) - currentS = s.rect(2.0,2.0).extrude(0.5) - toUnion = s.rect(1.0,1.0).extrude(1.0) - - currentS.union(toUnion.val(), combine=False) - - #TODO: When unioning and combining is figured out, uncomment the following assert - #self.assertEqual(10,currentS.faces().size()) - - def testCombine(self): - s = Workplane(Plane.XY()) - objects1 = s.rect(2.0,2.0).extrude(0.5).faces('>Z').rect(1.0,1.0).extrude(0.5) - - objects1.combine() - - self.assertEqual(11, objects1.faces().size()) - - - def testCombineSolidsInLoop(self): - #duplicates a memory problem of some kind reported when combining lots of objects - s = Workplane("XY").rect(0.5,0.5).extrude(5.0) - o = [] - beginTime = time.time() - for i in range(15): - t = Workplane("XY").center(10.0*i,0).rect(0.5,0.5).extrude(5.0) - o.append(t) - - #append the 'good way' - for oo in o: - s.add(oo) - s = s.combineSolids() - - print "Total time %0.3f" % (time.time() - beginTime) - - self.saveModel(s) - - def testClean(self): - """ - Tests the `clean()` method which is called automatically. - """ - - # make a cube with a splitter edge on one of the faces - # autosimplify should remove the splitter - s = Workplane("XY").moveTo(0,0).line(5,0).line(5,0).line(0,10).\ - line(-10,0).close().extrude(10) - - self.assertEqual(6, s.faces().size()) - - # test removal of splitter caused by union operation - s = Workplane("XY").box(10,10,10).union(Workplane("XY").box(20,10,10)) - - self.assertEqual(6, s.faces().size()) - - # test removal of splitter caused by extrude+combine operation - s = Workplane("XY").box(10,10,10).faces(">Y").\ - workplane().rect(5,10,5).extrude(20) - - self.assertEqual(10, s.faces().size()) - - # test removal of splitter caused by double hole operation - s = Workplane("XY").box(10,10,10).faces(">Z").workplane().\ - hole(3,5).faces(">Z").workplane().hole(3,10) - - self.assertEqual(7, s.faces().size()) - - # test removal of splitter caused by cutThruAll - s = Workplane("XY").box(10,10,10).faces(">Y").workplane().\ - rect(10,5).cutBlind(-5).faces(">Z").workplane().\ - center(0,2.5).rect(5,5).cutThruAll() - - self.assertEqual(18, s.faces().size()) - - # test removal of splitter with box - s = Workplane("XY").box(5,5,5).box(10,5,2) - - self.assertEqual(14, s.faces().size()) - - def testNoClean(self): - """ - Test the case when clean is disabled. - """ - # test disabling autoSimplify - s = Workplane("XY").moveTo(0,0).line(5,0).line(5,0).line(0,10).\ - line(-10,0).close().extrude(10, clean=False) - self.assertEqual(7, s.faces().size()) - - s = Workplane("XY").box(10,10,10).\ - union(Workplane("XY").box(20,10,10), clean=False) - self.assertEqual(14, s.faces().size()) - - s = Workplane("XY").box(10,10,10).faces(">Y").\ - workplane().rect(5,10,5).extrude(20, clean=False) - - self.assertEqual(12, s.faces().size()) - - def testExplicitClean(self): - """ - Test running of `clean()` method explicitly. - """ - s = Workplane("XY").moveTo(0,0).line(5,0).line(5,0).line(0,10).\ - line(-10,0).close().extrude(10,clean=False).clean() - self.assertEqual(6, s.faces().size()) - - def testCup(self): - - """ - UOM = "mm" - - # - # PARAMETERS and PRESETS - # These parameters can be manipulated by end users - # - bottomDiameter = FloatParam(min=10.0,presets={'default':50.0,'tumbler':50.0,'shot':35.0,'tea':50.0,'saucer':100.0},group="Basics", desc="Bottom diameter") - topDiameter = FloatParam(min=10.0,presets={'default':85.0,'tumbler':85.0,'shot':50.0,'tea':51.0,'saucer':400.0 },group="Basics", desc="Top diameter") - thickness = FloatParam(min=0.1,presets={'default':2.0,'tumbler':2.0,'shot':2.66,'tea':2.0,'saucer':2.0},group="Basics", desc="Thickness") - height = FloatParam(min=1.0,presets={'default':80.0,'tumbler':80.0,'shot':59.0,'tea':125.0,'saucer':40.0},group="Basics", desc="Overall height") - lipradius = FloatParam(min=1.0,presets={'default':1.0,'tumbler':1.0,'shot':0.8,'tea':1.0,'saucer':1.0},group="Basics", desc="Lip Radius") - bottomThickness = FloatParam(min=1.0,presets={'default':5.0,'tumbler':5.0,'shot':10.0,'tea':10.0,'saucer':5.0},group="Basics", desc="BottomThickness") - - # - # Your build method. It must return a solid object - # - def build(): - br = bottomDiameter.value / 2.0 - tr = topDiameter.value / 2.0 - t = thickness.value - s1 = Workplane("XY").circle(br).workplane(offset=height.value).circle(tr).loft() - s2 = Workplane("XY").workplane(offset=bottomThickness.value).circle(br - t ).workplane(offset=height.value - t ).circle(tr - t).loft() - - cup = s1.cut(s2) - cup.faces(">Z").edges().fillet(lipradius.value) - return cup - """ - - #for some reason shell doesnt work on this simple shape. how disappointing! - td = 50.0 - bd = 20.0 - h = 10.0 - t = 1.0 - s1 = Workplane("XY").circle(bd).workplane(offset=h).circle(td).loft() - s2 = Workplane("XY").workplane(offset=t).circle(bd-(2.0*t)).workplane(offset=(h-t)).circle(td-(2.0*t)).loft() - s3 = s1.cut(s2) - self.saveModel(s3) - - - def testEnclosure(self): - """ - Builds an electronics enclosure - Original FreeCAD script: 81 source statements ,not including variables - This script: 34 - """ - - #parameter definitions - p_outerWidth = 100.0 #Outer width of box enclosure - p_outerLength = 150.0 #Outer length of box enclosure - p_outerHeight = 50.0 #Outer height of box enclosure - - p_thickness = 3.0 #Thickness of the box walls - p_sideRadius = 10.0 #Radius for the curves around the sides of the bo - p_topAndBottomRadius = 2.0 #Radius for the curves on the top and bottom edges of the box - - p_screwpostInset = 12.0 #How far in from the edges the screwposts should be place. - p_screwpostID = 4.0 #nner Diameter of the screwpost holes, should be roughly screw diameter not including threads - p_screwpostOD = 10.0 #Outer Diameter of the screwposts.\nDetermines overall thickness of the posts - - p_boreDiameter = 8.0 #Diameter of the counterbore hole, if any - p_boreDepth = 1.0 #Depth of the counterbore hole, if - p_countersinkDiameter = 0.0 #Outer diameter of countersink. Should roughly match the outer diameter of the screw head - p_countersinkAngle = 90.0 #Countersink angle (complete angle between opposite sides, not from center to one side) - p_flipLid = True #Whether to place the lid with the top facing down or not. - p_lipHeight = 1.0 #Height of lip on the underside of the lid.\nSits inside the box body for a snug fit. - - #outer shell - oshell = Workplane("XY").rect(p_outerWidth,p_outerLength).extrude(p_outerHeight + p_lipHeight) - - #weird geometry happens if we make the fillets in the wrong order - if p_sideRadius > p_topAndBottomRadius: - oshell.edges("|Z").fillet(p_sideRadius) - oshell.edges("#Z").fillet(p_topAndBottomRadius) - else: - oshell.edges("#Z").fillet(p_topAndBottomRadius) - oshell.edges("|Z").fillet(p_sideRadius) - - #inner shell - ishell = oshell.faces("Z").workplane(-p_thickness)\ - .rect(POSTWIDTH,POSTLENGTH,forConstruction=True)\ - .vertices() - - for v in postCenters.all(): - v.circle(p_screwpostOD/2.0).circle(p_screwpostID/2.0)\ - .extrude((-1.0)*(p_outerHeight + p_lipHeight -p_thickness ),True) - - #split lid into top and bottom parts - (lid,bottom) = box.faces(">Z").workplane(-p_thickness -p_lipHeight ).split(keepTop=True,keepBottom=True).all() #splits into two solids - - #translate the lid, and subtract the bottom from it to produce the lid inset - lowerLid = lid.translate((0,0,-p_lipHeight)) - cutlip = lowerLid.cut(bottom).translate((p_outerWidth + p_thickness ,0,p_thickness - p_outerHeight + p_lipHeight)) - - #compute centers for counterbore/countersink or counterbore - topOfLidCenters = cutlip.faces(">Z").workplane().rect(POSTWIDTH,POSTLENGTH,forConstruction=True).vertices() - - #add holes of the desired type - if p_boreDiameter > 0 and p_boreDepth > 0: - topOfLid = topOfLidCenters.cboreHole(p_screwpostID,p_boreDiameter,p_boreDepth,(2.0)*p_thickness) - elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: - topOfLid = topOfLidCenters.cskHole(p_screwpostID,p_countersinkDiameter,p_countersinkAngle,(2.0)*p_thickness) - else: - topOfLid= topOfLidCenters.hole(p_screwpostID,(2.0)*p_thickness) - - #flip lid upside down if desired - if p_flipLid: - topOfLid.rotateAboutCenter((1,0,0),180) - - #return the combined result - result =topOfLid.union(bottom) - - self.saveModel(result) - - def testExtrude(self): - """ - Test symmetric extrude - """ - r = 1. - h = 1. - decimal_places = 9. - - #extrude symmetrically - s = Workplane("XY").circle(r).extrude(h,both=True) - - top_face = s.faces(">Z") - bottom_face = s.faces(" -1 ) - return result - - def testSTL(self): - self._exportBox(exporters.ExportTypes.STL,['facet normal']) - - def testSVG(self): - self._exportBox(exporters.ExportTypes.SVG,['']) - - def testSTEP(self): - self._exportBox(exporters.ExportTypes.STEP,['FILE_SCHEMA']) - - def testTJS(self): - self._exportBox(exporters.ExportTypes.TJS,['vertices','formatVersion','faces']) diff --git a/Libs/cadquery-lib/tests/TestImporters.py b/Libs/cadquery-lib/tests/TestImporters.py deleted file mode 100644 index edee5d5..0000000 --- a/Libs/cadquery-lib/tests/TestImporters.py +++ /dev/null @@ -1,54 +0,0 @@ -""" - Tests file importers such as STEP -""" -#core modules -import StringIO - -from cadquery import * -from cadquery import exporters -from cadquery import importers -from tests import BaseTest - -#where unit test output will be saved -import sys -if sys.platform.startswith("win"): - OUTDIR = "c:/temp" -else: - OUTDIR = "/tmp" - - -class TestImporters(BaseTest): - def importBox(self, importType, fileName): - """ - Exports a simple box to a STEP file and then imports it again - :param importType: The type of file we're importing (STEP, STL, etc) - :param fileName: The path and name of the file to write to - """ - #We're importing a STEP file - if importType == importers.ImportTypes.STEP: - #We first need to build a simple shape to export - shape = Workplane("XY").box(1, 2, 3).val() - - #Export the shape to a temporary file - shape.exportStep(fileName) - - # Reimport the shape from the new STEP file - importedShape = importers.importShape(importType,fileName) - - #Check to make sure we got a solid back - self.assertTrue(importedShape.val().ShapeType() == "Solid") - - #Check the number of faces and vertices per face to make sure we have a box shape - self.assertTrue(importedShape.faces("+X").size() == 1 and importedShape.faces("+X").vertices().size() == 4) - self.assertTrue(importedShape.faces("+Y").size() == 1 and importedShape.faces("+Y").vertices().size() == 4) - self.assertTrue(importedShape.faces("+Z").size() == 1 and importedShape.faces("+Z").vertices().size() == 4) - - def testSTEP(self): - """ - Tests STEP file import - """ - self.importBox(importers.ImportTypes.STEP, OUTDIR + "/tempSTEP.step") - -if __name__ == '__main__': - import unittest - unittest.main() diff --git a/Libs/cadquery-lib/tests/TestWorkplanes.py b/Libs/cadquery-lib/tests/TestWorkplanes.py deleted file mode 100644 index 838b953..0000000 --- a/Libs/cadquery-lib/tests/TestWorkplanes.py +++ /dev/null @@ -1,125 +0,0 @@ -""" - Tests basic workplane functionality -""" -#core modules - -#my modules -from cadquery import * -from tests import BaseTest,toTuple - -xAxis_ = Vector(1, 0, 0) -yAxis_ = Vector(0, 1, 0) -zAxis_ = Vector(0, 0, 1) -xInvAxis_ = Vector(-1, 0, 0) -yInvAxis_ = Vector(0, -1, 0) -zInvAxis_ = Vector(0, 0, -1) - -class TestWorkplanes(BaseTest): - - def testYZPlaneOrigins(self): - #xy plane-- with origin at x=0.25 - base = Vector(0.25,0,0) - p = Plane(base, Vector(0,1,0), Vector(1,0,0)) - - #origin is always (0,0,0) in local coordinates - self.assertTupleAlmostEquals((0,0,0), p.toLocalCoords(p.origin).toTuple() ,2 ) - - #(0,0,0) is always the original base in global coordinates - self.assertTupleAlmostEquals(base.toTuple(), p.toWorldCoords((0,0)).toTuple() ,2 ) - - def testXYPlaneOrigins(self): - base = Vector(0,0,0.25) - p = Plane(base, Vector(1,0,0), Vector(0,0,1)) - - #origin is always (0,0,0) in local coordinates - self.assertTupleAlmostEquals((0,0,0), p.toLocalCoords(p.origin).toTuple() ,2 ) - - #(0,0,0) is always the original base in global coordinates - self.assertTupleAlmostEquals(toTuple(base), p.toWorldCoords((0,0)).toTuple() ,2 ) - - def testXZPlaneOrigins(self): - base = Vector(0,0.25,0) - p = Plane(base, Vector(0,0,1), Vector(0,1,0)) - - #(0,0,0) is always the original base in global coordinates - self.assertTupleAlmostEquals(toTuple(base), p.toWorldCoords((0,0)).toTuple() ,2 ) - - #origin is always (0,0,0) in local coordinates - self.assertTupleAlmostEquals((0,0,0), p.toLocalCoords(p.origin).toTuple() ,2 ) - - def testPlaneBasics(self): - p = Plane.XY() - #local to world - self.assertTupleAlmostEquals((1.0,1.0,0),p.toWorldCoords((1,1)).toTuple(),2 ) - self.assertTupleAlmostEquals((-1.0,-1.0,0), p.toWorldCoords((-1,-1)).toTuple(),2 ) - - #world to local - self.assertTupleAlmostEquals((-1.0,-1.0), p.toLocalCoords(Vector(-1,-1,0)).toTuple() ,2 ) - self.assertTupleAlmostEquals((1.0,1.0), p.toLocalCoords(Vector(1,1,0)).toTuple() ,2 ) - - p = Plane.YZ() - self.assertTupleAlmostEquals((0,1.0,1.0),p.toWorldCoords((1,1)).toTuple() ,2 ) - - #world to local - self.assertTupleAlmostEquals((1.0,1.0), p.toLocalCoords(Vector(0,1,1)).toTuple() ,2 ) - - p = Plane.XZ() - r = p.toWorldCoords((1,1)).toTuple() - self.assertTupleAlmostEquals((1.0,0.0,1.0),r ,2 ) - - #world to local - self.assertTupleAlmostEquals((1.0,1.0), p.toLocalCoords(Vector(1,0,1)).toTuple() ,2 ) - - def testOffsetPlanes(self): - "Tests that a plane offset from the origin works ok too" - p = Plane.XY(origin=(10.0,10.0,0)) - - - self.assertTupleAlmostEquals((11.0,11.0,0.0),p.toWorldCoords((1.0,1.0)).toTuple(),2 ) - self.assertTupleAlmostEquals((2.0,2.0), p.toLocalCoords(Vector(12.0,12.0,0)).toTuple() ,2 ) - - #TODO test these offsets in the other dimensions too - p = Plane.YZ(origin=(0,2,2)) - self.assertTupleAlmostEquals((0.0,5.0,5.0), p.toWorldCoords((3.0,3.0)).toTuple() ,2 ) - self.assertTupleAlmostEquals((10,10.0,0.0), p.toLocalCoords(Vector(0.0,12.0,12.0)).toTuple() ,2 ) - - p = Plane.XZ(origin=(2,0,2)) - r = p.toWorldCoords((1.0,1.0)).toTuple() - self.assertTupleAlmostEquals((3.0,0.0,3.0),r ,2 ) - self.assertTupleAlmostEquals((10.0,10.0), p.toLocalCoords(Vector(12.0,0.0,12.0)).toTuple() ,2 ) - - def testXYPlaneBasics(self): - p = Plane.named('XY') - self.assertTupleAlmostEquals(p.zDir.toTuple(), zAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), xAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), yAxis_.toTuple(), 4) - - def testYZPlaneBasics(self): - p = Plane.named('YZ') - self.assertTupleAlmostEquals(p.zDir.toTuple(), xAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), yAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), zAxis_.toTuple(), 4) - - def testZXPlaneBasics(self): - p = Plane.named('ZX') - self.assertTupleAlmostEquals(p.zDir.toTuple(), yAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), zAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), xAxis_.toTuple(), 4) - - def testXZPlaneBasics(self): - p = Plane.named('XZ') - self.assertTupleAlmostEquals(p.zDir.toTuple(), yInvAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), xAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), zAxis_.toTuple(), 4) - - def testYXPlaneBasics(self): - p = Plane.named('YX') - self.assertTupleAlmostEquals(p.zDir.toTuple(), zInvAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), yAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), xAxis_.toTuple(), 4) - - def testZYPlaneBasics(self): - p = Plane.named('ZY') - self.assertTupleAlmostEquals(p.zDir.toTuple(), xInvAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.xDir.toTuple(), zAxis_.toTuple(), 4) - self.assertTupleAlmostEquals(p.yDir.toTuple(), yAxis_.toTuple(), 4) diff --git a/Libs/cadquery-lib/tests/__init__.py b/Libs/cadquery-lib/tests/__init__.py deleted file mode 100644 index 5dfc40e..0000000 --- a/Libs/cadquery-lib/tests/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -from cadquery import * -import unittest -import sys -import os - -import FreeCAD - -import Part as P -from FreeCAD import Vector as V - - -def readFileAsString(fileName): - f= open(fileName, 'r') - s = f.read() - f.close() - return s - - -def writeStringToFile(strToWrite, fileName): - f = open(fileName, 'w') - f.write(strToWrite) - f.close() - - -def makeUnitSquareWire(): - return Solid.cast(P.makePolygon([V(0, 0, 0), V(1, 0, 0), V(1, 1, 0), V(0, 1, 0), V(0, 0, 0)])) - - -def makeUnitCube(): - return makeCube(1.0) - - -def makeCube(size): - return Solid.makeBox(size, size, size) - - -def toTuple(v): - """convert a vector or a vertex to a 3-tuple: x,y,z""" - pnt = v - if type(v) == FreeCAD.Base.Vector: - return (v.Point.x, v.Point.y, v.Point.z) - elif type(v) == Vector: - return v.toTuple() - else: - raise RuntimeError("dont know how to convert type %s to tuple" % str(type(v)) ) - - -class BaseTest(unittest.TestCase): - - def assertTupleAlmostEquals(self, expected, actual, places): - for i, j in zip(actual, expected): - self.assertAlmostEquals(i, j, places) - -__all__ = ['TestCadObjects', 'TestCadQuery', 'TestCQSelectors', 'TestWorkplanes', 'TestExporters', 'TestCQSelectors', 'TestImporters','TestCQGI'] diff --git a/Shared.py b/Shared.py index 24b5ca9..96fb214 100644 --- a/Shared.py +++ b/Shared.py @@ -9,7 +9,10 @@ def clearActiveDocument(): # Grab our code editor so we can interact with it mw = FreeCADGui.getMainWindow() mdi = mw.findChild(QtGui.QMdiArea) - winName = mdi.currentSubWindow().windowTitle().split(" ")[0].split('.')[0] + currentWin = mdi.currentSubWindow() + if currentWin == None: + return + winName = currentWin.windowTitle().split(" ")[0].split('.')[0] try: doc = FreeCAD.getDocument(winName) @@ -84,4 +87,47 @@ def setActiveWindowTitle(title): mdiWin.setWindowTitle(title) cqCodePane = mdiWin.findChild(QtGui.QPlainTextEdit) - cqCodePane.setObjectName("cqCodePane_" + title.split('.')[0]) \ No newline at end of file + cqCodePane.setObjectName("cqCodePane_" + title.split('.')[0]) + + +def populateParameterEditor(parameters): + """Puts the proper controls in the script variable editor pane based on the parameters found""" + + FreeCAD.Console.PrintMessage("Script Variables:\r\n") + + mw = FreeCADGui.getMainWindow() + + # If the widget is open, we need to close it + dockWidgets = mw.findChildren(QtGui.QDockWidget) + for widget in dockWidgets: + if widget.objectName() == "cqVarsEditor": + gridLayout = QtGui.QGridLayout() + + line = 1 + + # Add controls for all the parameters so that they can be edited from the GUI + for pKey, pVal in parameters.iteritems(): + label = QtGui.QLabel(pKey) + + # We want to keep track of this parameter value field so that we can pull its value later when executing + value = QtGui.QLineEdit() + value.setText(str(pVal.default_value)) + value.setObjectName("pcontrol_" + pKey) + + # Add the parameter control sets, one set per line + gridLayout.addWidget(label, line, 0) + gridLayout.addWidget(value, line, 1) + + line += 1 + + # Create a widget we can put the layout in and add a scrollbar + newWidget = QtGui.QWidget() + newWidget.setLayout(gridLayout) + + # Add a scroll bar in case there are a lot of variables in the script + scrollArea = QtGui.QScrollArea() + scrollArea.setBackgroundRole(QtGui.QPalette.Light) + scrollArea.setStyleSheet("QLabel { color : black; }"); + scrollArea.setWidget(newWidget) + + widget.setWidget(scrollArea) \ No newline at end of file