def draw_freehand(self): """ Freehand sketching. """ if _ctx._ns["mousedown"]: x, y = mouse() if self.show_grid: x, y = self.grid.snap(x, y) if self.freehand_move == True: cmd = MOVETO self.freehand_move = False else: cmd = LINETO # Add a new LINETO to the path, # except when starting to draw, # then a MOVETO is added to the path. pt = PathElement() if cmd != MOVETO: pt.freehand = True # Used when mixed with curve drawing. else: pt.freehand = False pt.cmd = cmd pt.x = x pt.y = y pt.ctrl1 = Point(x,y) pt.ctrl2 = Point(x,y) self._points.append(pt) # Draw the current location of the cursor. r = 4 _ctx.nofill() _ctx.stroke(self.handle_color) _ctx.oval(pt.x-r, pt.y-r, r*2, r*2) _ctx.fontsize(9) _ctx.fill(self.handle_color) _ctx.text(" ("+str(int(pt.x))+", "+str(int(pt.y))+")", pt.x+r, pt.y) self._dirty = True else: # Export the updated drawing, # remember to do a MOVETO on the next interaction. self.freehand_move = True if self._dirty: self._points[-1].freehand = False self.export_svg() self._dirty = False
def round_segments(path, d): points = path.points new_points = [] for i, pt in enumerate(points): prev = points[i - 1] next = points[(i + 1) % len(points)] a = angle(prev.x, prev.y, next.x, next.y) c1 = coordinates(pt.x, pt.y, -d, a) c2 = coordinates(pt.x, pt.y, d, a) new_points.append(Point(c1[0], c1[1])) new_points.append(pt) new_points.append(Point(c2[0], c2[1])) new_path = path.cloneAndClear() _construct_path(new_path, new_points) return new_path
def forward(self, distance): x = self.pos.x + distance * cos(radians(self.dir)) y = self.pos.y + distance * sin(radians(self.dir)) p = Point(x, y) self.pos = p # extend the path self.lineto(p.x, p.y)
def reflect(shape, position, _angle, keep_original): """Mirrors and copies the geometry across an invisible axis.""" if shape is None: return None new_shape = shape.cloneAndClear() for contour in shape.contours: c = Contour() for point in contour.points: d = distance(point.x, point.y, position.x, position.y) a = angle(point.x, point.y, position.x, position.y) x, y = coordinates(position.x, position.y, d * cos(radians(a - _angle)), 180 + _angle) d = distance(point.x, point.y, x, y) a = angle(point.x, point.y, x, y) px, py = coordinates(point.x, point.y, d * 2, a) c.addPoint(Point(px, py, point.type)) if contour.closed: c.close() new_shape.add(c) if keep_original: g = Geometry() g.add(shape) g.add(new_shape) return g return new_shape
def coordinates(self, x0, y0, distance, angle): """ Calculates the coordinates of a point from the origin. """ x = x0 + cos(radians(angle)) * distance y = y0 + sin(radians(angle)) * distance return Point(x, y)
def wiggle_points(points, offset): new_points = [] for point in points: dx = (uniform(0, 1) - 0.5) * offset.x * 2 dy = (uniform(0, 1) - 0.5) * offset.y * 2 new_points.append(Point(point.x + dx, point.y + dy, point.type)) return new_points
def fit_to(shape, bounding, keep_proportions): """Fit a shape to another shape.""" if shape is None: return None if bounding is None: return shape bx, by, bw, bh = list(bounding.bounds) return fit(shape, Point(bx+bw/2, by+bh/2), bw, bh, keep_proportions)
def rotate(shape, angle, origin=Point.ZERO): """Rotate the given shape.""" if shape is None: return None t = Transform() t.translate(origin) t.rotate(angle) t.translate(Point(-origin.x, -origin.y)) return t.map(shape)
def scale(shape, scale, origin=Point.ZERO): """Scale the given shape.""" if shape is None: return None t = Transform() t.translate(origin) t.scale(scale.x / 100.0, scale.y / 100.0) t.translate(Point(-origin.x, -origin.y)) return t.map(shape)
def _locate(path, t, segments=None): """Locates t on a specific segment in the path. Returns (index, t, PathElement) A path is a combination of lines and curves (segments). The returned index indicates the start of the segment that contains point t. The returned t is the absolute time on that segment, in contrast to the relative t on the whole of the path. The returned point is the last MOVETO, any subsequent CLOSETO after i closes to that point. When you supply the list of segment lengths yourself, as returned from length(path, segmented=True), point() works about thirty times faster in a for-loop, since it doesn't need to recalculate the length during each iteration. Note that this has been deprecated: the BezierPath now caches the segment lengths the moment you use them. >>> path = BezierPath(None) >>> _locate(path, 0.0) Traceback (most recent call last): ... NodeBoxError: The given path is empty >>> path.moveto(0,0) >>> _locate(path, 0.0) Traceback (most recent call last): ... NodeBoxError: The given path is empty >>> path.lineto(100, 100) >>> _locate(path, 0.0) (0, 0.0, Point(x=0.0, y=0.0)) >>> _locate(path, 1.0) (0, 1.0, Point(x=0.0, y=0.0)) """ if segments == None: segments = path.segmentlengths(relative=True) if len(segments) == 0: raise NodeBoxError, "The given path is empty" for i, el in enumerate(path): if i == 0 or el.cmd == MOVETO: closeto = Point(el.x, el.y) if t <= segments[i] or i == len(segments) - 1: break else: t -= segments[i] try: t /= segments[i] except ZeroDivisionError: pass if i == len(segments) - 1 and segments[i] == 0: i -= 1 return (i, t, closeto)
def findpath(self, points, curvature=1.0): # The list of points consists of Point objects, # but it shouldn't crash on something straightforward # as someone supplying a list of (x,y)-tuples. from types import TupleType for i, pt in enumerate(points): if type(pt) == TupleType: points[i] = Point(pt[0], pt[1]) return CanvasContext.findpath(self, points, curvature)
def getReflectedControlPoint(self): if self.previousCommand.lower() != 'c' and\ self.previousCommand.lower() != 's' and\ self.previousCommand.lower() != 'q' and\ self.previousCommand.lower() != 't': return self.current # reflect point pt = Point(2 * self.current.x - self.control.x, 2 * self.current.y - self.control.y) return pt
def cook(foto, sg): f = File(abspath(foto)) bi = ImageIO.read(f) raster = bi.raster w = raster.width h = raster.height seg = sg all = [] for i in xrange(0, w, seg): for j in xrange(0, h, seg): c = bi.raster.getPixel(i, j, [0.0, 0.0, 0.0]) all.append(Point(i, j)) all.append(c[0]) return all
def polar_grid(distance, angle, radial, polar, full, position): if full: alpha = 360 / polar else: alpha = angle points = [] for p in xrange(polar): for r in xrange(radial): point = coordinates(position.x, position.y, r * distance, p * alpha) points.append(Point(point[0], point[1])) return points
def scatter(shape, amount, seed): """Generate points within the boundaries of a shape.""" if shape is None: return None _seed(seed) bx, by, bw, bh = list(shape.bounds) points = [] for i in xrange(amount): tries = 100 while tries > 0: pt = Point(bx + uniform(0, 1) * bw, by + uniform(0, 1) * bh) if shape.contains(pt): points.append(pt) break tries -= 1 return points
def snap(shape, distance, strength, position=Point.ZERO): """Snap geometry to a grid.""" def _snap(v, offset=0.0, distance=10.0, strength=1.0): return (v * (1.0-strength)) + (strength * round(v / distance) * distance) if shape is None: return None new_shape = shape.cloneAndClear() strength /= 100.0 for contour in shape.contours: c = Contour() for pt in contour.points: x = _snap(pt.x + position.x, position.x, distance, strength) - position.x y = _snap(pt.y + position.y, position.y, distance, strength) - position.y c.addPoint(Point(x, y, pt.type)) c.closed = contour.closed new_shape.add(c) return new_shape
def perpendicular_curve(pt0, pt1, curvature=0.8): d = distance(pt0.x, pt0.y, pt1.x, pt1.y) a = angle(pt0.x, pt0.y, pt1.x, pt1.y) mid = Point( pt0.x + (pt1.x-pt0.x) * 0.5, pt0.y + (pt1.y-pt0.y) * 0.5 ) dx, dy = coordinates(mid.x, mid.y, m, a-90) vx = pt0.x + (mid.x-pt0.x) * curvature vy = pt0.y + (mid.y-pt0.y) * curvature curveto(vx, vy, dx, dy, dx, dy) vx = pt1.x + (mid.x-pt1.x) * curvature vy = pt1.y + (mid.y-pt1.y) * curvature curveto(dx, dy, vx, vy, pt1.x, pt1.y)
def calculate_bounds(self): min = Point(float("inf"), float("inf")) max = Point(float("-inf"), float("-inf")) for n in self.graph.nodes: if (n.x > max.x): max.x = n.x if (n.y > max.y): max.y = n.y if (n.x < min.x): min.x = n.x if (n.y < min.y): min.y = n.y self.graph.min = min self.graph.max = max
def grid(rows, columns, width, height, position): """Create a grid of points.""" if columns > 1: column_size = width / (columns - 1) left = position.x - width / 2 else: column_size = left = position.x if rows > 1: row_size = height / (rows - 1) top = position.y - height / 2 else: row_size = top = position.y points = [] for ri in xrange(rows): for ci in xrange(columns): x = left + ci * column_size y = top + ri * row_size points.append(Point(x, y)) return points
def shape_on_path(shapes, path, amount, alignment, spacing, margin, baseline_offset): if not shapes: return [] if path is None: return [] if alignment == "trailing": shapes = list(shapes) shapes.reverse() length = path.length - margin m = margin / path.length c = 0 new_shapes = [] for i in xrange(amount): for shape in shapes: if alignment == "distributed": p = length / ((amount * len(shapes)) - 1) pos = c * p / length pos = m + (pos * (1 - 2 * m)) else: pos = ((c * spacing) % length) / length pos = m + (pos * (1 - m)) if alignment == "trailing": pos = 1 - pos p1 = path.pointAt(pos) p2 = path.pointAt(pos + 0.0000001) a = angle(p1.x, p1.y, p2.x, p2.y) if baseline_offset: coords = coordinates(p1.x, p1.y, baseline_offset, a - 90) p1 = Point(*coords) t = Transform() t.translate(p1) t.rotate(a) new_shapes.append(t.map(shape)) c += 1 return new_shapes
def update(self): """ Update runs each frame to check for mouse interaction. Alters the path by allowing the user to add new points, drag point handles and move their location. Updates are automatically stored as SVG in the given filename. """ x, y = mouse() if self.show_grid: x, y = self.grid.snap(x, y) if _ctx._ns["mousedown"] \ and not self.freehand: self._dirty = True # Handle buttons first. # When pressing down on a button, all other action halts. # Buttons appear near a point being edited. # Once clicked, actions are resolved. if self.edit != None \ and not self.drag_point \ and not self.drag_handle1 \ and not self.drag_handle2: pt = self._points[self.edit] dx = pt.x+self.btn_x dy = pt.y+self.btn_y # The delete button if self.overlap(dx, dy, x, y, r=self.btn_r): self.delete = self.edit return # The moveto button, # active on the last point in the path. dx += self.btn_r*2 + 2 if self.edit == len(self._points) -1 and \ self.overlap(dx, dy, x, y, r=self.btn_r): self.moveto = self.edit return if self.insert: self.inserting = True return # When not dragging a point or the handle of a point, # i.e. the mousebutton was released and then pressed again, # check to see if a point on the path is pressed. # When this point is not the last new point, # enter edit mode. if not self.drag_point and \ not self.drag_handle1 and \ not self.drag_handle2: self.editing = False indices = range(len(self._points)) indices.reverse() for i in indices: pt = self._points[i] if pt != self.new \ and self.overlap(x, y, pt.x, pt.y) \ and self.new == None: # Don't select a point if in fact # it is at the same location of the first handle # of the point we are currently editing. if self.edit == i+1 \ and self.overlap(self._points[i+1].ctrl1.x, self._points[i+1].ctrl1.y, x, y): continue else: self.edit = i self.editing = True break # When the mouse button is down, # edit mode continues as long as # a point or handle is dragged. # Else, stop editing and switch to add-mode # (the user is clicking somewhere on the canvas). if not self.editing: if self.edit != None: pt = self._points[self.edit] if self.overlap(pt.ctrl1.x, pt.ctrl1.y, x, y) or \ self.overlap(pt.ctrl2.x, pt.ctrl2.y, x, y): self.editing = True else: self.edit = None # When not in edit mode, there are two options. # Either no new point is defined and the user is # clicking somewhere on the canvas (add a new point) # or the user is dragging the handle of the new point. # Adding a new point is a fluid click-to-locate and # drag-to-curve action. if self.edit == None: if self.new == None: # A special case is when the used clicked # the moveto button on the last point in the path. # This indicates a gap (i.e. MOVETO) in the path. self.new = PathElement() if self.moveto == True \ or len(self._points) == 0: cmd = MOVETO self.moveto = None self.last_moveto = self.new else: cmd = CURVETO self.new.cmd = cmd self.new.x = x self.new.y = y self.new.ctrl1 = Point(x, y) self.new.ctrl2 = Point(x, y) self.new.freehand = False # Don't forget to map the point's ctrl1 handle # to the ctrl2 handle of the previous point. # This makes for smooth, continuous paths. if len(self._points) > 0: prev = self._points[-1] rx, ry = self.reflect(prev.x, prev.y, prev.ctrl2.x, prev.ctrl2.y) self.new.ctrl1 = Point(rx, ry) self._points.append(self.new) else: # Illustrator-like behavior: # when the handle is dragged downwards, # the path bulges upwards. rx, ry = self.reflect(self.new.x, self.new.y, x, y) self.new.ctrl2 = Point(rx, ry) # Edit mode elif self.new == None: pt = self._points[self.edit] # The user is pressing the mouse on a point, # enter drag-point mode. if self.overlap(pt.x, pt.y, x, y) \ and not self.drag_handle1 \ and not self.drag_handle2 \ and not self.new != None: self.drag_point = True self.drag_handle1 = False self.drag_handle2 = False # The user is pressing the mouse on a point's handle, # enter drag-handle mode. if self.overlap(pt.ctrl1.x, pt.ctrl1.y, x, y) \ and pt.cmd == CURVETO \ and not self.drag_point \ and not self.drag_handle2: self.drag_point = False self.drag_handle1 = True self.drag_handle2 = False if self.overlap(pt.ctrl2.x, pt.ctrl2.y, x, y) \ and pt.cmd == CURVETO \ and not self.drag_point \ and not self.drag_handle1: self.drag_point = False self.drag_handle1 = False self.drag_handle2 = True # In drag-point mode, # the point is located at the mouse coordinates. # The handles move relatively to the new location # (e.g. they are retained, the path does not distort). # Modify the ctrl1 handle of the next point as well. if self.drag_point == True: dx = x - pt.x dy = y - pt.y pt.x = x pt.y = y pt.ctrl2.x += dx pt.ctrl2.y += dy if self.edit < len(self._points)-1: rx, ry = self.reflect(pt.x, pt.y, x, y) next = self._points[self.edit+1] next.ctrl1.x += dx next.ctrl1.y += dy # In drag-handle mode, # set the path's handle to the mouse location. # Rotate the handle of the next or previous point # to keep paths smooth - unless the user is pressing "x". if self.drag_handle1 == True: pt.ctrl1 = Point(x, y) if self.edit > 0 \ and self.last_key != "x": prev = self._points[self.edit-1] d = self.distance(prev.x, prev.y, prev.ctrl2.x, prev.ctrl2.y) a = self.angle(prev.x, prev.y, pt.ctrl1.x, pt.ctrl1.y) prev.ctrl2 = self.coordinates(prev.x, prev.y, d, a+180) if self.drag_handle2 == True: pt.ctrl2 = Point(x, y) if self.edit < len(self._points)-1 \ and self.last_key != "x": next = self._points[self.edit+1] d = self.distance(pt.x, pt.y, next.ctrl1.x, next.ctrl1.y) a = self.angle(pt.x, pt.y, pt.ctrl2.x, pt.ctrl2.y) next.ctrl1 = self.coordinates(pt.x, pt.y, d, a+180) elif not self.freehand: # The mouse button is released # so we are not dragging anything around. self.new = None self.drag_point = False self.drag_handle1 = False self.drag_handle2 = False # The delete button for a point was clicked. if self.delete != None and len(self._points) > 0: i = self.delete cmd = self._points[i].cmd del self._points[i] if 0 < i < len(self._points): prev = self._points[i-1] rx, ry = self.reflect(prev.x, prev.y, prev.ctrl2.x, prev.ctrl2.y) self._points[i].ctrl1 = Point(rx, ry) # Also delete all the freehand points # prior to this point. start_i = i while i > 1: i -= 1 pt = self._points[i] if pt.freehand: del self._points[i] elif i < start_i-1 and pt.freehand == False: if pt.cmd == MOVETO: del self._points[i] break # When you delete a MOVETO point, # the last moveto (the one where the dashed line points to) # needs to be updated. if len(self._points) > 0 \ and (cmd == MOVETO or i == 0): self.last_moveto = self._points[0] for pt in self._points: if pt.cmd == MOVETO: self.last_moveto = pt self.delete = None self.edit = None # The moveto button for the last point # in the path was clicked. elif isinstance(self.moveto, int): self.moveto = True self.edit = None # We are not editing a node and # the mouse is hovering over the path outline stroke: # it is possible to insert a point here. elif self.edit == None \ and self.contains_point(x, y, d=2): self.insert = True else: self.insert = False # Commit insert of new point. if self.inserting \ and self.contains_point(x, y, d=2): self.insert_point(x, y) self.insert = False self.inserting = False # No modifications are being made right now # and the SVG file needs to be updated. if self._dirty == True: self.export_svg() self._dirty = False # Keyboard interaction. if _ctx._ns["keydown"]: self.last_key = _ctx._ns["key"] self.last_keycode = _ctx._ns["keycode"] if not _ctx._ns["keydown"] and self.last_key != None: # If the TAB-key is pressed, # switch the magnetic grid either on or off. if self.last_keycode == KEY_TAB: self.show_grid = not self.show_grid # When "f" is pressed, switch freehand mode. if self.last_key == "f": self.edit = None self.freehand = not self.freehand if self.freehand: self.msg = "freehand" else: self.msg = "curves" # When ESC is pressed exit edit mode. if self.last_keycode == KEY_ESC: self.edit = None # When BACKSPACE is pressed, delete current point. if self.last_keycode == _ctx.KEY_BACKSPACE \ and self.edit != None: self.delete = self.edit self.last_key = None self.last_code = None # Using the keypad you can scroll the screen. if _ctx._ns["keydown"]: dx = 0 dy = 0 keycode = _ctx._ns["keycode"] if keycode == _ctx.KEY_LEFT: dx = -10 elif keycode == _ctx.KEY_RIGHT: dx = 10 if keycode == _ctx.KEY_UP: dy = -10 elif keycode == _ctx.KEY_DOWN: dy = 10 if dx != 0 or dy != 0: for pt in self._points: pt.x += dx pt.y += dy pt.ctrl1.x += dx pt.ctrl1.y += dy pt.ctrl2.x += dx pt.ctrl2.y += dy
def makePoint(x, y): """ create a point or a dict """ if type(x) == float: return Point(x, y) else: return {'x': x, 'y': y}
def findpath(points, curvature=1.0): """Constructs a path between the given list of points. Interpolates the list of points and determines a smooth bezier path betweem them. The curvature parameter offers some control on how separate segments are stitched together: from straight angles to smooth curves. Curvature is only useful if the path has more than three points. """ # The list of points consists of Point objects, # but it shouldn't crash on something straightforward # as someone supplying a list of (x,y)-tuples. from types import TupleType for i, pt in enumerate(points): if type(pt) == TupleType: points[i] = Point(pt[0], pt[1]) if len(points) == 0: return None if len(points) == 1: path = BezierPath(None) path.moveto(points[0].x, points[0].y) return path if len(points) == 2: path = BezierPath(None) path.moveto(points[0].x, points[0].y) path.lineto(points[1].x, points[1].y) return path # Zero curvature means straight lines. curvature = max(0, min(1, curvature)) if curvature == 0: path = BezierPath(None) path.moveto(points[0].x, points[0].y) for i in range(len(points)): path.lineto(points[i].x, points[i].y) return path curvature = 4 + (1.0 - curvature) * 40 dx = {0: 0, len(points) - 1: 0} dy = {0: 0, len(points) - 1: 0} bi = {1: -0.25} ax = {1: (points[2].x - points[0].x - dx[0]) / 4} ay = {1: (points[2].y - points[0].y - dy[0]) / 4} for i in range(2, len(points) - 1): bi[i] = -1 / (curvature + bi[i - 1]) ax[i] = -(points[i + 1].x - points[i - 1].x - ax[i - 1]) * bi[i] ay[i] = -(points[i + 1].y - points[i - 1].y - ay[i - 1]) * bi[i] r = range(1, len(points) - 1) r.reverse() for i in r: dx[i] = ax[i] + dx[i + 1] * bi[i] dy[i] = ay[i] + dy[i + 1] * bi[i] path = BezierPath(None) path.moveto(points[0].x, points[0].y) for i in range(len(points) - 1): path.curveto(points[i].x + dx[i], points[i].y + dy[i], points[i + 1].x - dx[i + 1], points[i + 1].y - dy[i + 1], points[i + 1].x, points[i + 1].y) return path
def makeAbsolute(self, p): if self.isRelativeCommand(): return Point(p.x + self.current.x, p.y + self.current.y) return p
def getPoint(self): pt = Point(self.getScalar(), self.getScalar()) return self.makeAbsolute(pt)
def parse_path(e): d = get_attribute(e, "d", default="") d = re.sub(r",", r" ", d) # get rid of all commas d = re.sub(r"([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])", r"\1 \2", d) # separate commands from commands d = re.sub(r"([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])", r"\1 \2", d) # separate commands from commands d = re.sub(r"([MmZzLlHhVvCcSsQqTtAa])([^\s])", r"\1 \2", d) # separate commands from points d = re.sub(r"([^\s])([MmZzLlHhVvCcSsQqTtAa])", r"\1 \2", d) # separate commands from points d = re.sub(r"([0-9])([+\-])", r"\1 \2", d) # separate digits when no comma d = re.sub(r"(\.[0-9]*)(\.)", r"\1 \2", d) # separate digits when no comma d = re.sub(r"([Aa](\s+[0-9]+){3})\s+([01])\s*([01])", r"\1 \3 \4 ", d) # shorthand elliptical arc path syntax d = re.sub(r"[\s\r\t\n]+", r" ", d) d = d.strip() path = Path() pp = PathParser(d) pp.reset() while not pp.isEnd(): pp.nextCommand() command = pp.command.lower() if command == 'm': p = pp.getAsCurrentPoint() path.moveto(p.x, p.y) pp.start = pp.current while not pp.isCommandOrEnd(): p = pp.getAsCurrentPoint() path.lineto(p.x, p.y) elif command == 'l': while not pp.isCommandOrEnd(): p = pp.getAsCurrentPoint() path.lineto(p.x, p.y) elif command == 'h': while not pp.isCommandOrEnd(): newP = Point((pp.isRelativeCommand() and pp.current.x or 0) + pp.getScalar(), pp.current.y) pp.current = newP path.lineto(pp.current.x, pp.current.y) elif command == 'v': while not pp.isCommandOrEnd(): newP = Point(pp.current.x, (pp.isRelativeCommand() and pp.current.y or 0) + pp.getScalar()) pp.current = newP path.lineto(pp.current.x, pp.current.y) elif command == 'c': while not pp.isCommandOrEnd(): curr = pp.current p1 = pp.getPoint() cntrl = pp.getAsControlPoint() cp = pp.getAsCurrentPoint() path.curveto(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y) elif command == 's': while not pp.isCommandOrEnd(): curr = pp.current p1 = pp.getReflectedControlPoint() cntrl = pp.getAsControlPoint() cp = pp.getAsCurrentPoint() path.curveto(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y) elif command == 'q': while not pp.isCommandOrEnd(): curr = pp.current cntrl = pp.getAsControlPoint() cp = pp.getAsCurrentPoint() cp1x = curr.x + 2 / 3.0 * (cntrl.x - curr.x ) # CP1 = QP0 + 2 / 3 *(QP1-QP0) cp1y = curr.y + 2 / 3.0 * (cntrl.y - curr.y ) # CP1 = QP0 + 2 / 3 *(QP1-QP0) cp2x = cp1x + 1 / 3.0 * (cp.x - curr.x ) # CP2 = CP1 + 1 / 3 *(QP2-QP0) cp2y = cp1y + 1 / 3.0 * (cp.y - curr.y ) # CP2 = CP1 + 1 / 3 *(QP2-QP0) g.curveto(cp1x, cp1y, cp2x, cp2y, cp.x, cp.y) elif command == 't': while not pp.isCommandOrEnd(): curr = pp.current cntrl = pp.getReflectedControlPoint() pp.control = cntrl cp = pp.getAsCurrentPoint() cp1x = curr.x + 2 / 3.0 * (cntrl.x - curr.x ) # CP1 = QP0 + 2 / 3 *(QP1-QP0) cp1y = curr.y + 2 / 3.0 * (cntrl.y - curr.y ) # CP1 = QP0 + 2 / 3 *(QP1-QP0) cp2x = cp1x + 1 / 3.0 * (cp.x - curr.x ) # CP2 = CP1 + 1 / 3 *(QP2-QP0) cp2y = cp1y + 1 / 3.0 * (cp.y - curr.y ) # CP2 = CP1 + 1 / 3 *(QP2-QP0) path.curveto(cp1x, cp1y, cp2x, cp2y, cp.x, cp.y) elif command == 'a': while not pp.isCommandOrEnd(): curr = pp.current rx = pp.getScalar() ry = pp.getScalar() rot = pp.getScalar() # * (math.pi / 180.0) large = pp.getScalar() sweep = pp.getScalar() cp = pp.getAsCurrentPoint() ex = cp.x ey = cp.y segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, curr.x, curr.y) for seg in segs: bez = segmentToBezier(*seg) path.curveto(*bez) elif command == 'z': path.close() pp.current = pp.start return path
def center_point(shape): if shape is None: return Point.ZERO bounds = shape.bounds return Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2)
def make_point(x, y): return Point(x, y)
def __init__(self, path=None, file="path", freehand=False): if path != None: self.path = path self._points = list(path) for pt in self._points: pt.freehand = False if pt.cmd == LINETO or pt.cmd == MOVETO: pt.ctrl1 = Point(pt.x, pt.y) pt.ctrl2 = Point(pt.x, pt.y) else: self.path = None self._points = [] # These variables discern between different # modes of interaction. # In add-mode, new contains the last point added. # In edit-mode, edit contains the index of the point # in the path being edited. self.new = None self.edit = None self.editing = False self.insert = False self.inserting = False self.drag_point = False self.drag_handle1 = False self.drag_handle2 = False self.freehand = freehand self.freehand_move = True # Colors used to draw interface elements. self.strokewidth = 0.75 self.path_color = _ctx.color(0.2) self.path_fill = _ctx.color(0,0,0,0) self.handle_color = _ctx.color(0.6) self.new_color = _ctx.color(0.8) # Checks whether the SVG export file # should be updated based on the user's edits. self._dirty = False self.file = file # Different states for button actions. # When delete contains a number, # delete that index from the path. # When moveto contains True, # do a MOVETO before adding the next new point. self.delete = None self.moveto = None self.last_moveto = None self.btn_r = 5 self.btn_x = -5-1 self.btn_y = -5*2 # Magnetic grid to snap to when enabled. self.grid = MagneticGrid() self.show_grid = False # Keyboard keys pressed. self.last_key = None self.last_keycode = None # A message to flash on the screen. self.msg = "" self.msg_alpha = 1.0
def insert_point(self, x, y): """ Inserts a point on the path at the mouse location. We first need to check if the mouse location is on the path. Inserting point is time intensive and experimental. """ try: bezier = _ctx.ximport("bezier") except: from nodebox.graphics import bezier # Do a number of checks distributed along the path. # Keep the one closest to the actual mouse location. # Ten checks works fast but leads to imprecision in sharp corners # and curves closely located next to each other. # I prefer the slower but more stable approach. n = 100 closest = None dx0 = float(INFINITY) dy0 = float(INFINITY) for i in range(n): t = float(i)/n pt = self.path.point(t) dx = abs(pt.x-x) dy = abs(pt.y-y) if dx+dy <= dx0+dy0: dx0 = dx dy0 = dy closest = t # Next, scan the area around the approximation. # If the closest point is located at 0.2 on the path, # we need to scan between 0.1 and 0.3 for a better # approximation. If 1.5 was the best guess, scan # 1.40, 1.41 ... 1.59 and so on. # Each decimal precision takes 20 iterations. decimals = [3,4] for d in decimals: d = 1.0/pow(10,d) for i in range(20): t = closest-d + float(i)*d*0.1 if t < 0.0: t = 1.0+t if t > 1.0: t = t-1.0 pt = self.path.point(t) dx = abs(pt.x-x) dy = abs(pt.y-y) if dx <= dx0 and dy <= dy0: dx0 = dx dy0 = dy closest_precise = t closest = closest_precise # Update the points list with the inserted point. p = bezier.insert_point(self.path, closest_precise) i, t, pt = bezier._locate(self.path, closest_precise) i += 1 pt = PathElement() pt.cmd = p[i].cmd pt.x = p[i].x pt.y = p[i].y pt.ctrl1 = Point(p[i].ctrl1.x, p[i].ctrl1.y) pt.ctrl2 = Point(p[i].ctrl2.x, p[i].ctrl2.y) pt.freehand = False self._points.insert(i, pt) self._points[i-1].ctrl1 = Point(p[i-1].ctrl1.x, p[i-1].ctrl1.y) self._points[i+1].ctrl1 = Point(p[i+1].ctrl1.x, p[i+1].ctrl1.y) self._points[i+1].ctrl2 = Point(p[i+1].ctrl2.x, p[i+1].ctrl2.y)