Advertisement
danfalck

geom2d.py

Oct 21st, 2011
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # derived from CADvas
  4. # A 2D CAD application written in Python
  5. #
  6.  
  7. #
  8. # Author: Doug Blanding   <doug dot blanding at localnet dot com>
  9. # modifications by: Dan Falck </join #cam on freenode>
  10. #
  11. # CADvas is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # CADvas is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with CADvas; if not, write to the Free Software
  23. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  24. #
  25.  
  26. import string
  27. import math
  28.  
  29.  
  30.  
  31. version = '0.2.2'
  32.  
  33. #===========================================================================
  34. #
  35. # Math & geometry utility functions
  36. #
  37. #===========================================================================
  38.  
  39. def intersection(cline1, cline2):
  40.     """Return intersection (x,y) of 2 clines expressed as (a,b,c) coeff."""
  41.     a,b,c = cline1
  42.     d,e,f = cline2
  43.     i = b*f-c*e
  44.     j = c*d-a*f
  45.     k = a*e-b*d
  46.     if k:
  47.         return (i/k, j/k)
  48.     else:
  49.         return None
  50.  
  51. def cnvrt_2pts_to_coef(pt1, pt2):
  52.     """Return (a,b,c) coefficients of cline defined by 2 (x,y) pts."""
  53.     x1, y1 = pt1
  54.     x2, y2 = pt2
  55.     a = y2 - y1
  56.     b = x1 - x2
  57.     c = x2*y1-x1*y2
  58.     return (a, b, c)
  59.  
  60. def proj_pt_on_line(cline, pt):
  61.     """Return point which is the projection of pt on cline."""
  62.     a, b, c = cline
  63.     x, y = pt
  64.     denom = a**2 + b**2
  65.     if not denom:
  66.         return pt
  67.     xp = (b**2*x - a*b*y -a*c)/denom
  68.     yp = (a**2*y - a*b*x -b*c)/denom
  69.     return (xp, yp)
  70.  
  71. def pnt_in_box_p(pnt, box):
  72.     '''Point in box predicate: Return True if pnt is in box.'''
  73.     x, y = pnt
  74.     x1, y1, x2, y2 = box
  75.     if x1<x<x2 and y1<y<y2: return True
  76.     else: return False
  77.  
  78. def midpoint(p1, p2, f=.5):
  79.     """Return point part way (f=.5 by def) between points p1 and p2."""
  80.     return (((p2[0]-p1[0])*f)+p1[0], ((p2[1]-p1[1])*f)+p1[1])
  81.  
  82. def p2p_dist(p1, p2):
  83.     """Return the distance between two points"""
  84.     x, y = p1
  85.     u, v = p2
  86.     return math.sqrt((x-u)**2 + (y-v)**2)
  87.  
  88. def p2p_angle(p0, p1):
  89.     """Return angle (degrees) from p0 to p1."""
  90.     return math.degrees(math.atan2(p1[1]-p0[1], p1[0]-p0[0]))
  91.  
  92. def arc_angle_format(direction,start_pt,cen_pt,end_pt):
  93.     """Return arc in radius,center point, start angle, end angle format """
  94.     #move the arc so that center is at origin for easy calcs
  95.     new_start=sub_pt(start_pt,cen_pt)
  96.     new_end  =sub_pt(end_pt,  cen_pt)
  97.     start_angle= p2p_angle((0,0),new_start)
  98.     end_angle= p2p_angle((0,0),new_end)
  99.     #subtract angle1 from angle2
  100.     angle_diff= (end_angle-start_angle)
  101.     radius = p2p_dist(start_pt,cen_pt)
  102.     if direction[2] == 1:
  103.         new_arc = (radius,cen_pt,start_angle,end_angle)
  104.     else:
  105.         new_arc = (radius,cen_pt,end_angle,start_angle)
  106.     return new_arc
  107.  
  108.  
  109. def arc_angle(start_pt,end_pt,cen_pt):
  110.     """Return direction of arc- for CNC operations-works for arcs less than 180 degrees """
  111.     #move the arc so that center is at origin for easy calcs
  112.     new_start=sub_pt(start_pt,cen_pt)
  113.     new_end  =sub_pt(end_pt,  cen_pt)
  114.     angle1= p2p_angle((0,0),new_start)
  115.     angle2= p2p_angle((0,0),new_end)
  116.     #subtract angle1 from angle2
  117.     angle_diff= (angle2-angle1)
  118.     return angle_diff
  119.  
  120. def arc_angle2(start_pt,mid_pt,cen_pt):
  121.     """Return direction of arc- for CNC operations-works for arcs less than 180 degrees """
  122.     #move the arc so that center is at origin for easy calcs
  123.     new_start=sub_pt(start_pt,cen_pt)
  124.     new_mid  =sub_pt(mid_pt,cen_pt)
  125.    
  126.     angle1= p2p_angle((0,0),new_start)
  127.     angle2= p2p_angle((0,0),new_mid)
  128.    
  129.     #subtract angle1 from angle2
  130.     angle_diff= (angle2-angle1)
  131.     return angle_diff
  132.  
  133. def unitize(num):
  134.     """ return -1 or 1 depending on angle directio """
  135.     return int(num/math.fabs(num))
  136.  
  137.  
  138. def add_pt(p0, p1):
  139.     return (p0[0]+p1[0], p0[1]+p1[1])
  140.  
  141. def sub_pt(p0, p1):
  142.     return (p0[0]-p1[0], p0[1]-p1[1])
  143.  
  144. def line_circ_inters(x1, y1, x2, y2, xc, yc, r):
  145.     '''Return list of intersection pts of line defined by pts x1,y1 and x2,y2
  146.    and circle (cntr xc,yc and radius r).
  147.    Uses algorithm from Paul Bourke's web page.'''
  148.     intpnts = []
  149.     num = (xc - x1)*(x2 - x1) + (yc - y1)*(y2 - y1)
  150.     denom = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
  151.     if denom == 0:
  152.         return
  153.     u = num / denom
  154.     xp = x1 + u*(x2-x1)
  155.     yp = y1 + u*(y2-y1)
  156.  
  157.     a = (x2 - x1)**2 + (y2 - y1)**2
  158.     b = 2*((x2-x1)*(x1-xc) + (y2-y1)*(y1-yc))
  159.     c = xc**2+yc**2+x1**2+y1**2-2*(xc*x1+yc*y1)-r**2
  160.     q = b**2 - 4*a*c
  161.     if q == 0:
  162.         intpnts.append((xp, yp))
  163.     elif q:
  164.         u1 = (-b+math.sqrt(abs(q)))/(2*a)
  165.         u2 = (-b-math.sqrt(abs(q)))/(2*a)
  166.         intpnts.append(((x1 + u1*(x2-x1)), (y1 + u1*(y2-y1))))
  167.         intpnts.append(((x1 + u2*(x2-x1)), (y1 + u2*(y2-y1))))
  168.     return intpnts
  169.  
  170. def circ_circ_inters(x1, y1, r1, x2, y2, r2):
  171.     '''Return list of intersection pts of 2 circles.
  172.    Uses algorithm from Robert S. Wilson's web page.'''
  173.     pts = []
  174.     D = (x2-x1)**2 + (y2-y1)**2
  175.     if not D:
  176.         return pts  # circles have same cntr; no intersection
  177.     try:
  178.         q = math.sqrt(abs(((r1+r2)**2-D)*(D-(r2-r1)**2)))
  179.     except:
  180.         return pts  # circles don't interect
  181.     pts = [((x2+x1)/2+(x2-x1)*(r1**2-r2**2)/(2*D)+(y2-y1)*q/(2*D),
  182.             (y2+y1)/2+(y2-y1)*(r1**2-r2**2)/(2*D)-(x2-x1)*q/(2*D)),
  183.            ((x2+x1)/2+(x2-x1)*(r1**2-r2**2)/(2*D)-(y2-y1)*q/(2*D),
  184.             (y2+y1)/2+(y2-y1)*(r1**2-r2**2)/(2*D)+(x2-x1)*q/(2*D))]
  185.     if same_pt_p(pts[0], pts[1]):
  186.         pts.pop()   # circles are tangent
  187.     return pts
  188.  
  189. def same_pt_p(p1, p2):
  190.     '''Return True if p1 and p2 are within 1e-10 of each other.'''
  191.     if p2p_dist(p1, p2) < 1e-6:
  192.         return True
  193.     else:
  194.         return False
  195.  
  196. def cline_box_intrsctn(cline, box):
  197.     """Return tuple of pts where line intersects edges of box."""
  198.     x0, y0, x1, y1 = box
  199.     pts = []
  200.     segments = [((x0, y0), (x1, y0)),
  201.                 ((x1, y0), (x1, y1)),
  202.                 ((x1, y1), (x0, y1)),
  203.                 ((x0, y1), (x0, y0))]
  204.     for seg in segments:
  205.         pt = intersection(cline, cnvrt_2pts_to_coef(seg[0], seg[1]))
  206.         if pt:
  207.             if p2p_dist(pt, seg[0]) <= p2p_dist(seg[0], seg[1]) and \
  208.                p2p_dist(pt, seg[1]) <= p2p_dist(seg[0], seg[1]):
  209.                 if pt not in pts:
  210.                     pts.append(pt)
  211.     return tuple(pts)
  212.  
  213. def para_line(cline, pt):
  214.     """Return coeff of newline thru pt and parallel to cline."""
  215.     a, b, c = cline
  216.     x, y = pt
  217.     cnew = -(a*x + b*y)
  218.     return (a, b, cnew)
  219.  
  220. def para_lines(cline, d):
  221.     """Return 2 parallel lines straddling line, offset d."""
  222.     a, b, c = cline
  223.     c1 = math.sqrt(a**2 + b**2)*d
  224.     cline1 = (a, b, c + c1)
  225.     cline2 = (a, b, c - c1)
  226.     return (cline1, cline2)
  227.  
  228. def perp_line(cline, pt):
  229.     """Return coeff of newline thru pt and perpend to cline."""
  230.     a, b, c = cline
  231.     x, y = pt
  232.     cnew = a*y - b*x
  233.     return (b, -a, cnew)
  234.  
  235. def closer(p0, p1, p2):
  236.     """Return closer of p1 or p2 to point p0."""
  237.     d1 = (p1[0] - p0[0])**2 + (p1[1] - p0[1])**2
  238.     d2 = (p2[0] - p0[0])**2 + (p2[1] - p0[1])**2
  239.     if d1 < d2: return p1
  240.     else: return p2
  241.  
  242. def farther(p0, p1, p2):
  243.     """Return farther of p1 or p2 from point p0."""
  244.     d1 = (p1[0] - p0[0])**2 + (p1[1] - p0[1])**2
  245.     d2 = (p2[0] - p0[0])**2 + (p2[1] - p0[1])**2
  246.     if d1 > d2: return p1
  247.     else: return p2
  248.  
  249. def find_fillet_pts(r, commonpt, end1, end2):
  250.     """Return ctr of fillet (radius r) and tangent pts for corner
  251.    defined by a common pt, and two adjacent corner pts."""
  252.     line1 = cnvrt_2pts_to_coef(commonpt, end1)
  253.     line2 = cnvrt_2pts_to_coef(commonpt, end2)
  254.     # find 'interior' clines
  255.     cl1a, cl1b = para_lines(line1, r)
  256.     p2a = proj_pt_on_line(cl1a, end2)
  257.     p2b = proj_pt_on_line(cl1b, end2)
  258.     da = p2p_dist(p2a, end2)
  259.     db = p2p_dist(p2b, end2)
  260.     if da <= db: cl1 = cl1a
  261.     else: cl1 = cl1b
  262.     cl2a, cl2b = para_lines(line2, r)
  263.     p1a = proj_pt_on_line(cl2a, end1)
  264.     p1b = proj_pt_on_line(cl2b, end1)
  265.     da = p2p_dist(p1a, end1)
  266.     db = p2p_dist(p1b, end1)
  267.     if da <= db: cl2 = cl2a
  268.     else: cl2 = cl2b
  269.     pc = intersection(cl1, cl2)
  270.     p1 = proj_pt_on_line(line1, pc)
  271.     p2 = proj_pt_on_line(line2, pc)
  272.     return (pc, p1, p2)
  273.  
  274. def find_common_pt(apair, bpair):
  275.     """Return (common pt, other pt from a, other pt from b), where a and b
  276.    are coordinate pt pairs in (p1, p2) format."""
  277.     p0, p1 = apair
  278.     p2, p3 = bpair
  279.     if same_pt_p(p0, p2):
  280.         cp = p0     # common pt
  281.         opa = p1    # other pt a
  282.         opb = p3    # other pt b
  283.     elif same_pt_p(p0, p3):
  284.         cp = p0
  285.         opa = p1
  286.         opb = p2
  287.     elif same_pt_p(p1, p2):
  288.         cp = p1
  289.         opa = p0
  290.         opb = p3
  291.     elif same_pt_p(p1, p3):
  292.         cp = p1
  293.         opa = p0
  294.         opb = p2
  295.     else:
  296.         return
  297.     return (cp, opa, opb)
  298.  
  299. def cr_from_3p(p1, p2, p3):
  300.     """Return ctr pt and radius of circle on which 3 pts reside.
  301.    From Paul Bourke's web page."""
  302.     chord1 = cnvrt_2pts_to_coef(p1, p2)
  303.     chord2 = cnvrt_2pts_to_coef(p2, p3)
  304.     radial_line1 = perp_line(chord1, midpoint(p1, p2))
  305.     radial_line2 = perp_line(chord2, midpoint(p2, p3))
  306.     ctr = intersection(radial_line1, radial_line2)
  307.     if ctr:
  308.         radius =  p2p_dist(p1, ctr)
  309.         return (ctr, radius)
  310.  
  311. def extendline(p0, p1, d):
  312.     """Return point which lies on extension of line segment p0-p1,
  313.    beyond p1 by distance d."""
  314.     pts = line_circ_inters(p0[0], p0[1], p1[0], p1[1], p1[0], p1[1], d)
  315.     if pts:
  316.         return farther(p0, pts[0], pts[1])
  317.     else:
  318.         return
  319.  
  320. def shortenline(p0, p1, d):
  321.     """Return point which lies on line segment p0-p1,
  322.    short of p1 by distance d."""
  323.     pts = line_circ_inters(p0[0], p0[1], p1[0], p1[1], p1[0], p1[1], d)
  324.     if pts:
  325.         return closer(p0, pts[0], pts[1])
  326.     else:
  327.         return
  328.  
  329. def line_tan_to_circ(circ, p):
  330.     """Return tan pts on circ of line through p."""
  331.     c, r = circ
  332.     d = p2p_dist(c, p)
  333.     ang0 = p2p_angle(c, p)*math.pi/180
  334.     theta = math.asin(r/d)
  335.     ang1 = ang0+math.pi/2-theta
  336.     ang2 = ang0-math.pi/2+theta
  337.     p1 = (c[0]+(r*math.cos(ang1)), c[1]+(r*math.sin(ang1)))
  338.     p2 = (c[0]+(r*math.cos(ang2)), c[1]+(r*math.sin(ang2)))
  339.     return (p1, p2)
  340.  
  341. def line_tan_to_2circs(circ1, circ2):
  342.     """Return tangent pts on line tangent to 2 circles.
  343.    Order of circle picks determines which tangent line."""
  344.     c1, r1 = circ1
  345.     c2, r2 = circ2
  346.     d = p2p_dist(c1, c2)    # distance between centers
  347.     ang_loc = p2p_angle(c2, c1)*math.pi/180  # angle of line of centers
  348.     f = (r2/r1-1)/d # reciprocal dist from c1 to intersection of loc & tan line
  349.     theta = math.asin(r1*f)    # angle between loc and tangent line
  350.     ang1 = (ang_loc + math.pi/2 - theta)
  351.     ang2 = (ang_loc - math.pi/2 + theta)
  352.     p1 = (c1[0]+(r1*math.cos(ang1)), c1[1]+(r1*math.sin(ang1)))
  353.     p2 = (c2[0]+(r2*math.cos(ang1)), c2[1]+(r2*math.sin(ang1)))
  354.     return (p1, p2)
  355.  
  356. def angled_cline(pt, angle):
  357.     """Return cline through pt at angle (degrees)"""
  358.     ang = angle * math.pi / 180
  359.     dx = math.cos(ang)
  360.     dy = math.sin(ang)
  361.     p2 = (pt[0]+dx, pt[1]+dy)
  362.     cline = cnvrt_2pts_to_coef(pt, p2)
  363.     return cline
  364.  
  365. def ang_bisector(p0, p1, p2, f=0.5):
  366.     """Return cline coefficients of line through vertex p0, factor=f
  367.    between p1 and p2."""
  368.     ang1 = math.atan2(p1[1]-p0[1], p1[0]-p0[0])
  369.     ang2 = math.atan2(p2[1]-p0[1], p2[0]-p0[0])
  370.     deltang = ang2 - ang1
  371.     ang3 = (f * deltang + ang1)*180/math.pi
  372.     return angled_cline(p0, ang3)
  373.  
  374.  
  375. def pt_on_RHS_p(pt, p0, p1):
  376.     """Return True if pt is on right hand side going from p0 to p1."""
  377.     angline = p2p_angle(p0, p1)
  378.     angpt = p2p_angle(p0, pt)
  379.     if angline >= 0:
  380.         if angline > angpt > angline-180:
  381.             return True
  382.     else:
  383.         angline += 360
  384.         if angpt < 0:
  385.             angpt += 360
  386.         if angline > angpt > angline-180:
  387.             return True
  388.  
  389. def rotate_pt(pt, ang, ctr):
  390.     """Return coordinates of pt rotated ang (deg) CCW about ctr.
  391.  
  392.    This is a 3-step process:
  393.    1. translate to place ctr at origin.
  394.    2. rotate about origin (CCW version of Paul Bourke's algorithm.
  395.    3. apply inverse translation. """
  396.     x, y = sub_pt(pt, ctr)
  397.     A = ang * math.pi / 180
  398.     u = x * math.cos(A) - y * math.sin(A)
  399.     v = y * math.cos(A) + x * math.sin(A)
  400.     return add_pt((u, v), ctr)
  401.    
  402.  
  403. #===========================================================================
  404.  
  405.  
  406.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement