Esempio n. 1
0
def Draw(p):

    lay=0
    path=p['path']
    n=p['nodes']
    d=p['drawing']
    rx=p['position'][0]
    ry=p['position'][1]
    if 'layer' in p.keys(): lay=p['layer']

    for c in path:
        if c[0]=='line':
            d.add(dxf.line((rx+n[c[1]][0],ry+n[c[1]][1]),
                           (rx+n[c[2]][0],ry+n[c[2]][1]),layer=lay))
        elif c[0]=='arc':
            cr=geo.CircleFrom3Points(n[c[1]],n[c[3]],n[c[2]])
            if cr['Direction']<0:
                d.add(dxf.arc(center=(rx+cr['Center'][0],ry+cr['Center'][1]),
                              radius=cr['Radius'],
                              startangle=math.degrees(cr['P1Degree']),
                              endangle=math.degrees(cr['P3Degree']),
                              layer=lay))
            else:    
                d.add(dxf.arc(center=(rx+cr['Center'][0],ry+cr['Center'][1]),
                              radius=cr['Radius'],
                              startangle=math.degrees(cr['P3Degree']),
                              endangle=math.degrees(cr['P1Degree']),
                              layer=lay))
            
        elif c[0]=='circle':
            rds=n[c[2]][0]-n[c[1]][0]
            d.add(dxf.circle(rds,(rx+n[c[1]][0],ry+n[c[1]][1]),layer=lay))
Esempio n. 2
0
	def addToDrawing(self, drawing, layer='0'):
		Shape.addToDrawing(self, drawing, layer) 
		if not self.error:
			if self.p.reverse:
				arc = dxf.arc(self.p.radius, self.p.centerPoint, self.p.endAngle, self.p.startAngle, layer = '0')
			else:
				arc = dxf.arc(self.p.radius, self.p.centerPoint, self.p.startAngle, self.p.endAngle, layer = '0')
			drawing.add(arc)
Esempio n. 3
0
def DrawCreator(name, type, parameter, material, thickness=0, address=dirc):

    file_name = name + '.dxf'  #加一步判据
    file_name = re.sub('[\\\]|[\/]|[\*]', '_', file_name)
    drawing = dxf.drawing(file_name)

    if 'od' in parameter and not ('id' in parameter):

        drawing.add(dxf.circle(radius=(parameter['od']) / 2, center=(0, 0)))
        # drawing.add(dxf.text(file_name,height=parameter[0]/4,alignpoint =(0,0)))
    elif 'od' in parameter and 'id' in parameter and not ('angle'
                                                          in parameter):

        drawing.add(dxf.circle(radius=(parameter['od']) / 2, center=(0, 0)))
        drawing.add(dxf.circle(radius=(parameter['id']) / 2, center=(0, 0)))
        # drawing.add(dxf.text(file_name,height=parameter[1]/4, alignpoint =(0,0)))
    elif 'od' in parameter and 'id' in parameter and 'angle' in parameter:
        drawing.add(
            dxf.arc(radius=parameter['od'] / 2,
                    center=(0, 0),
                    startangle=0,
                    endangle=parameter['angle']))
        drawing.add(
            dxf.arc(radius=(parameter['id']) / 2,
                    center=(0, 0),
                    startangle=0,
                    endangle=parameter['angle']))
        drawing.add(
            dxf.polyline(points=[(parameter['od'] / 2,
                                  0), ((parameter['id']) / 2, 0)]))
        drawing.add(
            dxf.polyline(
                points=[((parameter['od']) / 2 *
                         math.cos(parameter['angle'] * math.pi / 180),
                         (parameter['od']) / 2 *
                         math.sin(parameter['angle'] * math.pi / 180)),
                        ((parameter['id']) / 2 *
                         math.cos(parameter['angle'] * math.pi / 180),
                         (parameter['id']) / 2 *
                         math.sin(parameter['angle'] * math.pi / 180))]))
    elif 'w' in parameter and 'l' in parameter:

        drawing.add(
            dxf.polyline(points=[(0, 0), (
                0, parameter['w']), (parameter['l'],
                                     parameter['w']), (parameter['l'],
                                                       0), (0, 0)]))
    else:
        print(file_name + '无对应图形')
        # 创建对应_厚度_的文件夹
    if not path.exists(address + '//' + '材料_' + material + '_厚度_' +
                       str(thickness)):
        #如果文件夹不存在创建
        mkdir(address + '//' + '材料_' + material + '_厚度_' + str(thickness))
    chdir(address + '\\材料_' + material + '_厚度_' + str(thickness))
    drawing.save()
Esempio n. 4
0
def arc_dxf(self, direction=True):
	radius = (self.centre - self.cutto).length()
	a = self.centre - self.cutto
	b = self.centre - self.cutfrom
	angle0 = math.atan2(a[1], a[0])/math.pi *180+180
	angle1 = math.atan2(b[1], b[0])/math.pi *180+180
        if(self.direction=='ccw'):
                return [dxf.arc(radius, self.centre, angle0, angle1)]
        else:
                return [dxf.arc(radius, self.centre, angle1, angle0)]
Esempio n. 5
0
class DXFPlato(Plato):
    """Plate renderer with DXF backend."""

    # DXF colours are specified as indexes in to a colour table.
    stroke_default = 7  # White
    stroke_alt = 6  # Magenta

    def __init__(self, file_path='out.dxf', **kwargs):
        """Create instance with this file name."""
        super(DXFPlato, self).__init__(**kwargs)
        self.drawing = dxf.drawing(file_path)

    def save(self):
        """Write to file."""
        self.drawing.save()

    def draw_roundrect(self,
                       (x, y),
                       (width, height),
                       radius,
                       color=stroke_default,
                       **kwargs):
        """Draw a rectangle with rounded corners."""
        left, right = x - 0.5 * width, x + 0.5 * width
        bottom, top = y - 0.5 * height, y + 0.5 * height

        self.drawing.add(
            dxf.line((left + radius, bottom), (right - radius, bottom),
                     color=color))
        self.drawing.add(
            dxf.arc(radius, (right - radius, bottom + radius),
                    270,
                    0,
                    color=color))
        self.drawing.add(
            dxf.line((right, bottom + radius), (right, top - radius),
                     color=color))
        self.drawing.add(
            dxf.arc(radius, (right - radius, top - radius), 0, 90,
                    color=color))
        self.drawing.add(
            dxf.line((left + radius, top), (right - radius, top), color=color))
        self.drawing.add(
            dxf.arc(radius, (left + radius, top - radius),
                    90,
                    180,
                    color=color))
        self.drawing.add(
            dxf.line((left, bottom + radius), (left, top - radius),
                     color=color))
        self.drawing.add(
            dxf.arc(radius, (left + radius, bottom + radius),
                    180,
                    270,
                    color=color))
Esempio n. 6
0
File: g2.py Progetto: soldocode/g2
 def writeDXF(self, dwg, pos=Point(0, 0)):
     if self.orientation > 0:
         dwg.add(
             dxf.arc(self.radius,
                     (self._center.x + pos.x, self._center.y + pos.y),
                     self.angleEnd.deg, self.angleStart.deg))
     else:
         dwg.add(
             dxf.arc(self.radius,
                     (self._center.x + pos.x, self._center.y + pos.y),
                     self.angleStart.deg, self.angleEnd.deg))
     return
Esempio n. 7
0
def arc_dxf(self, direction=True):
    if (hasattr(self, "parent") and hasattr(self.parent, 'z1')):
        colour = colour_from_z(self.parent.z1)
    else:
        colour = 1
    radius = (self.centre - self.cutto).length()
    a = self.centre - self.cutto
    b = self.centre - self.cutfrom
    angle0 = math.atan2(a[1], a[0]) / math.pi * 180 + 180
    angle1 = math.atan2(b[1], b[0]) / math.pi * 180 + 180
    if (self.direction == 'ccw'):
        return [dxf.arc(radius, self.centre, angle0, angle1, color=colour)]
    else:
        return [dxf.arc(radius, self.centre, angle1, angle0, color=colour)]
Esempio n. 8
0
def drawArcColouredLayer(draw, pxCentre, pyCentre, radio, AngIni, AngEnd,
                         colorA, capa):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx['color'] = colorA
    arcx['layer'] = capa
    draw.add(arcx)
    draw.add_layer(capa, color=colorA)
Esempio n. 9
0
def drawArcColouredAndThickness(draw, pxCentre, pyCentre, radio, AngIni, AngEnd, colorA, thicknes):
    # pre: thicknes float
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx["color"] = colorA
    arcx["thickness"] = thicknes
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorA)
Esempio n. 10
0
def drawArcColouredWithThickness(draw, pxCentre, pyCentre, radio, AngIni,
                                 AngEnd, colorA, thickness):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx['color'] = colorA
    arcx['thickness'] = thickness
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorA)
Esempio n. 11
0
 def hk(self, sx, sy, ex, ey):
     """halbkreis von sx, xy nach ex, ey, im uhrzeigersinn"""
     if sx == ex:
         cx = sx
         rp = (sy, ey)
         if sy > ey:
             sa = 270
             ea = 90
             cy = sy - ((sy - ey) / 2.0)
         else:
             sa = 90
             ea = 270
             cy = sy + ((ey - sy) / 2.0)
     elif sy == ey:
         cy = sy
         rp = (sx, ex)
         if sx > ex:
             sa = 0
             ea = 180
             cx = sx - ((sx - ex) / 2.0)
         else:
             sa = 180
             ea = 360
             cx = sx + ((ex - sx) / 2.0)
     else:
         raise ValueError("Halbkreis failed!")
     radius = abs(rp[0] - rp[1]) / 2.0
     cx = cx + self.x_off
     cy = cy + self.y_off
     self.drawing.add(
         dxf.arc(radius=radius,
                 center=(cx, cy),
                 startangle=sa,
                 endangle=ea,
                 layer='LINES'))
Esempio n. 12
0
 def arc(self, end, center, layer=None):
     if self.enable:
         r = xyDist(end, center)
         if self.svg is not None:
             self.path.push_arc(self.scaleOffset(end), 0, r, \
                                 large_arc=True, angle_dir='+', \
                                 absolute=True)
         if self.d is not None:
             if layer is None:
                 layer = self.lPath
             else:
                 if not layer in self.definedLayers:
                     self.definedLayers[layer] = True
                     self.d.add_layer(layer, color=self.color, lineweight=0)
             p0 = self.last
             p1 = end
             if xyDist(p0, p1) < MIN_DIST:
                 self.d.add(dxf.circle(r, center, layer=layer))
             else:
                 # dprt("p0 (%7.4f, %7.4f) p1 (%7.4f, %7.4f)" % \
                 #      (p0[0], p0[1], p1[0], p1[1]))
                 # if orientation(p0, center, p1) == CCW:
                 #     (p0, p1) = (p1, p0)
                 a0 = degrees(calcAngle(center, p0))
                 a1 = degrees(calcAngle(center, p1))
                 if a1 == 0.0:
                     a1 = 360.0
                 # dprt("a0 %5.1f a1 %5.1f" % (a0, a1))
                 self.d.add(dxf.arc(r, center, a0, a1, layer=layer))
             self.last = end
Esempio n. 13
0
 def hk(self, sx, sy, ex, ey):
     """halbkreis von sx, xy nach ex, ey, im uhrzeigersinn"""
     if sx == ex:
         cx = sx
         rp = (sy, ey)
         if sy > ey:
             sa = 270
             ea = 90
             cy = sy - ((sy - ey) / 2.0)
         else:
             sa = 90
             ea = 270
             cy = sy + ((ey - sy) / 2.0)
     elif sy == ey:
         cy = sy
         rp = (sx, ex)
         if sx > ex:
             sa = 0
             ea = 180
             cx = sx - ((sx - ex) / 2.0)
         else:
             sa = 180
             ea = 360
             cx = sx + ((ex - sx) / 2.0)
     else:
         raise ValueError("Halbkreis failed!")
     radius = abs(rp[0] - rp[1]) / 2.0
     cx = cx + self.x_off
     cy = cy + self.y_off
     self.drawing.add(dxf.arc(radius=radius, center=(cx, cy),
                              startangle=sa, endangle=ea, layer='LINES'))
Esempio n. 14
0
def outline_arc_line_with_dxfwrite(ai_segments, ai_outline_closed):
    """ Generates the arcs and lines outline with the mozman dxfwrite
  """
    dxf_points = [tuple((ai_segments[0][0], ai_segments[0][1]))]
    segment_nb = len(ai_segments) - 1
    dxf_outline = []
    for i in range(segment_nb):
        segment_type = 'line'
        dxf_points.append(tuple(
            (ai_segments[i + 1][0], ai_segments[i + 1][1])))
        point_start = dxf_points[-2]
        point_end = dxf_points[-1]
        if (len(ai_segments[i + 1]) == 4):
            segment_type = 'arc'
            dxf_points.append(
                tuple((ai_segments[i + 1][2], ai_segments[i + 1][3])))
            point_start = dxf_points[-3]
            point_mid = dxf_points[-2]
            point_end = dxf_points[-1]
        if (i == segment_nb - 1):
            #print("dbg306: last segment")
            if (ai_outline_closed):
                #print("dbg307: close")
                point_end = dxf_points[0]
        #print("dbg563: i: {:d}  segment: {:s}".format(i, segment_type))
        if (segment_type == 'line'):
            #dxf_line = DXFEngine.line(start=point_start, end=point_end, color=7, layer=default_dxf_layer_name)
            dxf_line = DXFEngine.line(start=point_start, end=point_end)
            dxf_outline.append(dxf_line)
        elif (segment_type == 'arc'):
            (lia, ptix, ptiy, u, v, w, uv, vw,
             uw) = arc_3_points_to_radius_center_angles(
                 point_start, point_mid, point_end)
            u2 = u
            w2 = u + uw
            if (uw < 0):
                #w2 = u + uw + 2*math.pi
                u2 = w
                w2 = u
            #print("dbg384: lia {:0.3f}  ptix {:0.3f}  ptiy {:0.3f}  u2 {:0.3f}  w2 {:0.3f}".format(lia, ptix, ptiy, u2*180/math.pi, w2*180/math.pi))
            if (
                    lia == 0
            ):  # when arc_3_points_to_radius_center_angles found that the 3 points are too colinear
                dxf_arc = DXFEngine.line(start=point_start, end=point_end)
            else:
                dxf_arc = DXFEngine.arc(lia, (ptix, ptiy), u2 * 180 / math.pi,
                                        w2 * 180 / math.pi)
            dxf_outline.append(dxf_arc)
            #arc_polyline = arc_of_circle(point_start, point_mid, point_end, unit_circle_resolution)
            #arc_polyline_dxf = []
            #for i in arc_polyline:
            #  arc_polyline_dxf.append(tuple(i))
            ##dxf_polyline = DXFEngine.polyline(arc_polyline_dxf, color=7, layer=default_dxf_layer_name)
            ##dxf_polyline = DXFEngine.polyline(arc_polyline_dxf, flags=DXFEngine.POLYLINE_3D_POLYLINE)
            #dxf_polyline = DXFEngine.polyline(arc_polyline_dxf)
            #dxf_outline.append(dxf_polyline)
    r_outline = dxf_outline
    return (r_outline)
Esempio n. 15
0
 def draw_crowns(self, d):
     """draw all crowns"""
     start = r2d(self.seg_crown[0])
     end = r2d(self.seg_crown[1])
     delta = r2d(self.ap)
     for i in range(self.n):
         d.add(dxf.arc(self.ar, (0.0, 0.0), start, end))
         start += delta
         end += delta
Esempio n. 16
0
 def draw_roots(self, d):
     """draw all the roots"""
     start = r2d(self.seg_root[0])
     end = r2d(self.seg_root[1])
     delta = r2d(self.ap)
     for i in range(self.n):
         d.add(dxf.arc(self.dr, (0.0, 0.0), start, end))
         start += delta
         end += delta
 def new_arc(self, s, e, layer='gearteeth', r=None, color = 0):
     if r == None:
         r = abs(s)    
     sa = phase(s)
     ea = phase(e)
     return dxf.arc(radius = r,
                    startangle=degrees(sa),
                    endangle=degrees(ea),
                    layer = layer, thickness=0.0)
Esempio n. 18
0
 def _arc(self, radius, a1, a2):
     if self._pen_down:
         self.dwg.add(dxf.arc(
             radius=radius,
             center=(self.x, self.y),
             startangle=a1,
             endangle=a2,
             layer=self.name,
         ))
    def cutOutRectangle(self, cx, cy, width, length, bit_diameter, cutx, cuty):

        ## copy class parameters
        drawing = self.drawing

        ## draw both x-lines
        ##  shorten lines appropriately, if cutx set to 1 == yes
        drawing.add(
            dxf.line((cx + cutx * bit_diameter, cy),
                     (cx + width - cutx * bit_diameter, cy)))
        drawing.add(
            dxf.line((cx + cutx * bit_diameter, cy + length),
                     (cx + width - cutx * bit_diameter, cy + length)))

        ## draw both y-lines
        ##  shorten lines appropriately, if cutx set to 1 == yes
        drawing.add(
            dxf.line((cx, cy + cuty * bit_diameter),
                     (cx, cy + length - cuty * bit_diameter)))
        drawing.add(
            dxf.line((cx + width, cy + cuty * bit_diameter),
                     (cx + width, cy + length - cuty * bit_diameter)))

        ## draw the dog-ears for both x-lines, if wanted
        if cutx == 1:
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx + bit_diameter / 2, cy), 180,
                        360))
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx + width - bit_diameter / 2, cy),
                        180, 360))
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx + bit_diameter / 2, cy + length),
                        360, 180))
            drawing.add(
                dxf.arc(bit_diameter / 2,
                        (cx + width - bit_diameter / 2, cy + length), 360,
                        180))

        ## draw the dog-ears for both y-lines, if wanted
        if cuty == 1:
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx, cy + bit_diameter / 2), 90,
                        270))
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx, cy + length - bit_diameter / 2),
                        90, 270))
            drawing.add(
                dxf.arc(bit_diameter / 2, (cx + width, cy + bit_diameter / 2),
                        270, 90))
            drawing.add(
                dxf.arc(bit_diameter / 2,
                        (cx + width, cy + length - bit_diameter / 2), 270, 90))
Esempio n. 20
0
    def draw_lobes(self, d):

        nf1 = circle2circle(self.nose, self.flank1)[0]
        nf2 = circle2circle(self.nose, self.flank2)[0]
        bf1 = circle2circle(self.base, self.flank1)[0]
        bf2 = circle2circle(self.base, self.flank2)[0]

        n_theta1 = r2d(self.nose.p2r(nf1))
        n_theta2 = r2d(self.nose.p2r(nf2))
        d.add(dxf.arc(self.nose.r, self.nose.c, n_theta1, n_theta2))

        b_theta1 = r2d(self.base.p2r(bf1))
        b_theta2 = r2d(self.base.p2r(bf2))
        d.add(dxf.arc(self.base.r, self.base.c, b_theta2, b_theta1))

        f1_theta1 = r2d(self.flank1.p2r(nf1))
        f1_theta2 = r2d(self.flank1.p2r(bf1))
        d.add(dxf.arc(self.flank1.r, self.flank1.c, f1_theta2, f1_theta1))

        f2_theta1 = r2d(self.flank2.p2r(nf2))
        f2_theta2 = r2d(self.flank2.p2r(bf2))
        d.add(dxf.arc(self.flank2.r, self.flank2.c, f2_theta1, f2_theta2))
