Merge pull request #101 from jmwright/cqgi

Cqgi
This commit is contained in:
Jeremy Wright 2017-10-04 06:21:09 -04:00 committed by GitHub
commit 6bfe99eac7
146 changed files with 223 additions and 14878 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "Libs/cadquery"]
path = Libs/cadquery
url = https://github.com/dcowden/cadquery.git

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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("<XY").workplane()
# Cut the corner out
result = result.circle(1.0).cutThruAll()
# Render the solid
show(result)

View File

@ -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)
# Workplane is offset from the object surface
result = result.faces("<X").workplane(offset=0.75)
# Create a disc
result = result.circle(1.0).extrude(0.5)
# Render the solid
show(result)

View File

@ -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 rotated workplane and put holes in each corner of a rectangle on
# that workplane, producing angled holes in the face
result = cadquery.Workplane("front").box(4.0, 4.0, 0.25).faces(">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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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, True)\
.rect((p_outerWidth - 2.0 * p_thickness), (p_outerLength - 2.0 * p_thickness))\
.extrude((p_outerHeight - 2.0 * p_thickness), False) # Set combine false to produce just the new boss
ishell.edges("|Z").fillet(p_sideRadius - p_thickness)
# Make the box outer box
box = oshell.cut(ishell)
# Make the screwposts
POSTWIDTH = (p_outerWidth - 2.0 * p_screwpostInset)
POSTLENGTH = (p_outerLength - 2.0 * p_screwpostInset)
postCenters = box.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)

View File

@ -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()

View File

@ -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)

View File

@ -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").shell(-1.0 * t)
# make the bumps on the top
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("<Z").workplane(invert=True)
if lbumps > 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)

View File

@ -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)

View File

@ -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)

View File

@ -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('<XY').workplane() \
.pushPoints(dot_pos).circle(r) \
.extrude(r)
# Make a fillet almost the same radius to get a pseudo spherical cap.
base = base.faces('>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))

View File

@ -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)

View File

@ -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)))

View File

