cleaned some code

This commit is contained in:
leyghisbb 2021-04-18 18:21:23 +02:00
parent 41663ffd86
commit 313b0c3b63
13 changed files with 368 additions and 367 deletions

View File

@ -454,7 +454,7 @@ class FoldedCardLayoutGuidesEffect(inkex.EffectExtension):
### GUIDES
# remove all the existing guides
[node.getparent().remove(node) for node in self.document.xpath('//sodipodi:guide',namespaces=inkex.NSS)]
[node.delete() for node in self.document.xpath('//sodipodi:guide',namespaces=inkex.NSS)]
# create the generator object
gen = LineGeneratorBase.CreateLineGenerator(opt.layout, opt.orientation, opt.card_width, opt.card_height, opt.card_margin, opt.bleed_margin, pageWidth, pageHeight, opt.page_margin, self.svg.unittouu)
@ -463,7 +463,7 @@ class FoldedCardLayoutGuidesEffect(inkex.EffectExtension):
### FOLD LINES
# remove any existing 'Crop marks' layer
[node.getparent().remove(node) for node in self.document.xpath("//svg:g[@inkscape:label='Crop Marks']",namespaces=inkex.NSS)]
[node.delete() for node in self.document.xpath("//svg:g[@inkscape:label='Crop Marks']",namespaces=inkex.NSS)]
svg = self.document.xpath('//svg:svg', namespaces=inkex.NSS)[0]
layer = etree.SubElement(svg, inkex.addNS('g',"svg"), {})

View File

@ -435,7 +435,7 @@ class HexLayoutGuidesEffect(inkex.Effect):
### GUIDES
# remove all the existing guides
[node.getparent().remove(node) for node in self.document.xpath('//sodipodi:guide',namespaces=inkex.NSS)]
[node.delete() for node in self.document.xpath('//sodipodi:guide',namespaces=inkex.NSS)]
# create the object generator
gen = HexGeneratorBase.CreateHexGenerator(opt.HexDiameter, opt.HexMargin, opt.BleedMargin, pageWidth, pageHeight, opt.PageMargin, self.svg.unittouu)
@ -444,7 +444,7 @@ class HexLayoutGuidesEffect(inkex.Effect):
### CROP MARKS
# remove any existing 'Crop marks' layer
[node.getparent().remove(node) for node in self.document.xpath("//svg:g[@inkscape:label='Crop Marks']",namespaces=inkex.NSS)]
[node.delete() for node in self.document.xpath("//svg:g[@inkscape:label='Crop Marks']",namespaces=inkex.NSS)]
svg = self.document.xpath('//svg:svg', namespaces=inkex.NSS)[0]
layer = etree.SubElement(svg, inkex.addNS('g',"svg"), {})

View File

@ -124,7 +124,7 @@ class RemoveDuplicateGuidesEffect(inkex.EffectExtension):
# now remove all the excess guides
for serial in groups:
for guide in groups[serial][1:]: # keep the first member of group
guide.node.getparent().remove(guide.node)
guide.node.delete()
if __name__ == '__main__':
effect = RemoveDuplicateGuidesEffect().run()

View File

@ -27,21 +27,21 @@ class ApplyTransform(inkex.EffectExtension):
self.recursiveFuseTransform(self.document.getroot())
@staticmethod
def objectToPath(node):
if node.tag == inkex.addNS('g', 'svg'):
return node
def objectToPath(element):
if element.tag == inkex.addNS('g', 'svg'):
return element
if node.tag == inkex.addNS('path', 'svg') or node.tag == 'path':
for attName in node.attrib.keys():
if element.tag == inkex.addNS('path', 'svg') or element.tag == 'path':
for attName in element.attrib.keys():
if ("sodipodi" in attName) or ("inkscape" in attName):
del node.attrib[attName]
return node
del element.attrib[attName]
return element
return node
return element
def scaleStrokeWidth(self, node, transf):
if 'style' in node.attrib:
style = node.attrib.get('style')
def scaleStrokeWidth(self, element, transf):
if 'style' in element.attrib:
style = element.attrib.get('style')
style = dict(Style.parse_str(style))
update = False
@ -55,32 +55,32 @@ class ApplyTransform(inkex.EffectExtension):
pass
if update:
node.attrib['style'] = Style(style).to_str()
element.attrib['style'] = Style(style).to_str()
def recursiveFuseTransform(self, node, transf=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]):
def recursiveFuseTransform(self, element, transf=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]):
transf = Transform(transf) * Transform(node.get("transform", None)) #a, b, c, d = linear transformations / e, f = translations
transf = Transform(transf) * Transform(element.get("transform", None)) #a, b, c, d = linear transformations / e, f = translations
if 'transform' in node.attrib:
del node.attrib['transform']
if 'transform' in element.attrib:
del element.attrib['transform']
node = ApplyTransform.objectToPath(node)
element = ApplyTransform.objectToPath(element)
if transf == NULL_TRANSFORM:
# Don't do anything if there is effectively no transform applied
# reduces alerts for unsupported nodes
# reduces alerts for unsupported elements
pass
elif 'd' in node.attrib:
d = node.get('d')
elif 'd' in element.attrib:
d = element.get('d')
p = CubicSuperPath(d)
p = Path(p).to_absolute().transform(transf, True)
node.set('d', str(Path(CubicSuperPath(p).to_path())))
element.set('d', str(Path(CubicSuperPath(p).to_path())))
self.scaleStrokeWidth(node, transf)
self.scaleStrokeWidth(element, transf)
elif node.tag in [inkex.addNS('polygon', 'svg'),
elif element.tag in [inkex.addNS('polygon', 'svg'),
inkex.addNS('polyline', 'svg')]:
points = node.get('points')
points = element.get('points')
points = points.strip().split(' ')
for k, p in enumerate(points):
if ',' in p:
@ -91,24 +91,24 @@ class ApplyTransform(inkex.EffectExtension):
p = ','.join(p)
points[k] = p
points = ' '.join(points)
node.set('points', points)
element.set('points', points)
self.scaleStrokeWidth(node, transf)
self.scaleStrokeWidth(element, transf)
elif node.tag in [inkex.addNS("ellipse", "svg"), inkex.addNS("circle", "svg")]:
elif element.tag in [inkex.addNS("ellipse", "svg"), inkex.addNS("circle", "svg")]:
def isequal(a, b):
return abs(a - b) <= transf.absolute_tolerance
if node.TAG == "ellipse":
rx = float(node.get("rx"))
ry = float(node.get("ry"))
if element.TAG == "ellipse":
rx = float(element.get("rx"))
ry = float(element.get("ry"))
else:
rx = float(node.get("r"))
rx = float(element.get("r"))
ry = rx
cx = float(node.get("cx"))
cy = float(node.get("cy"))
cx = float(element.get("cx"))
cy = float(element.get("cy"))
sqxy1 = (cx - rx, cy - ry)
sqxy2 = (cx + rx, cy - ry)
sqxy3 = (cx + rx, cy + ry)
@ -116,8 +116,8 @@ class ApplyTransform(inkex.EffectExtension):
newxy2 = transf.apply_to_point(sqxy2)
newxy3 = transf.apply_to_point(sqxy3)
node.set("cx", (newxy1[0] + newxy3[0]) / 2)
node.set("cy", (newxy1[1] + newxy3[1]) / 2)
element.set("cx", (newxy1[0] + newxy3[0]) / 2)
element.set("cy", (newxy1[1] + newxy3[1]) / 2)
edgex = math.sqrt(
abs(newxy1[0] - newxy2[0]) ** 2 + abs(newxy1[1] - newxy2[1]) ** 2
)
@ -126,31 +126,32 @@ class ApplyTransform(inkex.EffectExtension):
)
if not isequal(edgex, edgey) and (
node.TAG == "circle"
element.TAG == "circle"
or not isequal(newxy2[0], newxy3[0])
or not isequal(newxy1[1], newxy2[1])
):
inkex.utils.errormsg(
"Warning: Shape %s (%s) is approximate only, try Object to path first for better results"
% (node.TAG, node.get("id"))
% (element.TAG, element.get("id"))
)
if node.TAG == "ellipse":
node.set("rx", edgex / 2)
node.set("ry", edgey / 2)
if element.TAG == "ellipse":
element.set("rx", edgex / 2)
element.set("ry", edgey / 2)
else:
node.set("r", edgex / 2)
element.set("r", edgex / 2)
elif node.tag == inkex.addNS("use", "svg"):
# this is unstable at the moment
elif element.tag == inkex.addNS("use", "svg"):
href = None
old_href_key = '{http://www.w3.org/1999/xlink}href'
new_href_key = 'href'
if node.attrib.has_key(old_href_key) is True: # {http://www.w3.org/1999/xlink}href (which gets displayed as 'xlink:href') attribute is deprecated. the newer attribute is just 'href'
href = node.attrib.get(old_href_key)
#node.attrib.pop(old_href_key)
if node.attrib.has_key(new_href_key) is True:
href = node.attrib.get(new_href_key) #we might overwrite the previous deprecated xlink:href but it's okay
#node.attrib.pop(new_href_key)
if element.attrib.has_key(old_href_key) is True: # {http://www.w3.org/1999/xlink}href (which gets displayed as 'xlink:href') attribute is deprecated. the newer attribute is just 'href'
href = element.attrib.get(old_href_key)
#element.attrib.pop(old_href_key)
if element.attrib.has_key(new_href_key) is True:
href = element.attrib.get(new_href_key) #we might overwrite the previous deprecated xlink:href but it's okay
#element.attrib.pop(new_href_key)
#get the linked object from href attribute
linkedObject = self.document.getroot().xpath("//*[@id = '%s']" % href.lstrip('#')) #we must remove hashtag symbol
@ -161,14 +162,14 @@ class ApplyTransform(inkex.EffectExtension):
mask = None #image might have an alpha channel
new_mask_id = self.svg.get_unique_id("mask")
newMask = None
if node.attrib.has_key('mask') is True:
mask = node.attrib.get('mask')
#node.attrib.pop('mask')
if element.attrib.has_key('mask') is True:
mask = element.attrib.get('mask')
#element.attrib.pop('mask')
#get the linked mask from mask attribute. We remove the old and create a new
if mask is not None:
linkedMask = self.document.getroot().xpath("//*[@id = '%s']" % mask.lstrip('url(#').rstrip(')')) #we must remove hashtag symbol
linkedMask[0].getparent().remove(linkedMask[0])
linkedMask[0].delete()
maskAttributes = {'id': new_mask_id}
newMask = etree.SubElement(self.document.getroot(), inkex.addNS('mask', 'svg'), maskAttributes)
@ -182,25 +183,25 @@ class ApplyTransform(inkex.EffectExtension):
linkedObjectCopy.set('mask', 'url(#' + new_mask_id + ')')
maskRectAttributes = {'x': '{:1.6f}'.format(transf.e), 'y': '{:1.6f}'.format(transf.f), 'width': '{:1.6f}'.format(width), 'height': '{:1.6f}'.format(height), 'style':'fill:#ffffff;'}
maskRect = etree.SubElement(newMask, inkex.addNS('rect', 'svg'), maskRectAttributes)
self.document.getroot().append(linkedObjectCopy) #for each svg:use we append a copy to the document root
element.delete() #then we remove the use object
else:
self.recursiveFuseTransform(linkedObjectCopy, transf)
#self.recursiveFuseTransform(linkedObjectCopy, transf)
self.recursiveFuseTransform(element.unlink(), transf)
self.document.getroot().append(linkedObjectCopy) #for each svg:use we append a copy to the document root
node.getparent().remove(node) #then we remove the use object
elif node.tag in [inkex.addNS('rect', 'svg'),
elif element.tag in [inkex.addNS('rect', 'svg'),
inkex.addNS('text', 'svg'),
inkex.addNS('image', 'svg')]:
inkex.utils.errormsg(
"Shape %s (%s) not yet supported, try Object to path first"
% (node.TAG, node.get("id"))
% (element.TAG, element.get("id"))
)
else:
# e.g. <g style="...">
self.scaleStrokeWidth(node, transf)
self.scaleStrokeWidth(element, transf)
for child in node.getchildren():
for child in element.getchildren():
self.recursiveFuseTransform(child, transf)
if __name__ == '__main__':

View File

@ -260,7 +260,7 @@ class ChainPaths(inkex.EffectExtension):
if not len(new):
# node.clear()
if node.getparent() is not None:
node.getparent().remove(node)
node.delete()
obsoleted += 1
if debug: inkex.utils.debug("Path node obsoleted: " +str(id))
else:

View File

@ -111,7 +111,7 @@ class ContourScanner(inkex.EffectExtension):
parent.insert(idx, replacedNode)
idSuffix += 1
self.replacedNodes.append(replacedNode)
parent.remove(node)
node.delete()
for child in node:
self.breakContours(child)
@ -158,7 +158,7 @@ class ContourScanner(inkex.EffectExtension):
node.attrib['style'] = Style(style).to_str()
if self.options.remove_opened:
try:
node.getparent().remove(node)
node.delete()
except AttributeError:
pass #we ignore that parent can be None
if closed == True:
@ -169,7 +169,7 @@ class ContourScanner(inkex.EffectExtension):
node.attrib['style'] = Style(style).to_str()
if self.options.remove_closed:
try:
node.getparent().remove(node)
node.delete()
except AttributeError:
pass #we ignore that parent can be None
@ -220,7 +220,7 @@ class ContourScanner(inkex.EffectExtension):
node.attrib['style'] = intersectionStyle
if self.options.remove_selfintersecting:
if node.getparent() is not None: #might be already been deleted by previously checked settings so check again
node.getparent().remove(node)
node.delete()
#draw intersections segment lines - useless at the moment. We could use this information to cut the original polyline to get a new curve path which included the intersection points
#isectSegs = poly_point_isect.isect_polygon_include_segments(points)
@ -254,7 +254,7 @@ class ContourScanner(inkex.EffectExtension):
if len(intersectionGroup.getchildren()) == 0:
intersectionGroupParent = intersectionGroup.getparent()
if intersectionGroupParent is not None:
intersectionGroup.getparent().remove(intersectionGroup)
intersectionGroup.delete()
#put the node into the intersectionGroup to bundle the path with it's error markers. If removal is selected we need to avoid intersectionGroup.insert(), because it will break the removal
elif self.options.remove_selfintersecting == False:
intersectionGroup.insert(0, node)

View File

@ -287,7 +287,7 @@ class FilletChamfer(inkex.EffectExtension):
self.addEle(inkex.addNS('path','svg'), node.getparent(), attrib)
if self.options.remove:
node.getparent().remove(node)
node.delete()
if __name__ == '__main__':
FilletChamfer().run()

View File

@ -164,7 +164,7 @@ class Imagetracerjs (inkex.EffectExtension):
#remove the old image or not
if self.options.keeporiginal is not True:
node.getparent().remove(node)
node.delete()
else:
inkex.utils.debug("No image found for tracing. Please select an image first.")

View File

@ -24,297 +24,297 @@ from lxml import etree
from inkex.paths import Path
def saw(x):
#The function returns a symmetric triangle wave with period 4 and varying between -1 and 1
x = math.fmod(x, 4.0)
x = math.fabs(x)
if x > 2.0:
y = 3 - x
else:
y = x - 1
return y
#The function returns a symmetric triangle wave with period 4 and varying between -1 and 1
x = math.fmod(x, 4.0)
x = math.fabs(x)
if x > 2.0:
y = 3 - x
else:
y = x - 1
return y
def square(x):
#The function returns a square wave with period 4 and varying between -1 and 1
x = math.fmod(x, 4.0)
if 1.0 < x < 3.0:
y = 1.0
else:
y = -1.0
return y
#The function returns a square wave with period 4 and varying between -1 and 1
x = math.fmod(x, 4.0)
if 1.0 < x < 3.0:
y = 1.0
else:
y = -1.0
return y
class LineShading(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
self.arg_parser.add_argument('--palette', help='Choose the colors...')
self.arg_parser.add_argument("--waveform", help="Select the shape of the curve")
self.arg_parser.add_argument("--num_lines", type=int, help="Number of lines")
self.arg_parser.add_argument("--min_period", type=float, help="Minimum period (corresponds to black pixels)")
self.arg_parser.add_argument("--max_period", type=float, help="Maximum period (corresponds to white pixels)")
self.arg_parser.add_argument("--min_amplitude", type=float, help="Minimum amplitude (corresponds to white pixels)")
self.arg_parser.add_argument("--max_amplitude", type=float, help="Maximum amplitude (corresponds to black pixels)")
self.arg_parser.add_argument("--gamma", type=float, help="Maximum amplitude (corresponds to black pixels)")
self.arg_parser.add_argument("--line_width", type=float, help="Line width")
self.arg_parser.add_argument("--units", help="Units for line thickness")
self.arg_parser.add_argument("--remove", type=inkex.Boolean, help="If True, source image is removed")
self.arg_parser.add_argument("--active-tab", help="The selected UI-tab when OK was pressed")
def __init__(self):
inkex.Effect.__init__(self)
self.arg_parser.add_argument('--palette', help='Choose the colors...')
self.arg_parser.add_argument("--waveform", help="Select the shape of the curve")
self.arg_parser.add_argument("--num_lines", type=int, help="Number of lines")
self.arg_parser.add_argument("--min_period", type=float, help="Minimum period (corresponds to black pixels)")
self.arg_parser.add_argument("--max_period", type=float, help="Maximum period (corresponds to white pixels)")
self.arg_parser.add_argument("--min_amplitude", type=float, help="Minimum amplitude (corresponds to white pixels)")
self.arg_parser.add_argument("--max_amplitude", type=float, help="Maximum amplitude (corresponds to black pixels)")
self.arg_parser.add_argument("--gamma", type=float, help="Maximum amplitude (corresponds to black pixels)")
self.arg_parser.add_argument("--line_width", type=float, help="Line width")
self.arg_parser.add_argument("--units", help="Units for line thickness")
self.arg_parser.add_argument("--remove", type=inkex.Boolean, help="If True, source image is removed")
self.arg_parser.add_argument("--active-tab", help="The selected UI-tab when OK was pressed")
def drawfunction(self, image_w, image_h, file):
reader = png.Reader(file)
w, h, pixels, metadata = reader.read_flat()
matrice = [[1.0 for i in range(w)]for j in range(h)]
if metadata['alpha']:
n = 4
else:
n = 3
#RGB convert to grayscale 0.21R + 0.72G + 0.07B
for y in range(h):
for x in range(w):
pixel_pos = (x + y * w)*n
p = 1.0 - (pixels[pixel_pos]*0.21 + pixels[(pixel_pos+1)]*0.72 + pixels[(pixel_pos+2)]*0.07)/255.0
matrice[y][x] = math.pow(p, 1.0/self.options.gamma)
points = []
step_y = image_h/h
step_x = image_w/(w-1)
min_amplitude = self.options.min_amplitude*step_y/2
max_amplitude = self.options.max_amplitude*step_y/2
min_period = self.options.min_period*step_y
max_period = self.options.max_period*step_y
min_frequency = 1.0/max_period
max_frequency = 1.0/min_period
#Sinusoidal wave (optimized)
if self.options.waveform == 'sin':
for y in range(h):
pi = math.pi
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0
x0 = 0.0
y0 = math.sin(phase)*(min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x]) + (y+0.5)*step_y
points.append(['M',[x0, y0]])
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 2.0*pi/period*step_x
#calculate y
if phase > 2.0*pi:
if n_step > 0:
x3 = coord_x
y3 = -amplitude/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.32
y2 = y3
x1 = x0 + (x3-x0)*0.34
y1 = y0
x0 = x3
y0 = y3
points.append(['C',[x1, y1, x2, y2, x3, y3]])
n_step = 0
amplitude = 0
elif phase < pi < (phase + d_phase):
if n_step > 0:
x3 = coord_x
y3 = amplitude/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.34
y2 = y3
x1 = x0 + (x3-x0)*0.32
y1 = y0
x0 = x3
y0 = y3
points.append(['C',[x1, y1, x2, y2, x3, y3]])
n_step = 0
amplitude = 0
phase = math.fmod(phase, 2.0*pi)
#calculate x
if phase < 0.5*pi < (phase + d_phase):
coord_x = (x - (phase - 0.5*pi)/d_phase)*step_x
elif phase < 1.5*pi < (phase + d_phase):
coord_x = (x - (phase - 1.5*pi)/d_phase)*step_x
phase += d_phase
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
n_step += 1
#add last point
if n_step > 0:
phase = math.fmod(phase, 2.0*pi)
if (0 < phase < 0.5*pi) or (pi < phase < 1.5*pi):
x3 = (w-1)*step_x
y3 = amplitude*math.sin(phase)/n_step + (y+0.5)*step_y
x2 = x3
y2 = y3
x1 = x0 + (x3-x0)*0.33
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
else:
if coord_x > (w-1)*step_x:
coord_x = (w-1)*step_x
x3 = coord_x
y3 = math.copysign( amplitude , math.sin(phase))/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.32
y2 = y3
x1 = x0 + (x3-x0)*0.34
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
if coord_x < (w-1)*step_x:
x0 = x3
y0 = y3
x3 = (w-1)*step_x
y3 = amplitude*math.sin(phase)/n_step + (y+0.5)*step_y
x2 = x3
y2 = y3
x1 = x0 + (x3-x0)*0.33
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
def drawfunction(self, image_w, image_h, file):
reader = png.Reader(file)
w, h, pixels, metadata = reader.read_flat()
matrice = [[1.0 for i in range(w)]for j in range(h)]
if metadata['alpha']:
n = 4
else:
n = 3
#RGB convert to grayscale 0.21R + 0.72G + 0.07B
for y in range(h):
for x in range(w):
pixel_pos = (x + y * w)*n
p = 1.0 - (pixels[pixel_pos]*0.21 + pixels[(pixel_pos+1)]*0.72 + pixels[(pixel_pos+2)]*0.07)/255.0
matrice[y][x] = math.pow(p, 1.0/self.options.gamma)
#Sinusoidal wave (Brute-force)
elif self.options.waveform == 'sin_b':
pi2 = math.pi*2.0
for y in range(h):
phase = - pi2/4.0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
amplitude = min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x]
phase += pi2*step_x/period
phase = math.fmod(phase, pi2)
if x == 0:
points.append(['M',[x*step_x, amplitude*math.sin(phase) + (y+0.5)*step_y]])
else:
points.append(['L',[x*step_x, amplitude*math.sin(phase) + (y+0.5)*step_y]])
#Saw wave
elif self.options.waveform == 'saw':
for y in range(h):
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0.0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 4.0/period*step_x
if phase > 4.0:
coord_x = (x - (phase - 4.0)/d_phase)*step_x
elif phase < 2.0 < (phase + d_phase):
coord_x = (x - (phase - 2.0)/d_phase)*step_x
phase = math.fmod(phase, 4.0)
if (phase < 1.0 < (phase + d_phase)) or (phase < 3.0 < (phase + d_phase)):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, amplitude*square(phase - 1.0)/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, amplitude*square(phase - 1.0)/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
phase += d_phase
n_step += 1.0
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
if n_step > 0:
points.append(['L',[(w-1)*step_x, amplitude*saw(phase - 1.0)/n_step + (y+0.5)*step_y]])
points = []
step_y = image_h/h
step_x = image_w/(w-1)
min_amplitude = self.options.min_amplitude*step_y/2
max_amplitude = self.options.max_amplitude*step_y/2
min_period = self.options.min_period*step_y
max_period = self.options.max_period*step_y
min_frequency = 1.0/max_period
max_frequency = 1.0/min_period
#Sinusoidal wave (optimized)
if self.options.waveform == 'sin':
for y in range(h):
pi = math.pi
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0
x0 = 0.0
y0 = math.sin(phase)*(min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x]) + (y+0.5)*step_y
points.append(['M',[x0, y0]])
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 2.0*pi/period*step_x
#calculate y
if phase > 2.0*pi:
if n_step > 0:
x3 = coord_x
y3 = -amplitude/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.32
y2 = y3
x1 = x0 + (x3-x0)*0.34
y1 = y0
x0 = x3
y0 = y3
points.append(['C',[x1, y1, x2, y2, x3, y3]])
n_step = 0
amplitude = 0
elif phase < pi < (phase + d_phase):
if n_step > 0:
x3 = coord_x
y3 = amplitude/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.34
y2 = y3
x1 = x0 + (x3-x0)*0.32
y1 = y0
x0 = x3
y0 = y3
points.append(['C',[x1, y1, x2, y2, x3, y3]])
n_step = 0
amplitude = 0
phase = math.fmod(phase, 2.0*pi)
#calculate x
if phase < 0.5*pi < (phase + d_phase):
coord_x = (x - (phase - 0.5*pi)/d_phase)*step_x
elif phase < 1.5*pi < (phase + d_phase):
coord_x = (x - (phase - 1.5*pi)/d_phase)*step_x
phase += d_phase
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
n_step += 1
#add last point
if n_step > 0:
phase = math.fmod(phase, 2.0*pi)
if (0 < phase < 0.5*pi) or (pi < phase < 1.5*pi):
x3 = (w-1)*step_x
y3 = amplitude*math.sin(phase)/n_step + (y+0.5)*step_y
x2 = x3
y2 = y3
x1 = x0 + (x3-x0)*0.33
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
else:
if coord_x > (w-1)*step_x:
coord_x = (w-1)*step_x
x3 = coord_x
y3 = math.copysign( amplitude , math.sin(phase))/n_step + (y+0.5)*step_y
x2 = x3 - (x3-x0)*0.32
y2 = y3
x1 = x0 + (x3-x0)*0.34
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
if coord_x < (w-1)*step_x:
x0 = x3
y0 = y3
x3 = (w-1)*step_x
y3 = amplitude*math.sin(phase)/n_step + (y+0.5)*step_y
x2 = x3
y2 = y3
x1 = x0 + (x3-x0)*0.33
y1 = y0
points.append(['C',[x1, y1, x2, y2, x3, y3]])
#Sinusoidal wave (Brute-force)
elif self.options.waveform == 'sin_b':
pi2 = math.pi*2.0
for y in range(h):
phase = - pi2/4.0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
amplitude = min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x]
phase += pi2*step_x/period
phase = math.fmod(phase, pi2)
if x == 0:
points.append(['M',[x*step_x, amplitude*math.sin(phase) + (y+0.5)*step_y]])
else:
points.append(['L',[x*step_x, amplitude*math.sin(phase) + (y+0.5)*step_y]])
#Saw wave
elif self.options.waveform == 'saw':
for y in range(h):
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0.0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 4.0/period*step_x
if phase > 4.0:
coord_x = (x - (phase - 4.0)/d_phase)*step_x
elif phase < 2.0 < (phase + d_phase):
coord_x = (x - (phase - 2.0)/d_phase)*step_x
phase = math.fmod(phase, 4.0)
if (phase < 1.0 < (phase + d_phase)) or (phase < 3.0 < (phase + d_phase)):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, amplitude*square(phase - 1.0)/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, amplitude*square(phase - 1.0)/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
phase += d_phase
n_step += 1.0
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
if n_step > 0:
points.append(['L',[(w-1)*step_x, amplitude*saw(phase - 1.0)/n_step + (y+0.5)*step_y]])
#Square wave
else:
for y in range(h):
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 4.0/period*step_x
if phase > 4.0:
coord_x = (x - (phase - 4.0)/d_phase)*step_x
elif phase < 2.0 < (phase + d_phase):
coord_x = (x - (phase - 2.0)/d_phase)*step_x
phase = math.fmod(phase, 4.0)
if phase < 1.0 < (phase + d_phase):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
points.append(['L',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
elif phase < 3.0 < (phase + d_phase):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
points.append(['L',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
phase += d_phase
n_step += 1
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
if n_step > 0:
if 3.0 > phase > 1.0:
points.append(['L',[(w-1)*step_x, amplitude/n_step + (y+0.5)*step_y]])
#Square wave
else:
points.append(['L',[(w-1)*step_x, -amplitude/n_step + (y+0.5)*step_y]])
return points
def draw_path(self, node, file):
newpath = etree.Element(inkex.addNS('path','svg'))
line_width = self.options.line_width
units = self.options.units
s = {'stroke': '#000000', 'fill': 'none', 'stroke-linejoin': 'round', 'stroke-linecap': 'round', 'stroke-width': str(self.svg.unittouu(str(line_width) + units))}
newpath.set('style', str(inkex.Style(s)))
x = node.get('x')
y = node.get('y')
t = 'translate('+ x +','+ y +')'
newpath.set('transform', t)
image_w = float(node.get('width'))
image_h = float(node.get('height'))
newpath.set('d', str(Path(self.drawfunction(image_w, image_h, file))))
newpath.set('title', 'Line_Shading')
node.getparent().append(newpath)
newpath.set('x', x)
def export_png(self, node, file):
image_w = float(node.get('width'))
image_h = float(node.get('height'))
min_period = self.options.min_period
max_period = self.options.min_period
poinnt_per_min_period = 8.0
current_file = self.options.input_file
h_png = str(self.options.num_lines)
if min_period < max_period:
w_png = str(round(poinnt_per_min_period*image_w*float(h_png)/min_period/image_h))
else:
w_png = str(round(poinnt_per_min_period*image_w*float(h_png)/max_period/image_h))
id = node.get('id')
cmd = "inkscape " + current_file + " --export-type=\"png\" --export-filename=" + file + " --actions=\"export-width:"+w_png+";export-height:"+h_png+";export-background:rgb(255,255,255);export-background-opacity:255;export-id:"+id+"\""
#inkex.errormsg(cmd)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#inkex.utils.debug(cmd)
#inkex.utils.debug(proc.communicate())
#sys.exit(0)
#return_code = proc.wait()
#sys.exit(0)
f = proc.stdout
err = proc.stderr
f.close()
err.close()
proc.wait()
#inkex.errormsg(proc.stdout.read())
for y in range(h):
phase = 0.0
coord_x = 0.0
amplitude = 0.0
n_step = 0
for x in range(w):
period = min_period + (max_period - min_period)*(1-matrice[y][x])
#period = 1.0/(min_frequency + (max_frequency - min_frequency)*(matrice[y][x]))
d_phase = 4.0/period*step_x
if phase > 4.0:
coord_x = (x - (phase - 4.0)/d_phase)*step_x
elif phase < 2.0 < (phase + d_phase):
coord_x = (x - (phase - 2.0)/d_phase)*step_x
phase = math.fmod(phase, 4.0)
if phase < 1.0 < (phase + d_phase):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
points.append(['L',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
elif phase < 3.0 < (phase + d_phase):
if n_step > 0:
if coord_x == 0.0:
points.append(['M',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[coord_x, amplitude/n_step + (y+0.5)*step_y]])
points.append(['L',[coord_x, -amplitude/n_step + (y+0.5)*step_y]])
n_step = 0
amplitude = 0
phase += d_phase
n_step += 1
amplitude += (min_amplitude + (max_amplitude - min_amplitude)*matrice[y][x])
if n_step > 0:
if 3.0 > phase > 1.0:
points.append(['L',[(w-1)*step_x, amplitude/n_step + (y+0.5)*step_y]])
else:
points.append(['L',[(w-1)*step_x, -amplitude/n_step + (y+0.5)*step_y]])
return points
def draw_path(self, node, file):
newpath = etree.Element(inkex.addNS('path','svg'))
line_width = self.options.line_width
units = self.options.units
s = {'stroke': '#000000', 'fill': 'none', 'stroke-linejoin': 'round', 'stroke-linecap': 'round', 'stroke-width': str(self.svg.unittouu(str(line_width) + units))}
newpath.set('style', str(inkex.Style(s)))
x = node.get('x')
y = node.get('y')
t = 'translate('+ x +','+ y +')'
newpath.set('transform', t)
image_w = float(node.get('width'))
image_h = float(node.get('height'))
newpath.set('d', str(Path(self.drawfunction(image_w, image_h, file))))
newpath.set('title', 'Line_Shading')
node.getparent().append(newpath)
newpath.set('x', x)
def export_png(self, node, file):
image_w = float(node.get('width'))
image_h = float(node.get('height'))
min_period = self.options.min_period
max_period = self.options.min_period
poinnt_per_min_period = 8.0
current_file = self.options.input_file
h_png = str(self.options.num_lines)
if min_period < max_period:
w_png = str(round(poinnt_per_min_period*image_w*float(h_png)/min_period/image_h))
else:
w_png = str(round(poinnt_per_min_period*image_w*float(h_png)/max_period/image_h))
id = node.get('id')
cmd = "inkscape " + current_file + " --export-type=\"png\" --export-filename=" + file + " --actions=\"export-width:"+w_png+";export-height:"+h_png+";export-background:rgb(255,255,255);export-background-opacity:255;export-id:"+id+"\""
#inkex.errormsg(cmd)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#inkex.utils.debug(cmd)
#inkex.utils.debug(proc.communicate())
#sys.exit(0)
#return_code = proc.wait()
#sys.exit(0)
f = proc.stdout
err = proc.stderr
f.close()
err.close()
proc.wait()
#inkex.errormsg(proc.stdout.read())
def effect(self):
image_selected_flag = False
for id, node in self.svg.selected.items():
if node.tag == inkex.addNS('image','svg'):
image_selected_flag = True
tmp_dir = tempfile.mkdtemp()
png_temp_file = os.path.join(tmp_dir, "LineShading.png")
self.export_png(node, png_temp_file)
self.draw_path(node, png_temp_file)
shutil.rmtree(tmp_dir)
if self.options.remove:
node.getparent().remove(node)
return
if not image_selected_flag:
inkex.errormsg("Please select an image")
def effect(self):
image_selected_flag = False
for id, node in self.svg.selected.items():
if node.tag == inkex.addNS('image','svg'):
image_selected_flag = True
tmp_dir = tempfile.mkdtemp()
png_temp_file = os.path.join(tmp_dir, "LineShading.png")
self.export_png(node, png_temp_file)
self.draw_path(node, png_temp_file)
shutil.rmtree(tmp_dir)
if self.options.remove:
node.delete()
return
if not image_selected_flag:
inkex.errormsg("Please select an image")
if __name__ == '__main__':
LineShading().run()
LineShading().run()

View File

@ -287,7 +287,7 @@ class PathOps(inkex.EffectExtension):
if not self.options.keep_top:
top_node = self.svg.getElementById(top_path)
if top_node is not None:
top_node.getparent().remove(top_node)
top_node.delete()
# purge missing tagrefs (see below)
self.update_tagrefs()
# clean up
@ -353,7 +353,7 @@ class PathOps(inkex.EffectExtension):
href = tagref.get(inkex.addNS('href', 'xlink'))[1:]
if self.svg.getElementById(href) is None:
if mode == 'purge':
tagref.getparent().remove(tagref)
tagref.delete()
elif mode == 'placeholder':
temp = etree.Element(inkex.addNS('path', 'svg'))
temp.set('id', href)

View File

@ -151,7 +151,7 @@ class Primitive (inkex.EffectExtension):
exit(1)
#remove the old image or not
if self.options.keeporiginal is not True:
node.getparent().remove(node)
node.delete()
# create clip path to remove the stuffy surroundings
if self.options.cliprect:

View File

@ -260,7 +260,7 @@ class Shapes(inkex.Effect):
if midtype=="pillowrombus":
self.pillows(midtype, a, node, l, t, r, b, cX, cY)
pnts = []
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
if (sub_bb=='chamfer'):
if chtype=="chamfer":
@ -300,7 +300,7 @@ class Shapes(inkex.Effect):
self.pillows(chtype, a, node, l, t, r, b, cX, cY)
pnts = []
dS = "M %sZ"
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
if chtype == "spiralrect":
An, Al = (an, al)
pnts = [[l,t], [An,0], [0,Al], [-An,0], [0,-Al+a]]
@ -380,7 +380,7 @@ class Shapes(inkex.Effect):
nn = svgCircle(node.getparent(), rad, px, py)
self.estilo(nn,node)
pnts=[]
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
if sh=='nodes':
# get verts
obj, posh, posv, objS, oY =(sO.obj, int(sO.posh), int(sO.posv), sO.objsize, sO.ordery)
@ -450,7 +450,7 @@ class Shapes(inkex.Effect):
orderY.sort(key=myFunc)
for item in orderY:
grp.append( item[1])
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
# ##############################3
d = ""
@ -460,7 +460,7 @@ class Shapes(inkex.Effect):
d += "%s%s,%s " % (ss, str(n[0]),str(n[1]))
nn = self.addEle('path',pp, {'d':dS % (d)})
self.estilo(nn,node)
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
def makeRel(self,arr):
b = arr[:]
@ -608,7 +608,7 @@ class Shapes(inkex.Effect):
# curva1
nn = self.addEle('path',pp,{'d':"M %sZ" % (sCurva1),'style':'stroke-width:0.02;fill:#cc0000;stroke:#000000;'})
self.estilo(nn,node)
if deleteorigin: node.getparent().remove(node)
if deleteorigin: node.delete()
def drawArrow(self, sO, an, al, l, t):
arrowType = sO.arrowtype

View File

@ -384,7 +384,7 @@ class vpypetools (inkex.EffectExtension):
trajectoriesLayer[0].attrib.pop('fill') # remove unneccesary fill attribute
else:
if len(trajectoriesLayer) > 0:
trajectoriesLayer[0].getparent().remove(trajectoriesLayer[0])
trajectoriesLayer[0].delete()
lineLayers = import_doc.getroot().xpath("//svg:g[not(@id='pen_up_trajectories')]", namespaces=inkex.NSS) #all layer except the pen_up trajectories layer
if self.options.use_style_of_first_element is True and self.options.input_handling == "paths" and firstElementStyle is not None:
@ -420,7 +420,7 @@ class vpypetools (inkex.EffectExtension):
# Remove selection objects to do a real replace with new objects from vpype document
if self.options.keep_objects is False:
for node in nodesToWork:
node.getparent().remove(node)
node.delete()
if __name__ == '__main__':
vpypetools().run()