Esempio n. 21
0
def outline_arc_line_with_dxfwrite(ai_segments, ai_outline_closed):
  """ Generates the arcs and lines outline with the mozman dxfwrite
  """
  dxf_points = [tuple((ai_segments[0][0], ai_segments[0][1]))]
  segment_nb = len(ai_segments)-1
  dxf_outline = []
  for i in range(segment_nb):
    segment_type = 'line'
    dxf_points.append(tuple((ai_segments[i+1][0], ai_segments[i+1][1])))
    point_start = dxf_points[-2]
    point_end = dxf_points[-1]
    if(len(ai_segments[i+1])==4):
      segment_type = 'arc'
      dxf_points.append(tuple((ai_segments[i+1][2], ai_segments[i+1][3])))
      point_start = dxf_points[-3]
      point_mid = dxf_points[-2]
      point_end = dxf_points[-1]
    if(i==segment_nb-1):
      #print("dbg306: last segment")
      if(ai_outline_closed):
        #print("dbg307: close")
        point_end = dxf_points[0]
    #print("dbg563: i: {:d}  segment: {:s}".format(i, segment_type))
    if(segment_type=='line'):
      #dxf_line = DXFEngine.line(start=point_start, end=point_end, color=7, layer=default_dxf_layer_name)
      dxf_line = DXFEngine.line(start=point_start, end=point_end)
      dxf_outline.append(dxf_line)
    elif(segment_type=='arc'):
      (lia, ptix, ptiy, u, v, w, uv, vw, uw) = arc_3_points_to_radius_center_angles(point_start, point_mid, point_end)
      u2 = u
      w2 = u + uw
      if(uw<0):
        #w2 = u + uw + 2*math.pi
        u2 = w
        w2 = u
      #print("dbg384: lia {:0.3f}  ptix {:0.3f}  ptiy {:0.3f}  u2 {:0.3f}  w2 {:0.3f}".format(lia, ptix, ptiy, u2*180/math.pi, w2*180/math.pi))
      if(lia==0): # when arc_3_points_to_radius_center_angles found that the 3 points are too colinear
        dxf_arc = DXFEngine.line(start=point_start, end=point_end)
      else:
        dxf_arc = DXFEngine.arc(lia, (ptix, ptiy), u2*180/math.pi, w2*180/math.pi)
      dxf_outline.append(dxf_arc)
      #arc_polyline = arc_of_circle(point_start, point_mid, point_end, unit_circle_resolution)
      #arc_polyline_dxf = []
      #for i in arc_polyline:
      #  arc_polyline_dxf.append(tuple(i))
      ##dxf_polyline = DXFEngine.polyline(arc_polyline_dxf, color=7, layer=default_dxf_layer_name)
      ##dxf_polyline = DXFEngine.polyline(arc_polyline_dxf, flags=DXFEngine.POLYLINE_3D_POLYLINE)
      #dxf_polyline = DXFEngine.polyline(arc_polyline_dxf)
      #dxf_outline.append(dxf_polyline)
  r_outline = dxf_outline
  return(r_outline)
Esempio n. 22
0
def drawArcColouredLayer(draw, pxCentre, pyCentre, radio, AngIni, AngEnd, colorA, capa):
	arcx = dxf.arc(radio, (pxCentre,pyCentre), AngIni, AngEnd)
	arcx['color'] = colorA
	arcx['layer'] = capa
	draw.add(arcx)
	draw.add_layer(capa, color=colorA)
	#set value
	draw.header['$ANGBASE'] = 90.0
	draw.header['$ANGDIR'] = 1
	#get value
	contrareloj = draw.header['$ANGDIR'].value
	print ('el valor de direccion del Angulo es: ',contrareloj)
	anguloBase = draw.header['$ANGBASE'].value
	print ('elvalor del angulo base es:',anguloBase)
Esempio n. 23
0
def drawArcColouredLayer(draw, pxCentre, pyCentre, radio, AngIni, AngEnd,
                         colorA, capa):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx['color'] = colorA
    arcx['layer'] = capa
    draw.add(arcx)
    draw.add_layer(capa, color=colorA)
    #set value
    draw.header['$ANGBASE'] = 90.0
    draw.header['$ANGDIR'] = 1
    #get value
    contrareloj = draw.header['$ANGDIR'].value
    print('el valor de direccion del Angulo es: ', contrareloj)
    anguloBase = draw.header['$ANGBASE'].value
    print('elvalor del angulo base es:', anguloBase)
Esempio n. 24
0
    def drawPath(self,
                 outlines=mePath.Outline(),
                 xy=[0,0],
                 layer=-1):
        
                     
        self.Paths.append(outlines)#???
        lay=layer
        path=outlines.Path
        n=outlines.Nodes
        d=self.DXFDrawing
        rx=xy[0]
        ry=xy[1]

        for c in path:
         if c[0]=='line':
            d.add(dxf.line((rx+n[c[1]][0],ry+n[c[1]][1]),
                           (rx+n[c[2]][0],ry+n[c[2]][1]),layer=lay))
         elif c[0]=='arc':
            cr=geo.CircleFrom3Points(n[c[1]],n[c[3]],n[c[2]])
            if cr['Direction']<0:
                d.add(dxf.arc(center=(rx+cr['Center'][0],ry+cr['Center'][1]),
                              radius=cr['Radius'],
                              startangle=math.degrees(cr['P1Degree']),
                              endangle=math.degrees(cr['P3Degree']),
                              layer=lay))
            else:    
                d.add(dxf.arc(center=(rx+cr['Center'][0],ry+cr['Center'][1]),
                              radius=cr['Radius'],
                              startangle=math.degrees(cr['P3Degree']),
                              endangle=math.degrees(cr['P1Degree']),
                              layer=lay))
            
         elif c[0]=='circle':
            rds=n[c[2]][0]-n[c[1]][0]
            d.add(dxf.circle(rds,(rx+n[c[1]][0],ry+n[c[1]][1]),layer=lay))
Esempio n. 25
0
    def draw_dxf(self, name):
        drawing = dxf.drawing(name)
        for shape in self.shapes:
            dxfshape = None
            layrow = shape.index % 2
            laycolumn = shape.index / 2
            offset_x = -self.horizontal_compress * laycolumn
            offset_y = (self.mirror_shift - self.vertical_compress) * layrow
            offset_vector = Vector(offset_x, offset_y)

            if isinstance(shape, Line):
                start = shape.start.add(offset_vector).coords()
                end = shape.end.add(offset_vector).coords()
                dxfshape = dxf.line(start, end)

            if isinstance(shape, Arc):
                center = shape.center.add(offset_vector).coords()
                start = math.degrees(shape.start)
                end = math.degrees(shape.start + shape.angle)
                dxfshape = dxf.arc(shape.radius, center, start, end)

            if dxfshape != None:
                drawing.add(dxfshape)
        drawing.save()
Esempio n. 26
0
    def drawfigure(self):
        #  cretae file

        filename = 'model.dxf'
        drawing = dxf.drawing(filename)
        #  создаём объект
        nameobj = self.model
        nameobj = nameobj.replace('-', '')
        nameobj = nameobj.lower()
        # print (nameobj)
        figureobj = globals().get(nameobj)()
        #  подготавливаем объект ПЕРЕДАЁМ ПАРАМЕТРЫ
        figureobj.width = float(self.width)
        figureobj.height = float(self.height)
        figureobj.deep = float(self.deep)
        figureobj.thickness = float(self.thickness)

        if hasattr(figureobj,
                   'clearance'):  # есть атрибут отступ,  для псевдофрезы
            figureobj.clearance = float(self.clearance)

        figureobj.compute(
        )  # float(self.lf),  float(self.tf),  float(self.rf),  float(self.bf) )
        # обработка линий в цикле
        for X in range(1, 49):
            drawing.add_layer('SIDER', color=1, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, layer='SIDER')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='SIDER')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='SIDER')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='SIDER')
                drawing.add(linecyc)
                # line = dxf.line((1.2,  3.7),  (5.5,  9.7),  layer='LINES')

        #  чертим переднюю стенку
        for X in range(50, 99):
            drawing.add_layer('SIDEL', color=1, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, layer='SIDEL')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='SIDEL')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='SIDEL')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='SIDEL')
                drawing.add(linecyc)
                # line = dxf.line((1.2,  3.7),  (5.5,  9.7),  layer='LINES')

        # фигура крышки
        for X in range(100, 149):
            drawing.add_layer('TOP', color=7, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, color=7, layer='TOP')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='TOP')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='TOP')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='TOP')
                drawing.add(linecyc)
        # фигура дно
        for X in range(150, 199):
            drawing.add_layer('BOTTOM', color=3, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, layer='BOTTOM')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='BOTTOM')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='BOTTOM')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='BOTTOM')
                drawing.add(linecyc)
        # фигура  днa
        for X in range(200, 249):
            drawing.add_layer('FACE', color=3, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, layer='FACE')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='FACE')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='FACE')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='FACE')
                drawing.add(linecyc)
        # фигура  днa
        for X in range(250, 299):
            drawing.add_layer('ANFACE', color=3, linetype='SOLID')
            # vt = ('l%dx' % X)
            #  прямоугольникик в цикле
            if hasattr(figureobj, ('r%dx' % X)):  # есть прямоугольник
                rx = getattr(figureobj, ('r%dx' % X))
                ry = getattr(figureobj, ('r%dy' % X))
                rw = getattr(figureobj, ('r%dw' % X))
                rh = getattr(figureobj, ('r%dh' % X))
                rect = dxf.rectangle((rx, ry), rw, rh, layer='ANFACE')
                drawing.add(rect)
            if hasattr(figureobj, ('c%dx' % X)):  # есть окружность

                cx = getattr(figureobj, ('c%dx' % X))
                cy = getattr(figureobj, ('c%dy' % X))
                cr = getattr(figureobj, ('c%dr' % X))

                circle = dxf.circle(cr, (cx, cy), layer='ANFACE')
                drawing.add(circle)
            #  есть дуга для псевдо
            if hasattr(figureobj, ('arc%dx' % X)):  # есть дуга
                arcx = getattr(figureobj, ('arc%dx' % X))
                arcy = getattr(figureobj, ('arc%dy' % X))
                arcr = getattr(figureobj, ('arc%dr' % X))
                arcsa = getattr(figureobj, ('arc%dsangle' % X))
                arcse = getattr(figureobj, ('arc%deangle' % X))
                # рисум прямоугольник псевдофрезы
                arc = dxf.arc(arcr, (arcx, arcy), arcsa, arcse, layer='ANFACE')
                drawing.add(arc)
            #  линии в цикле
            if hasattr(figureobj, ('l%dx' % X)):  # есть линия
                lx = getattr(figureobj, ('l%dx' % X))
                ly = getattr(figureobj, ('l%dy' % X))
                lx1 = getattr(figureobj, ('l%dx1' % X))
                ly1 = getattr(figureobj, ('l%dy1' % X))
                # print(lx,  ly,  lx1,  ly1)
                linecyc = dxf.line((lx, ly), (lx1, ly1), layer='ANFACE')
                drawing.add(linecyc)
