diff options
| author | Lex Neva <github.com@lexneva.name> | 2018-08-16 16:36:39 -0400 |
|---|---|---|
| committer | Lex Neva <github.com@lexneva.name> | 2018-08-16 16:36:39 -0400 |
| commit | 284748a682d4aa95c91cc215d5945181c833de15 (patch) | |
| tree | 6334f284489243be5634fc811401de10631a87dd /lib | |
| parent | 64062f7cd7eee9ed5701209618b0564a211c494b (diff) | |
| parent | 0f882f07eb0fc263fcb8e05c1a212199902863da (diff) | |
Merge branch 'master' into lexelby-no-embroider-command
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/elements/auto_fill.py | 49 | ||||
| -rw-r--r-- | lib/elements/fill.py | 40 | ||||
| -rw-r--r-- | lib/elements/satin_column.py | 71 | ||||
| -rw-r--r-- | lib/elements/stroke.py | 46 | ||||
| -rw-r--r-- | lib/extensions/__init__.py | 1 | ||||
| -rw-r--r-- | lib/extensions/commands.py | 21 | ||||
| -rw-r--r-- | lib/extensions/convert_to_satin.py | 289 | ||||
| -rw-r--r-- | lib/extensions/params.py | 2 | ||||
| -rw-r--r-- | lib/simulator.py | 49 | ||||
| -rw-r--r-- | lib/stitches/running_stitch.py | 29 | ||||
| -rw-r--r-- | lib/svg/__init__.py | 2 | ||||
| -rw-r--r-- | lib/svg/path.py | 23 |
12 files changed, 558 insertions, 64 deletions
diff --git a/lib/elements/auto_fill.py b/lib/elements/auto_fill.py index 59816878..79220a86 100644 --- a/lib/elements/auto_fill.py +++ b/lib/elements/auto_fill.py @@ -30,7 +30,12 @@ class AutoFill(Fill): return False @property - @param('running_stitch_length_mm', _('Running stitch length (traversal between sections)'), unit='mm', type='float', default=1.5) + @param('running_stitch_length_mm', + _('Running stitch length (traversal between sections)'), + tooltip=_('Length of stitches around the outline of the fill region used when moving from section to section.'), + unit='mm', + type='float', + default=1.5) def running_stitch_length(self): return max(self.get_float_param("running_stitch_length_mm", 1.5), 0.01) @@ -40,7 +45,12 @@ class AutoFill(Fill): return self.get_boolean_param("fill_underlay", default=False) @property - @param('fill_underlay_angle', _('Fill angle (default: fill angle + 90 deg)'), unit='deg', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_angle', + _('Fill angle'), + tooltip=_('default: fill angle + 90 deg'), + unit='deg', + group=_('AutoFill Underlay'), + type='float') @cache def fill_underlay_angle(self): underlay_angle = self.get_float_param("fill_underlay_angle") @@ -51,35 +61,44 @@ class AutoFill(Fill): return self.angle + math.pi / 2.0 @property - @param('fill_underlay_row_spacing_mm', _('Row spacing (default: 3x fill row spacing)'), unit='mm', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_row_spacing_mm', + _('Row spacing'), + tooltip=_('default: 3x fill row spacing'), + unit='mm', + group=_('AutoFill Underlay'), + type='float') @cache def fill_underlay_row_spacing(self): return self.get_float_param("fill_underlay_row_spacing_mm") or self.row_spacing * 3 @property - @param('fill_underlay_max_stitch_length_mm', _('Max stitch length'), unit='mm', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_max_stitch_length_mm', + _('Max stitch length'), + tooltip=_('default: equal to fill max stitch length'), + unit='mm', + group=_('AutoFill Underlay'), type='float') @cache def fill_underlay_max_stitch_length(self): return self.get_float_param("fill_underlay_max_stitch_length_mm") or self.max_stitch_length @property @param('fill_underlay_inset_mm', - _('Inset'), - tooltip='Shrink the shape before doing underlay, to prevent underlay from showing around the outside of the fill.', - unit='mm', - group=_('AutoFill Underlay'), - type='float', - default=0) + _('Inset'), + tooltip=_('Shrink the shape before doing underlay, to prevent underlay from showing around the outside of the fill.'), + unit='mm', + group=_('AutoFill Underlay'), + type='float', + default=0) def fill_underlay_inset(self): return self.get_float_param('fill_underlay_inset_mm', 0) @property @param('expand_mm', - _('Expand'), - tooltip='Expand the shape before fill stitching, to compensate for gaps between shapes.', - unit='mm', - type='float', - default=0) + _('Expand'), + tooltip=_('Expand the shape before fill stitching, to compensate for gaps between shapes.'), + unit='mm', + type='float', + default=0) def expand(self): return self.get_float_param('expand_mm', 0) diff --git a/lib/elements/fill.py b/lib/elements/fill.py index 8d1d35f2..8018b2b4 100644 --- a/lib/elements/fill.py +++ b/lib/elements/fill.py @@ -15,12 +15,22 @@ class Fill(EmbroideryElement): super(Fill, self).__init__(*args, **kwargs) @property - @param('auto_fill', _('Manually routed fill stitching'), type='toggle', inverse=True, default=True) + @param('auto_fill', + _('Manually routed fill stitching'), + tooltip=_('AutoFill is the default method for generating fill stitching.'), + type='toggle', + inverse=True, + default=True) def auto_fill(self): return self.get_boolean_param('auto_fill', True) @property - @param('angle', _('Angle of lines of stitches'), unit='deg', type='float', default=0) + @param('angle', + _('Angle of lines of stitches'), + tooltip=_('The angle increases in a counter-clockwise direction. 0 is horizontal. Negative angles are allowed.'), + unit='deg', + type='float', + default=0) @cache def angle(self): return math.radians(self.get_float_param('angle', 0)) @@ -31,12 +41,21 @@ class Fill(EmbroideryElement): return self.get_style("fill", "#000000") @property - @param('flip', _('Flip fill (start right-to-left)'), type='boolean', default=False) + @param('flip', + _('Flip fill (start right-to-left)'), + tooltip=_('The flip option can help you with routing your stitch path. When you enable flip, stitching goes from right-to-left instead of left-to-right.'), + type='boolean', + default=False) def flip(self): return self.get_boolean_param("flip", False) @property - @param('row_spacing_mm', _('Spacing between rows'), unit='mm', type='float', default=0.25) + @param('row_spacing_mm', + _('Spacing between rows'), + tooltip=_('Distance between rows of stitches.'), + unit='mm', + type='float', + default=0.25) def row_spacing(self): return max(self.get_float_param("row_spacing_mm", 0.25), 0.1 * PIXELS_PER_MM) @@ -45,12 +64,21 @@ class Fill(EmbroideryElement): return self.get_float_param("end_row_spacing_mm") @property - @param('max_stitch_length_mm', _('Maximum fill stitch length'), unit='mm', type='float', default=3.0) + @param('max_stitch_length_mm', + _('Maximum fill stitch length'), + tooltip=_('The length of each stitch in a row. Shorter stitch may be used at the start or end of a row.'), + unit='mm', + type='float', + default=3.0) def max_stitch_length(self): return max(self.get_float_param("max_stitch_length_mm", 3.0), 0.1 * PIXELS_PER_MM) @property - @param('staggers', _('Stagger rows this many times before repeating'), type='int', default=4) + @param('staggers', + _('Stagger rows this many times before repeating'), + tooltip=_('Setting this dictates how many rows apart the stitches will be before they fall in the same column position.'), + type='int', + default=4) def staggers(self): return self.get_int_param("staggers", 4) diff --git a/lib/elements/satin_column.py b/lib/elements/satin_column.py index 2ceb38de..834509fd 100644 --- a/lib/elements/satin_column.py +++ b/lib/elements/satin_column.py @@ -17,18 +17,34 @@ class SatinColumn(EmbroideryElement): def satin_column(self): return self.get_boolean_param("satin_column") + # I18N: "E" stitch is so named because it looks like the letter E. + @property + @param('e_stitch', _('"E" stitch'), type='boolean', default='false') + def e_stitch(self): + return self.get_boolean_param("e_stitch") + @property def color(self): return self.get_style("stroke") @property - @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4) + @param('zigzag_spacing_mm', + _('Zig-zag spacing (peak-to-peak)'), + tooltip=_('Peak-to-peak distance between zig-zags.'), + unit='mm', + type='float', + default=0.4) def zigzag_spacing(self): # peak-to-peak distance between zigzags return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('pull_compensation_mm', _('Pull compensation'), unit='mm', type='float') + @param('pull_compensation_mm', + _('Pull compensation'), + tooltip=_('Satin stitches pull the fabric together, resulting in a column narrower than you draw in Inkscape. This setting expands each pair of needle penetrations outward from the center of the satin column.'), + unit='mm', + type='float', + default=0) def pull_compensation(self): # In satin stitch, the stitches have a tendency to pull together and # narrow the entire column. We can compensate for this by stitching @@ -48,7 +64,13 @@ class SatinColumn(EmbroideryElement): return max(self.get_float_param("contour_underlay_stitch_length_mm", 1.5), 0.01) @property - @param('contour_underlay_inset_mm', _('Contour underlay inset amount'), unit='mm', group=_('Contour Underlay'), type='float', default=0.4) + @param('contour_underlay_inset_mm', + _('Contour underlay inset amount'), + tooltip=_('Shrink the outline, to prevent the underlay from showing around the outside of the satin column.'), + unit='mm', + group=_('Contour Underlay'), + type='float', + default=0.4) def contour_underlay_inset(self): # how far inside the edge of the column to stitch the underlay return self.get_float_param("contour_underlay_inset_mm", 0.4) @@ -71,12 +93,24 @@ class SatinColumn(EmbroideryElement): return self.get_boolean_param("zigzag_underlay") @property - @param('zigzag_underlay_spacing_mm', _('Zig-Zag spacing (peak-to-peak)'), unit='mm', group=_('Zig-zag Underlay'), type='float', default=3) + @param('zigzag_underlay_spacing_mm', + _('Zig-Zag spacing (peak-to-peak)'), + tooltip=_('Distance between peaks of the zig-zags.'), + unit='mm', + group=_('Zig-zag Underlay'), + type='float', + default=3) def zigzag_underlay_spacing(self): return max(self.get_float_param("zigzag_underlay_spacing_mm", 3), 0.01) @property - @param('zigzag_underlay_inset_mm', _('Inset amount (default: half of contour underlay inset)'), unit='mm', group=_('Zig-zag Underlay'), type='float') + @param('zigzag_underlay_inset_mm', + _('Inset amount'), + tooltip=_('default: half of contour underlay inset'), + unit='mm', + group=_('Zig-zag Underlay'), + type='float', + default="") def zigzag_underlay_inset(self): # how far in from the edge of the satin the points in the zigzags # should be @@ -388,6 +422,28 @@ class SatinColumn(EmbroideryElement): return patch + def do_e_stitch(self): + # e stitch: do a pattern that looks like the letter "E". It looks like + # this: + # + # _|_|_|_|_|_|_|_|_|_|_|_| + + # print >> dbg, "satin", self.zigzag_spacing, self.pull_compensation + + patch = Patch(color=self.color) + + sides = self.walk_paths(self.zigzag_spacing, self.pull_compensation) + + # "left" and "right" here are kind of arbitrary designations meaning + # a point from the first and second rail repectively + for left, right in izip(*sides): + patch.add_stitch(left) + patch.add_stitch(right) + patch.add_stitch(left) + + return patch + + def to_patches(self, last_patch): # Stitch a variable-width satin column, zig-zagging between two paths. @@ -411,6 +467,9 @@ class SatinColumn(EmbroideryElement): # zigzags sit on the contour walk underlay like rail ties on rails. patches.append(self.do_zigzag_underlay()) - patches.append(self.do_satin()) + if self.e_stitch: + patches.append(self.do_e_stitch()) + else: + patches.append(self.do_satin()) return patches diff --git a/lib/elements/stroke.py b/lib/elements/stroke.py index e8eb4783..e84d5e79 100644 --- a/lib/elements/stroke.py +++ b/lib/elements/stroke.py @@ -4,7 +4,7 @@ import shapely.geometry from .element import param, EmbroideryElement, Patch from ..i18n import _ from ..utils import cache, Point -from ..stitches import running_stitch +from ..stitches import running_stitch, bean_stitch from ..svg import parse_length_with_units warned_about_legacy_running_stitch = False @@ -27,18 +27,45 @@ class Stroke(EmbroideryElement): return self.get_style("stroke-dasharray") is not None @property - @param('running_stitch_length_mm', _('Running stitch length'), unit='mm', type='float', default=1.5) + @param('running_stitch_length_mm', + _('Running stitch length'), + tooltip=_('Length of stitches in running stitch mode.'), + unit='mm', + type='float', + default=1.5, + sort_index=3) def running_stitch_length(self): return max(self.get_float_param("running_stitch_length_mm", 1.5), 0.01) @property - @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4) + @param('bean_stitch_repeats', + _('Bean stitch number of repeats'), + tooltip=_('Backtrack each stitch this many times. A value of 1 would triple each stitch (forward, back, forward). A value of 2 would quintuple each stitch, etc. Only applies to running stitch.'), + type='int', + default=0, + sort_index=2) + def bean_stitch_repeats(self): + return self.get_int_param("bean_stitch_repeats", 0) + + @property + @param('zigzag_spacing_mm', + _('Zig-zag spacing (peak-to-peak)'), + tooltip=_('Length of stitches in zig-zag mode.'), + unit='mm', + type='float', + default=0.4, + sort_index=3) @cache def zigzag_spacing(self): return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('repeats', _('Repeats'), type='int', default="1") + @param('repeats', + _('Repeats'), + tooltip=_('Defines how many times to run down and back along the path.'), + type='int', + default="1", + sort_index=1) def repeats(self): return self.get_int_param("repeats", 1) @@ -58,7 +85,12 @@ class Stroke(EmbroideryElement): return shapely.geometry.MultiLineString(line_strings) @property - @param('manual_stitch', _('Manual stitch placement'), tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), type='boolean', default=False) + @param('manual_stitch', + _('Manual stitch placement'), + tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), + type='boolean', + default=False, + sort_index=0) def manual_stitch_mode(self): return self.get_boolean_param('manual_stitch') @@ -152,6 +184,10 @@ class Stroke(EmbroideryElement): patch = Patch(color=self.color, stitches=path, stitch_as_is=True) elif self.is_running_stitch(): patch = self.running_stitch(path, self.running_stitch_length) + + if self.bean_stitch_repeats > 0: + patch.stitches = bean_stitch(patch.stitches, self.bean_stitch_repeats) + else: patch = self.simple_satin(path, self.zigzag_spacing, self.stroke_width) diff --git a/lib/extensions/__init__.py b/lib/extensions/__init__.py index 8b243176..30a08c9f 100644 --- a/lib/extensions/__init__.py +++ b/lib/extensions/__init__.py @@ -8,3 +8,4 @@ from output import Output from zip import Zip from flip import Flip from commands import Commands +from convert_to_satin import ConvertToSatin diff --git a/lib/extensions/commands.py b/lib/extensions/commands.py index b22b5d84..0924845c 100644 --- a/lib/extensions/commands.py +++ b/lib/extensions/commands.py @@ -12,7 +12,7 @@ from ..i18n import _ from ..elements import SatinColumn from ..utils import get_bundled_dir, cache from ..svg.tags import SVG_DEFS_TAG, SVG_GROUP_TAG, SVG_USE_TAG, SVG_PATH_TAG, INKSCAPE_GROUPMODE, XLINK_HREF, CONNECTION_START, CONNECTION_END, CONNECTOR_TYPE -from ..svg import get_node_transform +from ..svg import get_correction_transform class Commands(InkstitchExtension): @@ -48,21 +48,6 @@ class Commands(InkstitchExtension): if self.defs.find(path) is None: self.defs.append(deepcopy(self.symbol_defs.find(path))) - def get_correction_transform(self, node): - # if we want to place our new nodes in the same group as this node, - # then we'll need to factor in the effects of any transforms set on - # the parents of this node. - - # we can ignore the transform on the node itself since it won't apply - # to the objects we add - transform = get_node_transform(node.getparent()) - - # now invert it, so that we can position our objects in absolute - # coordinates - transform = simpletransform.invertTransform(transform) - - return simpletransform.formatTransform(transform) - def add_connector(self, symbol, element): # I'd like it if I could position the connector endpoint nicely but inkscape just # moves it to the element's center immediately after the extension runs. @@ -74,7 +59,7 @@ class Commands(InkstitchExtension): "id": self.uniqueId("connector"), "d": "M %s,%s %s,%s" % (start_pos[0], start_pos[1], end_pos.x, end_pos.y), "style": "stroke:#000000;stroke-width:1px;stroke-opacity:0.5;fill:none;", - "transform": self.get_correction_transform(symbol), + "transform": get_correction_transform(symbol), CONNECTION_START: "#%s" % symbol.get('id'), CONNECTION_END: "#%s" % element.node.get('id'), CONNECTOR_TYPE: "polyline", @@ -126,7 +111,7 @@ class Commands(InkstitchExtension): "width": "100%", "x": str(pos.x), "y": str(pos.y), - "transform": self.get_correction_transform(element.node) + "transform": get_correction_transform(element.node) } ) diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py new file mode 100644 index 00000000..dd5a9bc2 --- /dev/null +++ b/lib/extensions/convert_to_satin.py @@ -0,0 +1,289 @@ +import inkex +from shapely import geometry as shgeo +from itertools import chain, groupby +import numpy +from numpy import diff, sign, setdiff1d +import math +from copy import deepcopy + +from .base import InkstitchExtension +from ..svg.tags import SVG_PATH_TAG +from ..svg import get_correction_transform, PIXELS_PER_MM +from ..elements import Stroke +from ..utils import Point + + +class SelfIntersectionError(Exception): + pass + + +class ConvertToSatin(InkstitchExtension): + """Convert a line to a satin column of the same width.""" + + def effect(self): + if not self.get_elements(): + return + + if not self.selected: + inkex.errormsg(_("Please select at least one line to convert to a satin column.")) + return + + if not all(isinstance(item, Stroke) for item in self.elements): + # L10N: Convert To Satin extension, user selected one or more objects that were not lines. + inkex.errormsg(_("Only simple lines may be converted to satin columns.")) + return + + for element in self.elements: + parent = element.node.getparent() + index = parent.index(element.node) + correction_transform = get_correction_transform(element.node) + style_args = self.join_style_args(element) + + for path in element.paths: + path = self.remove_duplicate_points(path) + + if len(path) < 2: + # ignore paths with just one point -- they're not visible to the user anyway + continue + + self.fix_loop(path) + + try: + rails, rungs = self.path_to_satin(path, element.stroke_width, style_args) + except SelfIntersectionError: + inkex.errormsg(_("Cannot convert %s to a satin column because it intersects itself. Try breaking it up into multiple paths.") % element.node.get('id')) + + # revert any changes we've made + self.document = deepcopy(self.original_document) + + return + + parent.insert(index, self.satin_to_svg_node(rails, rungs, correction_transform)) + + parent.remove(element.node) + + def fix_loop(self, path): + if path[0] == path[-1]: + # Looping paths seem to confuse shapely's parallel_offset(). It loses track + # of where the start and endpoint is, even if the user explicitly breaks the + # path. I suspect this is because parallel_offset() uses buffer() under the + # hood. + # + # To work around this we'll introduce a tiny gap by nudging the starting point + # toward the next point slightly. + start = Point(*path[0]) + next = Point(*path[1]) + direction = (next - start).unit() + start += 0.01 * direction + path[0] = start.as_tuple() + + def remove_duplicate_points(self, path): + return [point for point, repeats in groupby(path)] + + def join_style_args(self, element): + """Convert svg line join style to shapely parallel offset arguments.""" + + args = { + 'join_style': shgeo.JOIN_STYLE.round + } + + element_join_style = element.get_style('stroke-linejoin') + + if element_join_style is not None: + if element_join_style == "miter": + args['join_style'] = shgeo.JOIN_STYLE.mitre + + # 4 is the default per SVG spec + miter_limit = float(element.get_style('stroke-miterlimit', 4)) + args['mitre_limit'] = miter_limit + elif element_join_style == "bevel": + args['join_style'] = shgeo.JOIN_STYLE.bevel + + return args + + def path_to_satin(self, path, stroke_width, style_args): + path = shgeo.LineString(path) + + left_rail = path.parallel_offset(stroke_width / 2.0, 'left', **style_args) + right_rail = path.parallel_offset(stroke_width / 2.0, 'right', **style_args) + + if not isinstance(left_rail, shgeo.LineString) or \ + not isinstance(right_rail, shgeo.LineString): + # If the parallel offsets come out as anything but a LineString, that means the + # path intersects itself, when taking its stroke width into consideration. See + # the last example for parallel_offset() in the Shapely documentation: + # https://shapely.readthedocs.io/en/latest/manual.html#object.parallel_offset + raise SelfIntersectionError() + + # for whatever reason, shapely returns a right-side offset's coordinates in reverse + left_rail = list(left_rail.coords) + right_rail = list(reversed(right_rail.coords)) + + rungs = self.generate_rungs(path, stroke_width) + + return (left_rail, right_rail), rungs + + def get_scores(self, path): + """Generate an array of "scores" of the sharpness of corners in a path + + A higher score means that there are sharper corners in that section of + the path. We'll divide the path into boxes, with the score in each + box indicating the sharpness of corners at around that percentage of + the way through the path. For example, if scores[40] is 100 and + scores[45] is 200, then the path has sharper corners at a spot 45% + along its length than at a spot 40% along its length. + """ + + # need 101 boxes in order to encompass percentages from 0% to 100% + scores = numpy.zeros(101, numpy.int32) + path_length = path.length + + prev_point = None + prev_direction = None + length_so_far = 0 + for point in path.coords: + point = Point(*point) + + if prev_point is None: + prev_point = point + continue + + direction = (point - prev_point).unit() + + if prev_direction is not None: + # The dot product of two vectors is |v1| * |v2| * cos(angle). + # These are unit vectors, so their magnitudes are 1. + cos_angle_between = prev_direction * direction + angle = abs(math.degrees(math.acos(cos_angle_between))) + + # Use the square of the angle, measured in degrees. + # + # Why the square? This penalizes bigger angles more than + # smaller ones. + # + # Why degrees? This is kind of arbitrary but allows us to + # use integer math effectively and avoid taking the square + # of a fraction between 0 and 1. + scores[int(round(length_so_far / path_length * 100.0))] += angle ** 2 + + length_so_far += (point - prev_point).length() + prev_direction = direction + prev_point = point + + return scores + + def local_minima(self, array): + # from: https://stackoverflow.com/a/9667121/4249120 + # This finds spots where the curvature (second derivative) is > 0. + # + # This method has the convenient benefit of choosing points around + # 5% before and after a sharp corner such as in a square. + return (diff(sign(diff(array))) > 0).nonzero()[0] + 1 + + def generate_rungs(self, path, stroke_width): + """Create rungs for a satin column. + + Where should we put the rungs along a path? We want to ensure that the + resulting satin matches the original path as closely as possible. We + want to avoid having a ton of rungs that will annoy the user. We want + to ensure that the rungs we choose actually intersect both rails. + + We'll place a few rungs perpendicular to the tangent of the path. + Things get pretty tricky at sharp corners. If we naively place a rung + perpendicular to the path just on either side of a sharp corner, the + rung may not intersect both paths: + | | + _______________| | + ______|_ + ____________________| + + It'd be best to place rungs in the straight sections before and after + the sharp corner and allow the satin column to bend the stitches around + the corner automatically. + + How can we find those spots? + + The general algorithm below is: + + * assign a "score" to each section of the path based on how sharp its + corners are (higher means a sharper corner) + * pick spots with lower scores + """ + + scores = self.get_scores(path) + + # This is kind of like a 1-dimensional gaussian blur filter. We want to + # avoid the area near a sharp corner, so we spread out its effect for + # 5 buckets in either direction. + scores = numpy.convolve(scores, [1, 2, 4, 8, 16, 8, 4, 2, 1], mode='same') + + # Now we'll find the spots that aren't near corners, whose scores are + # low -- the local minima. + rung_locations = self.local_minima(scores) + + # Remove the start and end, because we can't stick a rung there. + rung_locations = setdiff1d(rung_locations, [0, 100]) + + if len(rung_locations) == 0: + # Straight lines won't have local minima, so add a rung in the center. + rung_locations = [50] + + rungs = [] + last_rung_center = None + + for location in rung_locations: + # Convert percentage to a fraction so that we can use interpolate's + # normalized parameter. + location = location / 100.0 + + rung_center = path.interpolate(location, normalized=True) + rung_center = Point(rung_center.x, rung_center.y) + + # Avoid placing rungs too close together. This somewhat + # arbitrarily rejects the rung if there was one less than 2 + # millimeters before this one. + if last_rung_center is not None and \ + (rung_center - last_rung_center).length() < 2 * PIXELS_PER_MM: + continue + else: + last_rung_center = rung_center + + # We need to know the tangent of the path's curve at this point. + # Pick another point just after this one and subtract them to + # approximate a tangent vector. + tangent_end = path.interpolate(location + 0.001, normalized=True) + tangent_end = Point(tangent_end.x, tangent_end.y) + tangent = (tangent_end - rung_center).unit() + + # Rotate 90 degrees left to make a normal vector. + normal = tangent.rotate_left() + + # Travel 75% of the stroke width left and right to make the rung's + # endpoints. This means the rung's length is 150% of the stroke + # width. + offset = normal * stroke_width * 0.75 + rung_start = rung_center + offset + rung_end = rung_center - offset + + rungs.append((rung_start.as_tuple(), rung_end.as_tuple())) + + return rungs + + + def satin_to_svg_node(self, rails, rungs, correction_transform): + d = "" + for path in chain(rails, rungs): + d += "M" + for x, y in path: + d += "%s,%s " % (x, y) + d += " " + + return inkex.etree.Element(SVG_PATH_TAG, + { + "id": self.uniqueId("path"), + "style": "stroke:#000000;stroke-width:1px;fill:none", + "transform": correction_transform, + "d": d, + "embroider_satin_column": "true", + } + ) diff --git a/lib/extensions/params.py b/lib/extensions/params.py index 58fedd6b..1b8f2589 100644 --- a/lib/extensions/params.py +++ b/lib/extensions/params.py @@ -424,7 +424,7 @@ class SettingsFrame(wx.Frame): self.simulate_window.stop() self.simulate_window.load(stitch_plan=stitch_plan) else: - my_rect = self.GetRect() + my_rect = self.GetScreenRect() simulator_pos = my_rect.GetTopRight() simulator_pos.x += 5 diff --git a/lib/simulator.py b/lib/simulator.py index c7e74353..2d2d3e08 100644 --- a/lib/simulator.py +++ b/lib/simulator.py @@ -27,6 +27,26 @@ class EmbroiderySimulator(wx.Frame): self.panel = wx.Panel(self, wx.ID_ANY) self.panel.SetFocus() + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) + + self.button_label = ( + [_("Speed up"),_('Press + or arrow up to speed up')], + [_("Slow down"),_('Press - or arrow down to slow down')], + [_("Pause"),_("Press P to pause the animation")], + [_("Restart"),_("Press R to restart the animation")], + [_("Quit"),_("Press Q to close the simulation window")]) + self.buttons = [] + for i in range(0, len(self.button_label)): + self.buttons.append(wx.Button(self, -1, self.button_label[i][0])) + self.button_sizer.Add(self.buttons[i], 1, wx.EXPAND) + self.buttons[i].Bind(wx.EVT_BUTTON, self.on_key_down) + self.buttons[i].SetToolTip(self.button_label[i][1]) + + self.sizer.Add(self.panel, 1, wx.EXPAND) + self.sizer.Add(self.button_sizer, 0, wx.EXPAND) + self.SetSizer(self.sizer) + self.load(stitch_plan) if self.target_duration: @@ -68,26 +88,30 @@ class EmbroiderySimulator(wx.Frame): self.stitches_per_frame *= 2 def on_key_down(self, event): - keycode = event.GetKeyCode() + if hasattr(event, 'GetKeyCode'): + keycode = event.GetKeyCode() + else: + keycode = event.GetEventObject().GetLabelText() + self.panel.SetFocus() - if keycode == ord("+") or keycode == ord("=") or keycode == wx.WXK_UP: + if keycode == ord("+") or keycode == ord("=") or keycode == wx.WXK_UP or keycode == "Speed up": if self.frame_period == 1: self.stitches_per_frame *= 2 else: self.frame_period = self.frame_period / 2 - elif keycode == ord("-") or keycode == ord("_") or keycode == wx.WXK_DOWN: + elif keycode == ord("-") or keycode == ord("_") or keycode == wx.WXK_DOWN or keycode == "Slow down": if self.stitches_per_frame == 1: self.frame_period *= 2 else: self.stitches_per_frame /= 2 - elif keycode == ord("Q"): + elif keycode == ord("Q") or keycode == "Quit": self.Close() - elif keycode == ord('P'): + elif keycode == ord("P") or keycode == "Pause": if self.timer.IsRunning(): self.timer.Stop() else: self.timer.Start(self.frame_period) - elif keycode == ord("R"): + elif keycode == ord("R") or keycode == "Restart": self.stop() self.clear() self.go() @@ -170,7 +194,7 @@ class EmbroiderySimulator(wx.Frame): self.width = width self.height = height - self.scale = min(float(self.max_width) / width, float(self.max_height) / height) + self.scale = min(float(self.max_width) / width, float(self.max_height - 60) / height) # make room for decorations and the margin self.scale *= 0.95 @@ -212,10 +236,15 @@ class EmbroiderySimulator(wx.Frame): client_width, client_height = self.GetClientSize() decorations_width = window_width - client_width - decorations_height = window_height - client_height + decorations_height = window_height - client_height + 40 + + setsize_window_width = self.width * self.scale + decorations_width + self.margin * 2 + setsize_window_height = (self.height) * self.scale + decorations_height + self.margin * 2 + + if setsize_window_width < 600: + setsize_window_width = 600 - self.SetSize((self.width * self.scale + decorations_width + self.margin * 2, - self.height * self.scale + decorations_height + self.margin * 2)) + self.SetSize(( setsize_window_width, setsize_window_height)) e.Skip() diff --git a/lib/stitches/running_stitch.py b/lib/stitches/running_stitch.py index 96075e7a..5f8ed21e 100644 --- a/lib/stitches/running_stitch.py +++ b/lib/stitches/running_stitch.py @@ -1,3 +1,6 @@ +from copy import copy + + """ Utility functions to produce running stitches. """ @@ -64,3 +67,29 @@ def running_stitch(points, stitch_length): output.append(segment_start) return output + + +def bean_stitch(stitches, repeats): + """Generate bean stitch from a set of stitches. + + "Bean" stitch is made by backtracking each stitch to make it heaver. A + simple bean stitch would be two stitches forward, one stitch back, two + stitches forward, etc. This would result in each stitch being tripled. + + We'll say that the above counts as 1 repeat. Backtracking each stitch + repeatedly will result in a heavier bean stitch. There will always be + an odd number of threads piled up for each stitch. + """ + + if len(stitches) < 2: + return stitches + + new_stitches = [stitches[0]] + + for stitch in stitches: + new_stitches.append(stitch) + + for i in xrange(repeats): + new_stitches.extend(copy(new_stitches[-2:])) + + return new_stitches diff --git a/lib/svg/__init__.py b/lib/svg/__init__.py index 8e846555..429e6b5e 100644 --- a/lib/svg/__init__.py +++ b/lib/svg/__init__.py @@ -1,3 +1,3 @@ from .svg import color_block_to_point_lists, render_stitch_plan from .units import * -from .path import apply_transforms, get_node_transform +from .path import apply_transforms, get_node_transform, get_correction_transform diff --git a/lib/svg/path.py b/lib/svg/path.py index 2d9c0ff3..52144332 100644 --- a/lib/svg/path.py +++ b/lib/svg/path.py @@ -15,11 +15,30 @@ def get_node_transform(node): # start with the identity transform transform = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] - # combine this node's transform with all parent groups' transforms - transform = simpletransform.composeParents(node, transform) + # this if is because sometimes inkscape likes to create paths outside of a layer?! + if node.getparent() is not None: + # combine this node's transform with all parent groups' transforms + transform = simpletransform.composeParents(node, transform) # add in the transform implied by the viewBox viewbox_transform = get_viewbox_transform(node.getroottree().getroot()) transform = simpletransform.composeTransform(viewbox_transform, transform) return transform + +def get_correction_transform(node): + """Get a transform to apply to new siblings of this SVG node""" + + # if we want to place our new nodes in the same group/layer as this node, + # then we'll need to factor in the effects of any transforms set on + # the parents of this node. + + # we can ignore the transform on the node itself since it won't apply + # to the objects we add + transform = get_node_transform(node.getparent()) + + # now invert it, so that we can position our objects in absolute + # coordinates + transform = simpletransform.invertTransform(transform) + + return simpletransform.formatTransform(transform) |