@ -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('<Z').vertices('>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('<Z').vertices('>Y').vertices('<X')
res = add_wing(res, -1)
# make the bridge for extruder mounting
wp = res.faces('>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('<X'). \
workplane(). \
hLine(bridge_length). \
vLine(-10). \
hLine(-bridge_length). \
close().extrude(bridge_depth)
faces = res.faces('>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('<Y').workplane()
res = make_aux_holes(res, main_plate_size_x*2/3., 3)
# make aux holes at the side (@overhang)
res = res.faces('<X').workplane().transformed((90, 0, 0))
res = make_aux_holes(res, main_plate_size_x*2/3., 3)
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('<Y').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('<Y').edges('<X')
res = res.workplane()
res = move_to_center(res, face_left)
res = res.transformed((0, 180, 0))
hole_sep = 0.5*face_right.Area()/main_plate_thickness
res = make_aux_holes(res, hole_sep, 2)
# show the result
show(res)

View File

@ -1,11 +0,0 @@
# Example using advanced logical operators in string selectors
# to select only the inside edges on a shelled cube to chamfer.
import cadquery as cq
from Helpers import show
result = cq.Workplane("XY").box(2, 2, 2).\
faces(">Z").shell(-0.2).\
faces(">Z").edges("not(<X or >X or <Y or >Y)").\
chamfer(0.125)
show(result)

View File

@ -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)

View File

@ -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")

View File

@ -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

View File

@ -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

View File

@ -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

1
Libs/cadquery Submodule

@ -0,0 +1 @@
Subproject commit d1fb644aa45705c91067a74d3d37845dbc0faef9

File diff suppressed because one or more lines are too long

View File

@ -1,7 +0,0 @@
build/
*.pyc
doc/_build/*
dist/*
.idea/*
cadquery.egg-info
target/*

View File

@ -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

View File

@ -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))

View File

@ -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.

View File

@ -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

View File

@ -1 +0,0 @@
include README.md

View File

@ -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:
<p align="center">
<img src="doc/_static/hyOzd-cablefix.png" width="350"/>
<img src="doc/_static/hyOzd-finished.jpg" width="350"/>
</p>
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("<Z").workplane().pushPoints([
(px, py),
(-px, py),
(-px, -py),
(px, -py)
]).hole(mhd)
# fill holes
r = r.faces("<Y").workplane().center(0, mh/2.).pushPoints([
(-rl/2., 0),
(0, 0),
(rl/2., 0)
]).hole(fhd, mw/2.)
show(r)
```
Thanks go to cadquery contributor hyOzd ( Altu Technology ) for the example!
Why CadQuery instead of OpenSCAD?
========================================
CadQuery is based on OpenCasCade. CadQuery shares many features with OpenSCAD, another open source, script based, parametric model generator.
The primary advantage of OpenSCAD is the large number of already existing model libaries that exist already. So why not simply use OpenSCAD?
CadQuery scripts have several key advantages over OpenSCAD:
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.
License
========
CadQuery is licensed under the terms of the Apache Public License, version 2.0.
A copy of the license can be found at http://www.apache.org/licenses/LICENSE-2.0
CadQuery GUI Interfaces
=======================
There are currently several known CadQuery GUIs:
### CadQuery FreeCAD Module
You can use CadQuery inside of FreeCAD. There's an excellent plugin module here https://github.com/jmwright/cadquery-freecad-module
### CadQuery GUI (under active development)
Work is underway on a stand-alone gui here: https://github.com/jmwright/cadquery-gui
### ParametricParts.com
If you are impatient and want to see a working example with no installation, have a look at this lego brick example http://parametricparts.com/parts/vqb5dy69/.
The script that generates the model is on the 'modelscript' tab.
Installing -- FreeStanding Installation
========================================
Use these steps if you would like to write CadQuery scripts as a python API. In this case, FreeCAD is used only as a CAD kernel.
1. install FreeCAD, version 0.15 or greater for your platform. https://github.com/FreeCAD/FreeCAD/releases.
2. adjust your path if necessary. FreeCAD bundles a python interpreter, but you'll probably want to use your own,
preferably one that has virtualenv available. To use FreeCAD from any python interpreter, just append the FreeCAD
lib directory to your path. On (*Nix)::
```python
import sys
sys.path.append('/usr/lib/freecad/lib')
```
or on Windows::
```python
import sys
sys.path.append('/c/apps/FreeCAD/bin')
```
*NOTE* FreeCAD on Windows will not work with python 2.7-- you must use pthon 2.6.X!!!!
3. install cadquery::
```bash
pip install cadquery
```
3. test your installation::
```python
from cadquery import *
box = Workplane("XY").box(1,2,3)
exporters.toString(box,'STL')
```
You're up and running!
Installing -- Using CadQuery from Inside FreeCAD
=================================================
Use the Excellent CadQuery-FreeCAD plugin here:
https://github.com/jmwright/cadquery-freecad-module
It includes a distribution of the latest version of cadquery.
Roadmap/Future Work
=======================
Work has begun on Cadquery 2.0, which will feature:
1. Feature trees, for more powerful selection
2. Direct use of OpenCascade Community Edition(OCE), so that it is no longer required to install FreeCAD
3. https://github.com/jmwright/cadquery-gui, which will allow visualization of workplanes
The project page can be found here: https://github.com/dcowden/cadquery/projects/1
A more detailed description of the plan for CQ 2.0 is here: https://docs.google.com/document/d/1cXuxBkVeYmGOo34MGRdG7E3ILypQqkrJ26oVf3CUSPQ
Where does the name CadQuery come from?
========================================
CadQuery is inspired by jQuery, 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.

View File

@ -1,125 +0,0 @@
What is a CadQuery?
========================================
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.
Getting Started With CadQuery
========================================
The easiest way to get started with CadQuery is to Install FreeCAD ( version 14 recommended ) (http://www.freecadweb.org/) , and then to use our 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!
Recently Added Features
========================================
* 12/5/14 -- New FreeCAD/CadQuery Module! https://github.com/jmwright/cadquery-freecad-module
* 10/25/14 -- Added Revolution Feature ( thanks Jeremy ! )
Why CadQuery instead of OpenSCAD?
========================================
CadQuery is based on OpenCasCade. CadQuery shares many features with OpenSCAD, another open source, script based, parametric model generator.
The primary advantage of OpenSCAD is the large number of already existing model libaries that exist already. So why not simply use OpenSCAD?
CadQuery scripts have several key advantages over OpenSCAD:
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.
License
========
CadQuery is licensed under the terms of the LGPLv3. http://www.gnu.org/copyleft/lesser.html
Where is the GUI?
==================
If you would like IDE support, you can use CadQuery inside of FreeCAD. There's an excellent plugin module here https://github.com/jmwright/cadquery-freecad-module
CadQuery also provides the backbone of http://parametricparts.com, so the easiest way to see it in action is to review the samples and objects there.
Installing -- FreeStanding Installation
========================================
Use these steps if you would like to write CadQuery scripts as a python API. In this case, FreeCAD is used only as a CAD kernel.
1. install FreeCAD, version 0.14 or greater for your platform. http://sourceforge.net/projects/free-cad/.
2. adjust your path if necessary. FreeCAD bundles a python interpreter, but you'll probably want to use your own,
preferably one that has virtualenv available. To use FreeCAD from any python interpreter, just append the FreeCAD
lib directory to your path. On (*Nix)::
import sys
sys.path.append('/usr/lib/freecad/lib')
or on Windows::
import sys
sys.path.append('/c/apps/FreeCAD/bin')
*NOTE* FreeCAD on Windows will not work with python 2.7-- you must use pthon 2.6.X!!!!
3. install cadquery::
pip install cadquery
3. test your installation::
from cadquery import *
box = Workplane("XY").box(1,2,3)
exporters.toString(box,'STL')
You're up and running!
Installing -- Using CadQuery from Inside FreeCAD
=================================================
Use the Excellent CadQuery-FreeCAD plugin here:
https://github.com/jmwright/cadquery-freecad-module
It includes a distribution of the latest version of cadquery.
Where does the name CadQuery come from?
========================================
CadQuery is inspired by ( `jQuery <http://www.jquery.com>`_ ), 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.

View File

@ -1,2 +0,0 @@
#!/bin/sh
sphinx-build -b html doc target/docs

View File

@ -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.
***

View File

@ -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"

View File

@ -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 <http://www.gnu.org/licenses/>
"""

File diff suppressed because it is too large Load Diff

View File

@ -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
<div class="cq" style="text-align:%(txt_align)s;float:left;">
%(out_svg)s
</div>
<div style="clear:both;">
</div>
"""
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)

View File

@ -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 = "<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

View File

@ -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

View File

@ -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 <http://www.gnu.org/licenses/>
"""
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

View File

@ -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 <g> 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 = "<root>%s</root>" % 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 = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
width="%(width)s"
height="%(height)s"
>
<g transform="scale(%(unitScale)s, -%(unitScale)s) translate(%(xTranslate)s,%(yTranslate)s)" stroke-width="%(strokeWidth)s" fill="none">
<!-- hidden lines -->
<g stroke="rgb(160, 160, 160)" fill="none" stroke-dasharray="%(strokeWidth)s,%(strokeWidth)s" >
%(hiddenContent)s
</g>
<!-- solid lines -->
<g stroke="rgb(0, 0, 0)" fill="none">
%(visibleContent)s
</g>
</g>
<g transform="translate(20,%(textboxY)s)" stroke="rgb(0,0,255)">
<line x1="30" y1="-30" x2="75" y2="-33" stroke-width="3" stroke="#000000" />
<text x="80" y="-30" style="stroke:#000000">X </text>
<line x1="30" y1="-30" x2="30" y2="-75" stroke-width="3" stroke="#000000" />
<text x="25" y="-85" style="stroke:#000000">Y </text>
<line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3" stroke="#000000" />
<text x="65" y="-5" style="stroke:#000000">Z </text>
<!--
<line x1="0" y1="0" x2="%(unitScale)s" y2="0" stroke-width="3" />
<text x="0" y="20" style="stroke:#000000">1 %(uom)s </text>
-->
</g>
</svg>
"""
PATHTEMPLATE="\t\t\t<path d=\"%s\" />\n"

View File

@ -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 <http://www.gnu.org/licenses/>
"""
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)

View File

@ -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")

File diff suppressed because it is too large Load Diff

View File

@ -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
"""

View File

@ -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 <http://www.gnu.org/licenses/>
"""
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
[+\|-\|<\|>\|] \<X\|Y\|Z>
"""
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)

View File

@ -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)

View File

@ -1,2 +0,0 @@
This documentation should be generated with sphinxdoc.
see ../build-docs.sh

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

View File

@ -1,404 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>CadQuery Cheatsheet</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
.section {
margin: 0.5em;
padding: 0px 0.5em 0.5em;
background-color: #EBEBEB;
}
.column {
float: left;
width: 375px;
}
tr {
background-color: #FFFFFF;
}
td {
text-align: center;
width: 5em;
}
h2 {
display: inline;
}
</style>
</head>
<body>
<div class="column" style="width:475px;">
<div class="section">
<h2>Documentation</h2>
<ul style="background-color:#ffffff;margin-bottom:0px;margin-top:0px;">
<li><a href="http://parametricparts.com/docs/#">ParametricParts Documentation</a></li>
<li><a href="https://github.com/dcowden/cadquery/blob/master/README.md">CadQuery Readme</a></li>
<li><a href="http://parametricparts.com/docs/examples.html#examples">CadQuery Examples</a></li>
<li><a href="http://parametricparts.com/docs/classreference.html">CadQuery Class Reference</a></li>
</ul>
</div>
<div class="section">
<h2>BREP Terminology</h2><br />
<table style="width:100%;">
<tr>
<td style="width:10%;"><strong>vertex</strong></td>
<td style="width:90%;">A single point in space</td>
</tr>
<tr>
<td><strong>edge</strong></td>
<td>A connection between two or more vertices along a particular path (called a curve)</td>
</tr>
<tr>
<td><strong>wire</strong></td>
<td>A collection of edges that are connected together</td>
</tr>
<tr>
<td><strong>face</strong></td>
<td>A set of edges or wires that enclose a surface</td>
</tr>
<tr>
<td><strong>shell</strong></td>
<td>A collection of faces that are connected together along some of their edges</td>
</tr>
<tr>
<td><strong>solid</strong></td>
<td>A shell that has a closed interior</td>
</tr>
<tr>
<td><strong>compound</strong></td>
<td>A collection of solids</td>
</tr>
</table>
</div>
<div class="section">
<h2>Named Planes</h2><br />
Available named planes are as follows. Direction references refer to the global directions.
<table style="width:100%;">
<tr>
<th style="width:25%;">Name</th>
<th style="width:25%;">xDir</th>
<th style="width:25%;">yDir</th>
<th style="width:25%;">zDir</th>
</tr>
<tr>
<td>XY</td>
<td>+x</td>
<td>+y</td>
<td>+z</td>
</tr>
<tr>
<td>YZ</td>
<td>+y</td>
<td>+z</td>
<td>+x</td>
</tr>
<tr>
<td>XZ</td>
<td>+x</td>
<td>+z</td>
<td>-y</td>
</tr>
<tr>
<td>front</td>
<td>+x</td>
<td>+y</td>
<td>+z</td>
</tr>
<tr>
<td>back</td>
<td>-x</td>
<td>+y</td>
<td>-z</td>
</tr>
<tr>
<td>left</td>
<td>+z</td>
<td>+y</td>
<td>-x</td>
</tr>
<tr>
<td>right</td>
<td>-z</td>
<td>+y</td>
<td>+x</td>
</tr>
<tr>
<td>top</td>
<td>+x</td>
<td>-z</td>
<td>+y</td>
</tr>
<tr>
<td>bottom</td>
<td>+x</td>
<td>+z</td>
<td>-y</td>
</tr>
</table>
</div>
<div class="section">
<h2>Core Classes</h2><br />
<table style="width:100%;">
<tr>
<th style="width:40%;">Class</th>
<th style="width:60%;">Description</th>
</tr>
<tr>
<td>CQ(obj)</td>
<td>Provides enhanced functionality for a wrapped CAD primitive.</td>
</tr>
<tr>
<td>Plane(origin, xDir, normal)</td>
<td>A 2d coordinate system in space, with the x-y axes on the a plane, and a particular point as the origin.</td>
</tr>
<tr>
<td>Workplane(inPlane[origin, obj])</td>
<td>Defines a coordinate system in space, in which 2-d coordinates can be used.</td>
</tr>
</table>
</div>
</div>
<div class="column" style="width:600px;">
<div class="section">
<h2>Selector Methods</h2><br />
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.<br />
<table style="width:100%;">
<tr>
<th style="width:40%;">Selector Method</th>
<th style="width:60%;">Description</th>
</tr>
<tr>
<td><a href="http://parametricparts.com/docs/classreference.html#cadfile.cadutils.cadquery.CQ.faces">CQ.faces(selector=None)</a></td>
<td>Select the faces of objects on the stack, optionally filtering the selection.</td>
<tr>
<td><a href="http://parametricparts.com/docs/classreference.html#cadfile.cadutils.cadquery.CQ.edges">CQ.edges(selector=None)</a></td>
<td>Select the edges of objects on the stack, optionally filtering the selection.</td>
</tr>
<tr>
<td><a href="http://parametricparts.com/docs/classreference.html#cadfile.cadutils.cadquery.CQ.vertices">CQ.vertices(selector=None)</a></td>
<td>Select the vertices of objects on the stack, optionally filtering the selection.</td>
</tr>
<tr>
<td><a href="http://parametricparts.com/docs/classreference.html#cadfile.cadutils.cadquery.CQ.solids">CQ.solids(selector=None)</a></td>
<td>Select the solids of objects on the stack, optionally filtering the selection.</td>
</tr>
<tr>
<td><a href="http://parametricparts.com/docs/classreference.html#cadfile.cadutils.cadquery.CQ.shells">CQ.shells(selector=None)</a></td>
<td>Select the shells of objects on the stack, optionally filtering the selection.</td>
</tr>
</table>
</div>
<div class="section">
<h2>Selector Classes</h2><br />
<table style="width:100%;">
<tr>
<th style="width:40%;">Class</th>
<th style="width:60%;">Description</th>
</tr>
<tr>
<td>NearestToPointSelector(pnt)</td>
<td>Selects object nearest the provided point.</td>
</tr>
<tr>
<td>ParallelDirSelector(vector[tolerance])</td>
<td>Selects objects parallel with the provided direction.</td>
</tr>
<tr>
<td>DirectionSelector(vector[tolerance])</td>
<td>Selects objects aligned with the provided direction.</td>
</tr>
<tr>
<td>PerpendicularDirSelector(vector[tolerance])</td>
<td>Selects objects perpendicular with the provided direction.</td>
</tr>
<tr>
<td>TypeSelector(typeString)</td>
<td>Selects objects of the prescribed topological type.</td>
</tr>
<tr>
<td>DirectionMinMaxSelector(vector[directionMax])</td>
<td>Selects objects closest or farthest in the specified direction.</td>
</tr>
<tr>
<td>StringSyntaxSelector(selectorString)</td>
<td>Filter lists objects using a simple string syntax.</td>
</tr>
</table>
</div>
<div class="section">
<h2>Selector String Modifiers</h2><br />
Selectors are a complex topic: see <a href="http://parametricparts.com/docs/selectors.html">CadQuery String Selectors</a> for more information.<br />
Axis Strings are: X, Y, Z, XY, YZ, XZ
<table style="width:100%;">
<tr>
<th style="width:10%;">Modifier</th>
<th style="width:90%;">Description</th>
</tr>
<tr>
<td>&#124;</td>
<td>Parallel to (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=paralleldirselector#cadfile.cadutils.cadquery.ParallelDirSelector">ParallelDirSelector</a>). Can return multiple objects.</td>
</tr>
<tr>
<td>&#35;</td>
<td>Perpendicular to (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=perpendiculardirselector#cadfile.cadutils.cadquery.PerpendicularDirSelector">PerpendicularDirSelector</a>)</td>
</tr>
<tr>
<td>&#43;</td>
<td>Positive direction (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=directionselector#cadfile.cadutils.cadquery.DirectionSelector">DirectionSelector</a>)</td>
</tr>
<tr>
<td>&#45;</td>
<td>Negative direction (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=directionselector#cadfile.cadutils.cadquery.DirectionSelector">DirectionSelector</a>)</td>
</tr>
<tr>
<td>&gt;</td>
<td>Maximize (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=directionminmaxselector#cadfile.cadutils.cadquery.DirectionMinMaxSelector">DirectionMinMaxSelector</a> with directionMax=True)</td>
</tr>
<tr>
<td>&lt;</td>
<td>Minimize (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=directionminmaxselector#cadfile.cadutils.cadquery.DirectionMinMaxSelector">DirectionMinMaxSelector</a> with directionMax=False)</td>
</tr>
<tr>
<td>&#37;</td>
<td>Curve/surface type (same as <a href="http://parametricparts.com/docs/classreference.html?highlight=typeselector#cadfile.cadutils.cadquery.TypeSelector">TypeSelector</a>)</td>
</tr>
</table>
</div>
<div class="section">
<h2>Examples of Filtering Faces</h2><br />
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.
<table style="width:100%;">
<tr>
<th style="width:10%;">Selector</th>
<th style="width:40%;">Selector Class</th>
<th style="width:40%;">Selects</th>
<th style="width:10%;"># Objects Returned</th>
</tr>
<tr>
<td>&#43;Z</td>
<td>DirectionSelector</td>
<td>Faces with normal in +z direction</td>
<td>0 or 1</td>
</tr>
<tr>
<td>&#124;Z</td>
<td>ParallelDirSelector</td>
<td>Faces parallel to xy plane</td>
<td>0..many</td>
</tr>
<tr>
<td>&#45;X</td>
<td>DirectionSelector</td>
<td>Faces with normal in neg x direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#35;Z</td>
<td>PerpendicularDirSelector</td>
<td>Faces perpendicular to z direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#37;Plane</td>
<td>TypeSelector</td>
<td>Faces of type plane</td>
<td>0..many</td>
</tr>
<tr>
<td>&gt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Face farthest in the positive y dir</td>
<td>0 or 1</td>
</tr>
<tr>
<td>&lt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Face farthest in the negative y dir</td>
<td>0 or 1</td>
</tr>
</table>
</div>
<div class="section">
<h2>Examples of Filtering Edges</h2><br />
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.
<table style="width:100%;">
<tr>
<th style="width:10%;">Selector</th>
<th style="width:40%;">Selector Class</th>
<th style="width:40%;">Selects</th>
<th style="width:10%;"># Objects Returned</th>
</tr>
<tr>
<td>&#43;Z</td>
<td>DirectionSelector</td>
<td>Edges aligned in the Z direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#124;Z</td>
<td>ParallelDirSelector</td>
<td>Edges parallel to z direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#45;X</td>
<td>DirectionSelector</td>
<td>Edges aligned in neg x direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#35;Z</td>
<td>PerpendicularDirSelector</td>
<td>Edges perpendicular to z direction</td>
<td>0..many</td>
</tr>
<tr>
<td>&#37;Plane</td>
<td>TypeSelector</td>
<td>Edges type line</td>
<td>0..many</td>
</tr>
<tr>
<td>&gt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Edges farthest in the positive y dir</td>
<td>0 or 1</td>
</tr>
<tr>
<td>&lt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Edges farthest in the negative y dir</td>
<td>0 or 1</td>
</tr>
</table>
</div>
<div class="section">
<h2>Examples of Filtering Vertices</h2><br />
Only a few of the filter types apply to vertices. The location of the vertex is the subject of the filter.
<table style="width:100%;">
<tr>
<th style="width:10%;">Selector</th>
<th style="width:40%;">Selector Class</th>
<th style="width:40%;">Selects</th>
<th style="width:10%;"># Objects Returned</th>
</tr>
<tr>
<td>&gt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Vertices farthest in the positive y dir</td>
<td>0 or 1</td>
</tr>
<tr>
<td>&lt;Y</td>
<td>DirectionMinMaxSelector</td>
<td>Vertices farthest in the negative y dir</td>
<td>0 or 1</td>
</tr>
</table>
</div>
</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -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

View File

@ -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:

View File

@ -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 <h1> and <h2> 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
# "<project> v<release> 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 <link> 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'

View File

@ -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 <https://github.com/jmwright/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 <https://www.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:

View File

@ -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.

File diff suppressed because it is too large Load Diff

View File

@ -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)

View File

@ -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 <https://github.com/jmwright/cadquery-freecad-module>`_ or
`parametricParts.com <https://www.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.

View File

@ -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 <https://youtu.be/lxhBNOE7GVs>`_ 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`

View File

@ -1,63 +0,0 @@
.. _installation:
Installing CadQuery
===================================
CadQuery is based on `FreeCAD <http://sourceforge.net/apps/mediawiki/free-cad/index.php?title=Main_Page>`_,
which is turn based on the open-source `OpenCascade <http://www.opencascade.com/>`_ 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 <http://youtu.be/InZu8jgaYCA>`_ will walk you through the installation
Installation: Other Platforms
------------------------------------------
1. Install FreeCAD using the appropriate installer for your platform, on `www.freecadweb.org <http://www.freecadweb.org/wiki/?title=Download>`_
2. pip install cadquery
This `Windows Installation video <https://www.youtube.com/watch?v=dWw4Y_ah-8k>`_ 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 <https://github.com/jmwright/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 <https://www.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

Some files were not shown because too many files have changed in this diff Show More