#   записываем в файл
        drawing.save()
def export_via_dxfwrite(  dxf_fn, V):
    from XMLlib import SvgXMLTreeNode
    from svgLib_dd import SvgTextParser, SvgPath, SvgPolygon
    from numpy import arctan2
    from circleLib import fitCircle_to_path, findCircularArcCentrePoint, pointsAlongCircularArc
    from dxfwrite import DXFEngine as dxf
    drawing = dxf.drawing( dxf_fn)
    
    pageSvg = open(V.page.PageResult).read()
    XML_tree =  SvgXMLTreeNode( pageSvg,0)
    def yT(y): #y transform
        return 210-y
    warningsShown = []
    SelectViewObjectPoint_loc = None
    for element in XML_tree.getAllElements():
        clr_text = None        
        if element.parms.has_key('fill'):
            clr_text =  element.parms['fill']
        elif element.parms.has_key('style'):
            for part in element.parms['style'].split(';'):
                if part.startswith('stroke:rgb('):
                    clr_text = part[ len('stroke:'):]
        if clr_text == None or clr_text =='none' or not clr_text.startswith('rgb(') :
            color_code = 0
        else:
            #FreeCAD.Console.PrintMessage( "color text: %s\n" % clr_text )
            r,g,b = [ int(v.strip()) for v in clr_text[ len('rgb('): clr_text.find(')')].split(',') ]
            color_code = colorLookup(r,g,b)[0]
        if element.tag == 'circle':
            x, y = element.applyTransforms( float( element.parms['cx'] ), float( element.parms['cy'] ) )
            r =  float( element.parms['r'] )* element.scaling2()
            drawing.add( dxf.circle( r, (x,yT(y)), color=color_code) )
        elif element.tag == 'line':
            x1, y1 = element.applyTransforms( float( element.parms['x1'] ), float( element.parms['y1'] ) )
            x2, y2 = element.applyTransforms( float( element.parms['x2'] ), float( element.parms['y2'] ) )
            drawing.add( dxf.line( (x1, yT(y1)), (x2, yT(y2)), color=color_code ) )
        elif element.tag == 'text' and element.parms.has_key('x'):
            x,y = element.applyTransforms( float( element.parms['x'] ), float( element.parms['y'] ) )
            try:
                t = SvgTextParser(element.XML[element.pStart: element.pEnd ] )
                drawing.add(dxf.text( t.text, insert=(x, yT(y)), height=t.height()*0.8, rotation=t.rotation, layer='TEXTLAYER', color=color_code) )
            except ValueError, msg:
                FreeCAD.Console.PrintWarning('dxf_export: unable to convert text element "%s": %s, ignoring...\n' % (element.XML[element.pStart: element.pEnd ], str(msg) ) )
        elif element.tag == 'path': 
            #FreeCAD.Console.PrintMessage(element.parms['d']+'\n')
            path = SvgPath( element )
            for line in path.lines:
                drawing.add( dxf.line( (line.x1, yT(line.y1)), (line.x2,yT(line.y2)), color=color_code) ) 
            for arc in path.arcs:
                if arc.circular:
                    for r, center, angle1, angle2 in arc.dxfwrite_arc_parms( yT ):
                        drawing.add( dxf.arc( r, center, angle1, angle2 , color=color_code) )
                else:
                    for x1,y1,x2,y2 in arc.approximate_via_lines( 12 ):
                        drawing.add( dxf.line( (x1, yT(y1)), (x2, yT(y2)), color=color_code) )
            for bezierCurve in path.bezierCurves:
                x, y, r, r_error = bezierCurve.fitCircle()
                if r_error < 10**-4:
                    raise NotImplementedError
                    drawing.add( dxf.arc( *bezierCurve.dxfwrite_arc_parms(x, y, r) ) )
                else:
                    X,Y = bezierCurve.points_along_curve()
                    for i in range(len(X) -1):
                        drawing.add( dxf.line( (X[i], yT(Y[i])), (X[i+1],yT(Y[i+1])), color=color_code ) )
Esempio n. 28
0
def drawArcColouredWithThickness(draw, pxCentre, pyCentre, radio, AngIni, AngEnd,colorA,thickness):
	arcx = dxf.arc(radio, (pxCentre,pyCentre), AngIni, AngEnd)
	arcx['color'] = colorA
	arcx['thickness'] = thickness
	draw.add(arcx)
	draw.add_layer(currentLayer, color=colorA)
    def drawGridPart(self, start_x, start_y, x, z, number_of_compartments):

        ## copy class parameters
        thickness = self.thickness
        bit_diameter = self.bit_diameter
        drawing = self.drawing

        ## calculate finger lengths
        ##  length of divider - ((number of divisions - 1) * thickness of the material) / number of divisions
        length_of_division = float(x - (number_of_compartments - 1) *
                                   thickness) / number_of_compartments

        ## draw the lower line with interruptions
        ##   the same has to be applied for the other direction
        for j in range(0, number_of_compartments - 1):

            ## first dog-ears-variant: draw them to the top
            if (False):
                ## draw the finger line, depending on x or y direction and length
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x + length_of_division, start_y)))
                start_x += length_of_division
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x, start_y + float(z) / 2)))
                start_y += float(z) / 2
                ## add the dog-ears here!
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x + float(bit_diameter) / 2, start_y), 0, 180))
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x + thickness - float(bit_diameter) / 2,
                         start_y), 0, 180))
                ## skip connection line, if thickness not large enough (eliminate dots)
                if thickness > 2 * bit_diameter:
                    drawing.add(
                        dxf.line(
                            (start_x + bit_diameter, start_y),
                            (start_x + thickness - bit_diameter, start_y)))
                ## but continue anyway
                start_x += thickness
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x, start_y - float(z) / 2)))
                start_y -= float(z) / 2

            ## second dog-ears-variant: draw them to the side
            if (False):
                ## draw the finger line, depending on x or y direction and length
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x + length_of_division, start_y)))
                start_x += length_of_division
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x, start_y + float(z) / 2 - bit_diameter)))
                start_y += float(z) / 2
                ## add the dog-ears here!
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x, start_y - float(bit_diameter) / 2), 90, 270))
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x + thickness,
                         start_y - float(bit_diameter) / 2), 270, 90))
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x + thickness, start_y)))
                ## but continue anyway
                start_x += thickness
                drawing.add(
                    dxf.line((start_x, start_y - bit_diameter),
                             (start_x, start_y - float(z) / 2)))
                start_y -= float(z) / 2

            ### draw diagonal dog-ears
            if (True):
                ## draw the finger line, depending on x or y direction and length
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x + length_of_division, start_y)))
                start_x += length_of_division
                # shorten up-line by dog-ear
                drawing.add(
                    dxf.line((start_x, start_y),
                             (start_x, start_y + float(z) / 2 -
                              math.sqrt(2) / 2 * bit_diameter)))
                start_y += float(z) / 2
                # draw diagonal dog ears
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x + math.sqrt(2) / 4 * bit_diameter,
                         start_y - math.sqrt(2) / 4 * bit_diameter), 45, 225))
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (start_x + thickness - math.sqrt(2) / 4 * bit_diameter,
                         start_y - math.sqrt(2) / 4 * bit_diameter), 315, 135))
                # draw dog-ear-connection line + add thickness to position of cursor_x
                drawing.add(
                    dxf.line(
                        (start_x + math.sqrt(2) / 2 * bit_diameter, start_y),
                        (start_x + thickness - math.sqrt(2) / 2 * bit_diameter,
                         start_y)))
                start_x += thickness
                # draw a line downwards
                drawing.add(
                    dxf.line(
                        (start_x, start_y - math.sqrt(2) / 2 * bit_diameter),
                        (start_x, start_y - float(z) / 2)))
                start_y -= float(z) / 2

        ## draw last line to the right
        drawing.add(
            dxf.line((start_x, start_y),
                     (start_x + length_of_division, start_y)))
        start_x += length_of_division
        ## draw line up
        drawing.add(dxf.line((start_x, start_y), (start_x, start_y + z)))
        start_y += z
        # replace above line with this to create outer edge
        #    drawOneSide(start_x+thickness,start_y,2,0,1,z,thickness,0,0,0);  start_y+=z

        ## draw long line to-the-left
        drawing.add(dxf.line((start_x, start_y), (start_x - x, start_y)))
        start_x -= x
        ## draw final down line
        drawing.add(dxf.line((start_x, start_y), (start_x, start_y - z)))
        start_y -= z
Esempio n. 30
0
def drawArcFMC(draw, pxCentre, pyCentre, radio, AngIni, AngEnd):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx['color'] = colorLine
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorLine)
Esempio n. 31
0
def drawArcColoured(draw, pxCentre, pyCentre, radio, AngIni, AngEnd, colorA):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx['color'] = colorA
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorA)
Esempio n. 32
0
        '*ACTIVE',
        center_point=(10,10),
        height = 30,
    )

# add LINE-entity
drawing.add(dxf.line((0,0),( 10,0),
    color=dxfwrite.BYLAYER,
    layer='dxfwrite'
))

# add a CIRCLE-entity
drawing.add(dxf.circle(center=(5,0), radius=5))

# add an ARC-entity
drawing.add(dxf.arc(center=(5,0), radius=4, startangle=30, endangle=150))

#add a POINT-entity
drawing.add(dxf.point(point=(1,1)))

# add a SOLID-entity with 4 points
drawing.add(dxf.solid([(0,0), (1,0), (1,1), (0,1)], color=2))

# add a SOLID-entity with 3 points
drawing.add(dxf.solid([(0,1), (1,1), (1,2)], color=3))

# add a 3DFACE-entity
drawing.add(dxf.face3d([(5,5), (6,5), (6,6), (5,6)], color=3))

# add a Trace-entity
drawing.add(dxf.trace([(7,5), (8,5), (8,6), (7,6)], color=4))
# text size
textsize = 2.5

# arrows/lines function
def dim12_arrow(u1, u2, u3, u4, l1, l2, l3, l4, c1, c2, c3, c4):
    drawing.add(dxf.line((c1, c2), (c3, c4)))
    drawing.add(dxf.line((u1, u2), (u3, u4)))
    drawing.add(dxf.line((l1, l2), (l3, l4)))

def dim8_arrow(u11, u12, u13, u14, l11, l12, l13, l14):
    drawing.add(dxf.line((u11, u12), (u13, u14)))
    drawing.add(dxf.line((l11, l12), (l13, l14)))

def dim5_arrow(r1, (c1, c2), st1, ed1):
    drawing.add(dxf.arc(r1, (c1, c2), st1, ed1))

def dim4_arrow(l21, l22, l23, l24):
    drawing.add(dxf.line((l21, l22), (l23, l24)))

def atrace(t1, t2, t3, t4, t5, t6):
    drawing.add(dxf.trace([(t1, t2), (t3, t4), (t5, t6)]))

# input file
f=open('Sloped footing(b).csv')
lst={'A':'','D':'','a':'','Dm':''}
data=[row for row in csv.reader(f)]
for i in lst.keys():
    for j in range(len(data)):
            if(i==data[j][0]):
                    ans=data[j][1]
        for l in range(track_points-1):

            # Calculate bearing from point 0 to point 1
            b01 = (numpy.pi / 2.) - numpy.arctan2(north[l+1] - north[l], east[l+1] - east[l])

            # Create two points on a line parallel to the one running from point 0 to point 1
            x1 = east[l] + ((track_width / 4.) * numpy.cos(b01))
            y1 = north[l] - ((track_width / 4.) * numpy.sin(b01))
            x2 = east[l+1] + ((track_width / 4.) * numpy.cos(b01))
            y2 = north[l+1] - ((track_width / 4.) * numpy.sin(b01))

            # First line
            drawing.add(dxf.line((x1,y1),(x2,y2),color=1))
            # First arc
            drawing.add(dxf.arc((track_width / 4.),(east[l+1],north[l+1]),numpy.degrees(0.-b01),numpy.degrees(numpy.pi-b01),color=1))
            
            # Now do it again creating a line on the other side of the track
            x3 = east[l+1] - ((track_width / 4.) * numpy.cos(b01))
            y3 = north[l+1] + ((track_width / 4.) * numpy.sin(b01))
            x4 = east[l] - ((track_width / 4.) * numpy.cos(b01))
            y4 = north[l] + ((track_width / 4.) * numpy.sin(b01))

            # Second line
            drawing.add(dxf.line((x3,y3),(x4,y4),color=1))
            # Second arc
            drawing.add(dxf.arc((track_width / 4.),(east[l],north[l]),numpy.degrees(numpy.pi-b01),numpy.degrees(0.-b01),color=1))
            # Repeat first line (possibly redundant?)
            drawing.add(dxf.line((x1,y1),(x2,y2),color=1))

        # Write data to dxf file
Esempio n. 35
0
def export_via_dxfwrite(dxf_fn, V):
    from XMLlib import SvgXMLTreeNode
    from svgLib_dd import SvgTextParser, SvgPath, SvgPolygon
    from numpy import arctan2
    from circleLib import fitCircle_to_path, findCircularArcCentrePoint, pointsAlongCircularArc
    from dxfwrite import DXFEngine as dxf
    drawing = dxf.drawing(dxf_fn)

    pageSvg = open(V.page.PageResult).read()
    XML_tree = SvgXMLTreeNode(pageSvg, 0)

    def yT(y):  #y transform
        return 210 - y

    warningsShown = []
    SelectViewObjectPoint_loc = None
    for element in XML_tree.getAllElements():
        clr_text = None
        if element.parms.has_key('fill'):
            clr_text = element.parms['fill']
        elif element.parms.has_key('style'):
            for part in element.parms['style'].split(';'):
                if part.startswith('stroke:rgb('):
                    clr_text = part[len('stroke:'):]
        if clr_text == None or clr_text == 'none' or not clr_text.startswith(
                'rgb('):
            color_code = 0
        else:
            #FreeCAD.Console.PrintMessage( "color text: %s\n" % clr_text )
            r, g, b = [
                int(v.strip())
                for v in clr_text[len('rgb('):clr_text.find(')')].split(',')
            ]
            color_code = colorLookup(r, g, b)[0]
        if element.tag == 'circle':
            x, y = element.applyTransforms(float(element.parms['cx']),
                                           float(element.parms['cy']))
            r = float(element.parms['r']) * element.scaling2()
            drawing.add(dxf.circle(r, (x, yT(y)), color=color_code))
        elif element.tag == 'line':
            x1, y1 = element.applyTransforms(float(element.parms['x1']),
                                             float(element.parms['y1']))
            x2, y2 = element.applyTransforms(float(element.parms['x2']),
                                             float(element.parms['y2']))
            drawing.add(dxf.line((x1, yT(y1)), (x2, yT(y2)), color=color_code))
        elif element.tag == 'text' and element.parms.has_key('x'):
            x, y = element.applyTransforms(float(element.parms['x']),
                                           float(element.parms['y']))
            try:
                t = SvgTextParser(element.XML[element.pStart:element.pEnd])
                drawing.add(
                    dxf.text(t.text,
                             insert=(x, yT(y)),
                             height=t.height() * 0.8,
                             rotation=t.rotation,
                             layer='TEXTLAYER',
                             color=color_code))
            except ValueError, msg:
                FreeCAD.Console.PrintWarning(
                    'dxf_export: unable to convert text element "%s": %s, ignoring...\n'
                    % (element.XML[element.pStart:element.pEnd], str(msg)))
        elif element.tag == 'path':
            #FreeCAD.Console.PrintMessage(element.parms['d']+'\n')
            path = SvgPath(element)
            for line in path.lines:
                drawing.add(
                    dxf.line((line.x1, yT(line.y1)), (line.x2, yT(line.y2)),
                             color=color_code))
            for arc in path.arcs:
                if arc.circular:
                    for r, center, angle1, angle2 in arc.dxfwrite_arc_parms(
                            yT):
                        drawing.add(
                            dxf.arc(r,
                                    center,
                                    angle1,
                                    angle2,
                                    color=color_code))
                else:
                    for x1, y1, x2, y2 in arc.approximate_via_lines(12):
                        drawing.add(
                            dxf.line((x1, yT(y1)), (x2, yT(y2)),
                                     color=color_code))
            for bezierCurve in path.bezierCurves:
                x, y, r, r_error = bezierCurve.fitCircle()
                if r_error < 10**-4:
                    raise NotImplementedError
                    drawing.add(
                        dxf.arc(*bezierCurve.dxfwrite_arc_parms(x, y, r)))
                else:
                    X, Y = bezierCurve.points_along_curve()
                    for i in range(len(X) - 1):
                        drawing.add(
                            dxf.line((X[i], yT(Y[i])),
                                     (X[i + 1], yT(Y[i + 1])),
                                     color=color_code))
Esempio n. 36
0
def drawArcColoured(draw, pxCentre, pyCentre, radio, AngIni, AngEnd, colorA):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx["color"] = colorA
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorA)
Esempio n. 37
0
drawing.add_layer('bend', color=2)
drawing.add_layer('calibrate', color=3)
drawing.add_layer('drill', color=4)

# rounded rectangle radius
rrr = 2.0

# full panel outline
drawing.add(dxf.line((rrr, 0.0), (h - rrr, 0.0)))
drawing.add(dxf.line((rrr, w), (h - rrr, w)))
drawing.add(dxf.line((0.0, rrr), (0.0, w - rrr)))
drawing.add(dxf.line((h, rrr), (h, w - rrr)))

# edge corners rounded
drawing.add(dxf.arc(rrr, center=(rrr, rrr), startangle=180.0, endangle=270.0))
drawing.add(
    dxf.arc(rrr, center=(rrr, w - rrr), startangle=90.0, endangle=180.0))
drawing.add(dxf.arc(rrr, center=(h - rrr, rrr), startangle=270.0,
                    endangle=0.0))
drawing.add(
    dxf.arc(rrr, center=(h - rrr, w - rrr), startangle=0.0, endangle=90.0))

# lcd hole
drawing.add(dxf.rectangle((lx, ly - t), lh, lw))

# pot holes
circle_ch(volr, volx, voly - t)
circle_ch(tunr, tunx, tuny - t)

# Kenwood-style 2 pin jack holes
Esempio n. 38
0
 def append_to_dxf(self, drawing):
     drawing.add(
         dxf.arc(self.radius, (self.center[0], -self.center[1]),
                 self.start_angle * 180 / math.pi,
                 self.end_angle * 180 / math.pi))
def export_via_dxfwrite(  dxf_fn, V):
    from drawingDimensioning.XMLlib import SvgXMLTreeNode
    from drawingDimensioning.svgLib import SvgTextParser, SvgPath, SvgPolygon
    from drawingDimensioning.circleLib import fitCircle_to_path, findCircularArcCentrePoint, pointsAlongCircularArc
    from numpy import arctan2
    from dxfwrite import DXFEngine as dxf
    drawing = dxf.drawing( dxf_fn)
    
    pageSvg = open(V.page.PageResult).read()
    XML_tree =  SvgXMLTreeNode( pageSvg,0)
    defaultHeight = 0
    defaultFont = 'Verdana'
    defaultAnchor = 'left'
    def yT(y): #y transform
        return 210-y
    warningsShown = []
    SelectViewObjectPoint_loc = None
    for element in XML_tree.getAllElements():
        clr_text = None        
        if 'fill' in element.parms:
            clr_text =  element.parms['fill']
        elif 'style' in element.parms:
            for part in element.parms['style'].split(';'):
                if part.startswith('stroke:rgb('):
                    clr_text = part[ len('stroke:'):]
                elif part.startswith('font-size'):
                    defaultHeight = part[len('font-size:')]
                elif part.startswith('font-family'):
                    defaultFont = part[len('font-family:'):]
                elif part.startswith('text-anchor'):
                    defaultAnchor = part[len('text-anchor:'):]
        if clr_text == None or clr_text =='none' or not clr_text.startswith('rgb(') :
            color_code = 0
        else:
            #FreeCAD.Console.PrintMessage( "color text: %s\n" % clr_text )
            r,g,b = [ int(v.strip()) for v in clr_text[ len('rgb('): clr_text.find(')')].split(',') ]
            color_code = colorLookup(r,g,b)[0]
        if element.tag == 'circle':
            x, y = element.applyTransforms( float( element.parms['cx'] ), float( element.parms['cy'] ) )
            r =  float( element.parms['r'] )* element.scaling2()
            drawing.add( dxf.circle( r, (x,yT(y)), color=color_code) )
        elif element.tag == 'line':
            x1, y1 = element.applyTransforms( float( element.parms['x1'] ), float( element.parms['y1'] ) )
            x2, y2 = element.applyTransforms( float( element.parms['x2'] ), float( element.parms['y2'] ) )
            drawing.add( dxf.line( (x1, yT(y1)), (x2, yT(y2)), color=color_code ) )
        elif element.tag == 'text' and 'x' in element.parms:
            x,y = element.applyTransforms( float( element.parms['x'] ), float( element.parms['y'] ) )
            t = SvgTextParser(element.XML[element.pStart: element.pEnd ] )
            try:
                drawing.add(dxf.text( t.text, insert=(x, yT(y)), height=t.height()*0.8, rotation=t.rotation, layer='TEXTLAYER', color=color_code) )
            except ValueError as e:
                temp = t.text.replace('<tspan>','')
                temp = temp.replace('</tspan>','')
                t.text = temp
                t.font_size = defaultHeight
                t.font_family = defaultFont          
                if defaultAnchor == 'middle':
                    shift = t.width()/2.0   
                    x,y = element.applyTransforms( float( element.parms['x'] )-shift, float( element.parms['y'] ) )
                drawing.add(dxf.text( temp, insert=(x, yT(y)), height=t.height()*0.8, rotation=t.rotation, layer='TEXTLAYER', color=color_code) )
                #FreeCAD.Console.PrintWarning('dxf_export: unable to convert text element "%s": %s, ignoring...\n' % (element.XML[element.pStart: element.pEnd ], str(e) ) )
        elif element.tag == 'path': 
            #FreeCAD.Console.PrintMessage(element.parms['d']+'\n')
            path = SvgPath( element )
            for line in path.lines:
                drawing.add( dxf.line( (line.x1, yT(line.y1)), (line.x2,yT(line.y2)), color=color_code) ) 
            for arc in path.arcs:
                if arc.circular:
                    for r, center, angle1, angle2 in arc.dxfwrite_arc_parms( yT ):
                        drawing.add( dxf.arc( r, center, angle1, angle2 , color=color_code) )
                else:
                    for x1,y1,x2,y2 in arc.approximate_via_lines( 12 ):
                        drawing.add( dxf.line( (x1, yT(y1)), (x2, yT(y2)), color=color_code) )
            for bezierCurve in path.bezierCurves:
                x, y, r, r_error = bezierCurve.fitCircle()
                if r_error < 10**-4:
                    drawing.add( dxf.arc( *bezierCurve.dxfwrite_arc_parms(x, y, r), color=color_code ) )
                else:
                    X,Y = bezierCurve.points_along_curve()
                    for i in range(len(X) -1):
                        drawing.add( dxf.line( (X[i], yT(Y[i])), (X[i+1],yT(Y[i+1])), color=color_code ) )
        elif element.tag == 'polygon':
            p = SvgPolygon( element )
            for line in p.lines:
                drawing.add( dxf.line( (line.x1, yT(line.y1)), (line.x2,yT(line.y2)), color=color_code) ) 
        elif element.tag == 'rect':
            x, y = element.applyTransforms( float( element.parms['x'] ), float( element.parms['y'] ) )
            width =  float( element.parms['width'] )* element.scaling2()
            height =  float( element.parms['height'] )* element.scaling2()
            drawing.add(dxf.rectangle((x, yT(y)), width, -height, color = color_code) )
        elif not element.tag in warningsShown:
            FreeCAD.Console.PrintWarning('dxf_export: Warning export of %s elements not supported, ignoring...\n' % element.tag )
            warningsShown.append(element.tag)
    drawing.save()
    FreeCAD.Console.PrintMessage("dxf_export: %s successfully created\n" % dxf_fn)
drawing.add(dxf.line(
(0,UPPER_CONN_CUT_Y),
(UPPER_CONN_CUT_X,UPPER_CONN_CUT_Y),
color=7,
layer='Edge.Cuts'))

drawing.add(dxf.line(
(UPPER_CONN_CUT_X+UPPER_CONN_CUT_R,UPPER_CONN_CUT_Y-UPPER_CONN_CUT_R),
(UPPER_CONN_CUT_X+UPPER_CONN_CUT_R,0),
color=7,
layer='Edge.Cuts'))

drawing.add(dxf.arc(
radius=UPPER_CONN_CUT_R,
center=(UPPER_CONN_CUT_X,UPPER_CONN_CUT_Y-UPPER_CONN_CUT_R),
startangle=0,
endangle=90,
color=7,
layer='Edge.Cuts'))

drawing.add(dxf.line(
(UPPER_CONN_CUT_X+UPPER_CONN_CUT_R,0),
(CUTOUT_CENTRE_X-CUTOUT_R,0),
color=7,
layer='Edge.Cuts'))

drawing.add(dxf.line(
(CUTOUT_CENTRE_X-CUTOUT_R,0),
(CUTOUT_CENTRE_X-CUTOUT_R,UPPER_CONN_CUT_Y),
color=7,
layer='Edge.Cuts'))
Esempio n. 41
0
def create_dxf(filename, polys, close=False, close_with_arc=False, right_temple_text=None):
    drawing = dxf.drawing(filename)
    drawing.add_layer('OUTLINE', color=1)
    drawing.add_layer('TEXT', color=2)

    for p in polys:
        polyline = dxf.polyline(layer="OUTLINE", thickness=0.1)
        if close:
            p = p + [p[0]]  # Close the polygon to avoid a cusp
        elif close_with_arc and p[0] != p[-1]:
            # Temples get a little arc to account for frame curvature after bending.
            # Frame is bent at base 6 curvature, which is 88 mm radius sphere.  Plane
            # intersecting sphere at 30mm (about the offset of most temples) is 80mm radius.
            # First find the center of the arc

            center_point = (
                    p[-1][0] + (p[0][0]-p[-1][0])/2,
                    p[-1][1] + (p[0][1]-p[-1][1])/2)

            vect = (p[-1][0]-p[0][0], p[-1][1]-p[0][1])
            scale = (vect[0]**2 + vect[1]**2) ** 0.5
            unit_vect = (vect[0]/scale, vect[1]/scale)
            vect = (unit_vect[0]*88, unit_vect[1]*88)
            vect = (vect[1], -vect[0])
            center_point = (center_point[0]+vect[0], center_point[1]+vect[1])

            # We set it arbitrarily at 79 mm but the actual radius will be to the end points
            radius = ((center_point[0]-p[0][0])**2 + (center_point[1]-p[0][1])**2) **0.5
            print 'radius', radius
            angle1 = math.atan2(p[0][1]-center_point[1], p[0][0] - center_point[0])
            angle2 = math.atan2(p[-1][1]-center_point[1], p[-1][0] - center_point[0])
            print 'angle of p0', math.degrees(angle1)
            print 'angle of pn1', math.degrees(angle2)

            drawing.add(dxf.arc(radius, center_point, math.degrees(angle2), math.degrees(angle1), layer="OUTLINE", thickness=0.1))


        polyline.add_vertices(p)
        drawing.add(polyline)

    if right_temple_text:
        p = polys[1]
        insertion_point = (
                p[-1][0] + (p[0][0]-p[-1][0])/2,
                p[-1][1] + (p[0][1]-p[-1][1])/2)

        vect = (p[-1][0]-p[0][0], p[-1][1]-p[0][1])
        scale = (vect[0]**2 + vect[1]**2) ** 0.5
        unit_vect = (vect[0]/scale, vect[1]/scale)
        vect = (unit_vect[0]*15, unit_vect[1]*15)
        vect = (vect[1], -vect[0])
        insertion_point = (insertion_point[0]+vect[0], insertion_point[1]+vect[1]-1)

        bottom_vect = (p[100][0]-p[0][0], p[100][1]-p[0][1])
        text_angle = math.atan2(bottom_vect[1], bottom_vect[0])
        print 'text angle', text_angle
        txt = dxf.text(
                right_temple_text,
                insertion_point,
                rotation=math.degrees(text_angle),
                style="ARIAL",
                layer="TEXT",
                height=2.0
                )
        txt2 = dxf.text(
                "made with love by GUILD eyewear",
                (insertion_point[0]+0.5, insertion_point[1]-3),
                style="TIMES",
                rotation=math.degrees(text_angle),
                layer="TEXT",
                height=2.0
                )
        drawing.add(txt);
    #    drawing.add(txt2);
    drawing.save()
    def drawOneSide(self, cx, cy, nf, dirx, diry, size, thickness, starthigh,
                    beginshort, endshort):
        # cx        ... start in x direction
        # cy        ... start in y direction
        # nf        ... number of fingers
        # dirx      ... direction in x, [ -1, 0, 1 ]
        # diry      ... direction in y, [ -1, 0, 1 ]
        # size      ... run-length of the finger joint line

        ## copy class parameters
        bit_diameter = self.bit_diameter
        drawing = self.drawing

        ## left of direction in x-dimension is INSIDE of the part
        ## left of direction in y-dimension is INSIDE of the part

        # 1 .. normal into workpiece
        # 2 .. normal into fingers
        # 3 .. diagonal
        dog_ears = 1

        ## remember which direction to go for the finger insets
        ##     starthigh --> out    --> -1
        ## not starthigh --> inside -->  1
        if starthigh == True:
            in_or_out = -1
        else:
            in_or_out = 1

        #old dog ears
        if (dog_ears == 1):
            # determine our direction and set the half-circle arc for the dog-ears
            if dirx == 1:
                arc_from = 0
                arc_to = 180
            elif dirx == -1:
                arc_from = 180
                arc_to = 0
            elif diry == -1:
                arc_from = 270
                arc_to = 90
            elif diry == 1:
                arc_from = 90
                arc_to = 270
            else:
                arc_from = 0
                arc_to = 0

        #diagonal dog-ears
        if (dog_ears == 3):
            # determine our direction and set the half-circle arc for the dog-ears
            if dirx == 1:
                arc_from = 45
                arc_to = 225
            elif dirx == -1:
                arc_from = 225
                arc_to = 45
            elif diry == -1:
                arc_from = 315
                arc_to = 135
            elif diry == 1:
                arc_from = 135
                arc_to = 315
            else:
                arc_from = 0
                arc_to = 0

        ## for all fingers to generate...
        for i in range(0, int(nf)):

            ## calculate finger width; we do it here instead of outside the for-loop,
            ## because sometimes we will have to adjust it, but need the full value
            ## again in the next iteration
            finger_size = float(size) / int(nf)

            ## if we start (i==0) with a short piece (parameter beginshort):
            if beginshort and i == 0:
                ## adjust current position accordingly
                cx += abs(thickness) * (dirx)
                cy += abs(thickness) * (diry)
                ## shorten the finger_size temporarily by the same amount
                finger_size -= abs(thickness)

            ## are we in the last iteration?
            if endshort and i == nf - 1:
                ## shorten the finger_size temporarily by the same amount
                finger_size -= abs(thickness)

            ## starthigh correction:
            ##  if we start low/inset finger correct the x/y position accordingly
            if not starthigh and i == 0:
                cx += abs(thickness) * (-diry) * in_or_out
                cy += abs(thickness) * (dirx) * in_or_out

            ## bit_diameter defined && we are drawing INside
            if bit_diameter > 0 and in_or_out == 1:
                ## draw this arc only if this is not the first finger...
                if i > 0:
                    ##          dxf.arc( diameter , ( x , y ) , arc_from, arc_to )
                    # dog ear 1
                    if (dog_ears == 1):
                        drawing.add(
                            dxf.arc(
                                float(bit_diameter) / 2,
                                (cx + float(bit_diameter) / 2 * dirx,
                                 cy + float(bit_diameter) / 2 * diry),
                                arc_from, arc_to))

                    ## dogear diagonal
                    if (dog_ears == 3):
                        drawing.add(
                            dxf.arc(
                                float(bit_diameter) / 2,
                                (cx + math.sqrt(2) / 2 * float(bit_diameter) /
                                 2 * dirx + math.sqrt(2) / 2 *
                                 float(bit_diameter) / 2 * diry,
                                 cy + math.sqrt(2) / 2 * float(bit_diameter) /
                                 2 * diry - math.sqrt(2) / 2 *
                                 float(bit_diameter) / 2 * dirx), arc_from,
                                arc_to))

                    ## increase the cursor position
                    if (dog_ears == 1):
                        cx += bit_diameter * dirx
                        cy += bit_diameter * diry

                    ## diagonal
                    if (dog_ears == 3):
                        cx += math.sqrt(2) * float(bit_diameter) / 2 * dirx
                        cy += math.sqrt(2) * float(bit_diameter) / 2 * diry

                    ## shorten the length of the following finger accordingly
                    finger_size -= bit_diameter
                    #finger_size -= math.sqrt(2)*float(bit_diameter) ##bit_diameter##

                ## draw this arc only if this is not the last finger...
                if i < nf - 1:
                    # old dog-ears
                    if (dog_ears == 1):
                        drawing.add(
                            dxf.arc(
                                float(bit_diameter) / 2,
                                (cx - float(bit_diameter) / 2 * dirx +
                                 finger_size * dirx,
                                 cy - float(bit_diameter) / 2 * diry +
                                 finger_size * diry), arc_from, arc_to))
                    if (dog_ears == 3):
                        drawing.add(
                            dxf.arc(
                                float(bit_diameter) / 2,
                                (cx - math.sqrt(2) / 2 * float(bit_diameter) /
                                 2 * dirx + math.sqrt(2) / 2 *
                                 float(bit_diameter) / 2 * diry +
                                 finger_size * dirx, cy - math.sqrt(2) / 2 *
                                 float(bit_diameter) / 2 * diry -
                                 math.sqrt(2) / 2 * float(bit_diameter) / 2 *
                                 dirx + finger_size * diry), arc_from - 90,
                                arc_to - 90))

                    ## shorten length of finger accordingly
                    # old dog-ears
                    finger_size -= bit_diameter  #
                    #finger_size -= math.sqrt(2)*float(bit_diameter) ##bit_diameter##

            ## draw the finger line, depending on x or y direction and length
            drawing.add(
                dxf.line((cx, cy),
                         (cx + finger_size * dirx, cy + finger_size * diry)))

            ## increase the cursor position after drawing the finger
            cx += (finger_size) * dirx
            cy += (finger_size) * diry

            ## if we have drawn a second dog-ear, add it to the cursor position
            if bit_diameter > 0 and in_or_out == 1 and i < nf - 1:
                cx += bit_diameter * dirx
                cy += bit_diameter * diry

            ## skip if end already reached
            if not (i == nf - 1):
                ## draw one line of material thickness inwards/outwards
                drawing.add(
                    dxf.line((cx, cy),
                             (cx - abs(thickness) * (-diry) * in_or_out,
                              cy - abs(thickness) * (dirx) * in_or_out)))
                ## adjust current position accordingly
                cx -= abs(thickness) * (-diry) * in_or_out
                cy -= abs(thickness) * (dirx) * in_or_out
                in_or_out *= -1
Esempio n. 43
0
 def append_to_dxf(self, drawing):
     drawing.add(dxf.arc(self.radius, (self.center[0], -self.center[1]), self.start_angle * 180 / math.pi, self.end_angle * 180 / math.pi))
    def drawOneSide2(self, cx, cy, nf, dirx, diry, size, thickness, starthigh,
                     beginshort, endshort):

        ## copy class parameters
        bit_diameter = self.bit_diameter
        drawing = self.drawing

        ## for all fingers to generate...
        for i in range(0, int(nf)):

            ## calculate finger width;
            finger_size = float(size) / int(nf)

            ## alternate in/out finger with regards to starthigh
            cx += diry * thickness * (
                (starthigh + i) % 2 == 0) - thickness * diry * (
                    (starthigh + i) % 2 != 0)
            cy += dirx * thickness * (
                (starthigh + i) % 2 == 0) - thickness * dirx * (
                    (starthigh + i) % 2 != 0)

            ## draw the finger-line and upd position
            ##                     start +                 shorten start/end by bit_diameter if we are inside          start + finger size
            drawing.add(
                dxf.line(
                    (cx + dirx * math.sqrt(2) / 2 * bit_diameter *
                     ((starthigh + i) % 2 == 0), cy),
                    (cx + (finger_size * dirx) -
                     dirx * math.sqrt(2) / 2 * bit_diameter *
                     ((starthigh + i) % 2 == 0), cy + (finger_size * diry))))
            cx += (finger_size * dirx)
            cy += (finger_size * diry)

            ## circle in ze edge!!                    start + thickness in correct direction if in + push a little to position
            ## only if not the last one and we start with high
            if i < nf - 1 and starthigh:
                drawing.add(
                    dxf.arc(
                        float(bit_diameter) / 2,
                        (cx + thickness * diry * ((starthigh + i) % 2 != 0) +
                         dirx * math.sqrt(2) / 4 * (bit_diameter) *
                         ((starthigh + i) % 2 != 0) - dirx * math.sqrt(2) / 4 *
                         (bit_diameter) *
                         ((starthigh + i) % 2 == 0), cy + thickness * dirx *
                         ((starthigh + i) % 2 != 0) - dirx * math.sqrt(2) / 4 *
                         (bit_diameter)),
                        45 - dirx * 90 * ((starthigh + i) % 2 == 0),
                        225 - dirx * 90 * ((starthigh + i) % 2 == 0)))

            ## skip line in/out on last line
            if i < nf - 1:
                ## draw the line in or out
                ##                     start  -  down                               + up                                   - dog-ear shortens line for going from in to out
                drawing.add(
                    dxf.line(
                        (
                            cx, cy - dirx * math.sqrt(2) / 2 * bit_diameter *
                            ((starthigh + i) % 2 == 0)
                        ),  #  - dirx*math.sqrt(2)/2*bit_diameter*(starthigh%2==0) ) ,
                        (cx, cy - thickness * dirx *
                         ((starthigh + i) % 2 == 0) + thickness * dirx *
                         ((starthigh + i) % 2 != 0) -
                         dirx * math.sqrt(2) / 2 * bit_diameter *
                         ((starthigh + i) % 2 != 0))))
def tisk_odstup(df_result, df_input, df_rotate):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    os.chdir(os.path.dirname(__file__))
    print(dir_path)

    ###################################
    drawing = dxf.drawing('drawing.dxf')
    drawing.header['$LTSCALE'] = 500
    # dimensionline setup:
    # add block and layer definition to drawing
    if df_input['Hodnota'][5] == 'ANO':
        dimstyles.setup(drawing)
        dimstyles.new("dots",
                      tickfactor=df_input['Hodnota'][6] * 2.5,
                      height=df_input['Hodnota'][6] * 2.5,
                      scale=1.,
                      textabove=df_input['Hodnota'][6])

    # Přidání hladin do výkresu
    drawing.add_layer('LINES', color=5, linetype='DIVIDE')

    df_result_tisk = df_result[['sirka', 'd', 'd\'', 'd\'s']] * 1000
    df_result_text = df_result['Nazev/fasada']
    '''df_result_text ='''
    odstup = df_result_tisk.values.tolist()
    rotation = df_rotate.values.tolist()
    text = df_result_text.values.tolist()

    x = 0
    for i in range(len(odstup)):
        # Středová kružnice
        des_B = distance([x, 0], [x + odstup[i][0] / 2, odstup[i][1]])
        des_C = distance([x, 0], [x + odstup[i][0], odstup[i][2]])
        deg_A = radians(90)
        deg_B = atan(odstup[i][1] / (odstup[i][0] / 2))
        deg_C = atan(odstup[i][2] / (odstup[i][0]))

        A = [
            x + cos(radians(rotation[i][0]) + deg_A) * odstup[i][2],
            0 + sin(radians(rotation[i][0]) + deg_A) * odstup[i][2]
        ]
        B = [
            x + cos(radians(rotation[i][0]) + deg_B) * des_B,
            0 + sin(radians(rotation[i][0]) + deg_B) * des_B
        ]
        C = [
            x + cos(radians(rotation[i][0]) + deg_C) * des_C,
            0 + sin(radians(rotation[i][0]) + deg_C) * des_C
        ]

        center, radius = define_circle(A, B, C)
        if center is not None:
            angle_end = define_angle(center, A)
            angle_begin = define_angle(center, C)

        # Vzdálenost od počátku ke středu boční pravé kružnice
        des_C_r = distance([x, 0], [x + odstup[i][0], odstup[i][2] / 2])
        # Úhel od počátku ke středu boční pravé kružnice
        deg_C_r = atan(odstup[i][2] / 2 / (odstup[i][0]))

        # Souřanice středu bočních kružnic
        A_l = [
            x + cos(radians(rotation[i][0]) + deg_A) * odstup[i][2] / 2,
            0 + sin(radians(rotation[i][0]) + deg_A) * odstup[i][2] / 2
        ]
        A_r = [
            x + cos(radians(rotation[i][0]) + deg_C_r) * des_C_r,
            0 + sin(radians(rotation[i][0]) + deg_C_r) * des_C_r
        ]

        # Vykreslení kružnic
        arc = dxf.arc(odstup[i][3],
                      A_l,
                      90 + rotation[i][0],
                      270 + rotation[i][0],
                      layer='LINES')
        drawing.add(arc)
        arc = dxf.arc(odstup[i][3],
                      A_r,
                      270 + rotation[i][0],
                      90 + rotation[i][0],
                      layer='LINES')
        drawing.add(arc)

        if center is not None:
            arc = dxf.arc(radius,
                          center,
                          angle_begin,
                          angle_end,
                          layer='LINES')
            drawing.add(arc)
        else:
            line = dxf.line(A, C, layer='LINES')
            drawing.add(line)
        text_to_add = text[i]
        plain_text = unicodedata.normalize('NFKD', text_to_add)
        text_added = dxf.text(plain_text, (x, odstup[i][1] + 1000), height=500)
        drawing.add(text_added)
        if df_input['Hodnota'][5] == 'ANO':

            des_boc = distance([x, 0], [x - odstup[i][3], odstup[i][2] / 2])
            deg_boc = atan(odstup[i][2] / 2 / (-(odstup[i][3])))

            A_boc = [
                x - cos(radians(rotation[i][0]) + deg_boc) * des_boc,
                0 - sin(radians(rotation[i][0]) + deg_boc) * des_boc
            ]

            angll = rotation[i][0]
            if 90 < rotation[i][0] < 270:
                angll = rotation[i][0] - 180

            des_center = distance([x, 0],
                                  [x + odstup[i][0] / 2, odstup[i][1] / 2])
            deg_center = atan(odstup[i][1] / 2 / (odstup[i][0] / 2))

            center_text = [
                x + cos(radians(rotation[i][0]) + deg_center) * des_center,
                0 + sin(radians(rotation[i][0]) + deg_center) * des_center
            ]

            des_top = distance([x, 0], [x + odstup[i][0] / 2, odstup[i][1]])
            deg_top = atan(odstup[i][1] / (odstup[i][0] / 2))

            top_point = [
                x + cos(radians(rotation[i][0]) + deg_top) * des_top,
                0 + sin(radians(rotation[i][0]) + deg_top) * des_top
            ]

            des_bot = distance([x, 0], [x + odstup[i][0] / 2, 0])
            deg_bot = atan(0 / (odstup[i][0] / 2))

            bot_point = [
                x + cos(radians(rotation[i][0]) + deg_bot) * des_bot,
                0 + sin(radians(rotation[i][0]) + deg_bot) * des_bot
            ]

            angllee = rotation[i][0]
            if 0 < rotation[i][0] < 180:
                angllee = rotation[i][0] - 180

            drawing.add(
                LinearDimension(A_l, [A_l, A_boc],
                                dimstyle='dots',
                                angle=angll))
            drawing.add(
                LinearDimension(center_text, [top_point, bot_point],
                                dimstyle='dots',
                                angle=angllee + 90))
        x += 15000

    drawing.save()
Esempio n. 46
0
 def arc(self, radius=None, center=None, startangle=None, endangle=None, color=None):
     item = dxf.arc(radius=radius, center=center, startangle=startangle, endangle=endangle, color=color)
     self.add(item)
Esempio n. 47
0
from dxfwrite import DXFEngine as dxf

drawing = dxf.drawing('drawing.dxf')
arc = dxf.arc(0.1, (1.0, 1.0), 0, 90)
arc['layer'] = 'points'
arc['color'] = 7
arc['center'] = (2, 3, 7)  # int or float
arc['radius'] = 3.5
drawing.add(arc)
drawing.save()
import math
#import pdb


# arrows/lines function
def dim12_arrow(u1, u2, u3, u4, l1, l2, l3, l4, c1, c2, c3, c4):
    drawing.add(dxf.line((c1, c2), (c3, c4)))
    drawing.add(dxf.line((u1, u2), (u3, u4)))
    drawing.add(dxf.line((l1, l2), (l3, l4)))

def dim8_arrow(u11, u12, u13, u14, l11, l12, l13, l14):
    drawing.add(dxf.line((u11, u12), (u13, u14)))
    drawing.add(dxf.line((l11, l12), (l13, l14)))

def dim5_arrow(r1, (c1, c2), st1, ed1):
    drawing.add(dxf.arc(r1, (c1, c2), st1, ed1))

def dim4_arrow(l21, l22, l23, l24):
    drawing.add(dxf.line((l21, l22), (l23, l24)))

def atrace(t1, t2, t3, t4, t5, t6):
    drawing.add(dxf.trace([(t1, t2), (t3, t4), (t5, t6)]))


#input file
f=open('Sloped footing(c).csv')
lst={'A':'','D':'','a':'','Dm':''}
data=[row for row in csv.reader(f)]
for i in lst.keys():
    for j in range(len(data)):
            if(i==data[j][0]):
Esempio n. 49
0
def arcOfCircle(drawing, geometry):
    arc = findTag(geometry, 'ArcOfCircle').attrib
    drawing.add(dxf.arc(arc['Radius'], (float(arc['CenterX']), float(arc['CenterY'])), float(arc['StartAngle'])*180/pi, float(arc['EndAngle'])*180/pi))
Esempio n. 50
0
def drawArcColouredLayer(draw, pxCentre, pyCentre, radio, AngIni, AngEnd, colorA, capa):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx["color"] = colorA
    arcx["layer"] = capa
    draw.add(arcx)
    draw.add_layer(capa, color=colorA)
# add a VIEWPORT-tableentry
drawing.add_vport(
    '*ACTIVE',
    center_point=(10, 10),
    height=30,
)

# add LINE-entity
drawing.add(dxf.line((0, 0), (10, 0), color=dxfwrite.BYLAYER,
                     layer='dxfwrite'))

# add a CIRCLE-entity
drawing.add(dxf.circle(center=(5, 0), radius=5))

# add an ARC-entity
drawing.add(dxf.arc(center=(5, 0), radius=4, startangle=30, endangle=150))

#add a POINT-entity
drawing.add(dxf.point(point=(1, 1)))

# add a SOLID-entity with 4 points
drawing.add(dxf.solid([(0, 0), (1, 0), (1, 1), (0, 1)], color=2))

# add a SOLID-entity with 3 points
drawing.add(dxf.solid([(0, 1), (1, 1), (1, 2)], color=3))

# add a 3DFACE-entity
drawing.add(dxf.face3d([(5, 5), (6, 5), (6, 6), (5, 6)], color=3))

# add a Trace-entity
drawing.add(dxf.trace([(7, 5), (8, 5), (8, 6), (7, 6)], color=4))
Esempio n. 52
0
def drawArcFMC(draw, pxCentre, pyCentre, radio, AngIni, AngEnd):
    arcx = dxf.arc(radio, (pxCentre, pyCentre), AngIni, AngEnd)
    arcx["color"] = colorLine
    draw.add(arcx)
    draw.add_layer(currentLayer, color=colorLine)
Esempio n. 53
0
            dxf.line((float(p[0]), float(p[1])),
                     (float(p[0]) + float(p[2]), float(p[1]))))

        drawing.add(
            dxf.line((float(p[0]) + float(p[2]), float(p[1])),
                     (float(p[0]) + float(p[2]), float(p[1]) + float(p[3]))))
        drawing.add(
            dxf.line((float(p[0]) + float(p[2]), float(p[1]) + float(p[3])),
                     (float(p[0]), float(p[1]) + float(p[3]))))

        drawing.add(
            dxf.line((float(p[0]), float(p[1]) + float(p[3])),
                     (float(p[0]), float(p[1]))))
    elif cmd == "arcIn":
        x1 = float(p[0])
        y1 = float(p[1])
        x2 = float(p[2])
        y2 = float(p[3])
        centerX = float([2])
        centerY = float([3])
        rad = abs(centerX - x1)  # x1,y1 x2,y2 centerX,centerY

        angleDeg = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
        drawing.add(dxf.arc(rad, (centerX, centerY)))
drawing.save()
path = '\"'
for x in range(3, 4):
    path += sys.argv[x] + ' '
path = path[:-1] + '\"'
print('mv ~/' + name + '.dxf ' + path)
os.system('mv ~/' + name + '.dxf ' + path)