-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvgExport.pspscript
769 lines (693 loc) · 32.5 KB
/
svgExport.pspscript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
from JascApp import *
import Tkinter
import tkFileDialog
import xml.etree.cElementTree as xml
import os
import struct
import uuid
import math
genSilent = {'ExecutionMode': App.Constants.ExecutionMode.Silent,
'AutoActionMode': App.Constants.AutoActionMode.Match,
'Version': ((9,0,0),1),
}
defs = None
env = None
def ScriptProperties():
return {
'Author': u'LeviFiction',
'Copyright': u'2021',
'Description': u'Exports entire image to SVG format',
'Host': u'PaintShop Pro',
'Host Version': u'9.00'
}
def Do(Environment):
global env
env = Environment
Tkinter.Tk().withdraw()
filename = verify_filename(tkFileDialog.asksaveasfilename(initialdir = user_path('Pictures'),title = "Export SVG",filetypes = (("SVG","*.svg"),)))
svg_data = makeSVG(Environment)
SaveSVG(filename, svg_data)
# This function is used to see if materials already exist as resource
def elements_equal(e1, e2):
"""Determine if two elements are the same"""
if e1.tag != e2.tag: return False
if e1.text != e2.text: return False
if e1.tail != e2.tail: return False
if e1.attrib != e2.attrib: return False
if len(e1) != len(e2): return False
return all(elements_equal(c1, c2) for c1, c2 in zip(e1, e2))
def makeSVG(Environment, includeRaster=False, Embed=True):
"""Start process of converting full document to SVG"""
current_layer_path = None
global defs
defs = xml.Element('defs')
rootTree = xml.Element('svg', {'version':"1.1",
'width':str(App.TargetDocument.Width),
'height':str(App.TargetDocument.Height),
'xmlns': "http://www.w3.org/2000/svg"})
selectBottomLayer(Environment)
newLayer = True
while newLayer:
result = returnLayerProperties(Environment)
if result['Path'] == current_layer_path:
break
else:
current_layer_path = result['Path']
if result['LayerType'] in [0,4,5,6,7,8,9,10,11,12,13,14,15] and includeRaster:
print("Not a good layer")
elif result['LayerType'] == 1:
print(result.keys())
group = createGroup(validName(result['General']['Name']), opacity=str(result['General']['Opacity'])+'%')
objs = True
while objs:
color = "RGB(0,0,0"
objs = nextObject(Environment)
if objs:
obj = objs['ListOfObjects'][0]
if obj['ObjectType'] == 'Group':
#createVectorGroup(group, objs)
print("Create Vector Group")
create_vector_group(Environment, group, objs)
elif obj['ObjectType'] == 'Rectangle':
data = obj['RectangleData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addRect(group, data['ObjectName'],
data['Top'],
data['Left'],
data['Width'],
data['Height'],
data['RadiusX'],
data['RadiusY'],
data['Matrix'], fill_color, stroke_data)
elif obj['ObjectType'] == 'Ellipse':
data = obj['EllipseData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addEllipse(group, data['ObjectName'],
data['CenterX'],
data['CenterY'],
data['RadiusX'],
data['RadiusY'],
data['Matrix'], fill_color, stroke_data)
elif obj['ObjectType'] == 'SymmetricShape':
convert_to_path(Environment, obj['Path'])
current_object = returnVectorProperties(Environment)['ListOfObjects'][0]
data = current_object['ObjectData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addPath(group, data['ObjectName'], data['Path'], fill_color, stroke_data)
elif obj['ObjectType'] in ['Text', 'TextEx']:
convert_to_path(Environment, obj['Path'])
current_object = returnVectorProperties(Environment)['ListOfObjects'][0]
data = current_object['ObjectData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addPath(group, data['ObjectName'], data['Path'], fill_color, stroke_data)
elif obj['ObjectType'] == 'Path':
data = obj['ObjectData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'width':data['LineWidth'],
'stroke_color':data['Stroke']}
fill_color = data['Fill']
addPath(group, data['ObjectName'], data['Path'], fill_color, stroke_data)
rootTree.insert(len(rootTree), group)
newLayer = selectNextLayer(Environment)
if len(defs.getchildren()) >= 1: #if we have defs
rootTree.insert(0, defs)
return rootTree
def createGroup(id, opacity="100%"):
"""Create SVG Group usually represents a layer"""
return xml.Element('g', {'id': id, 'opacity':opacity})
def create_vector_group(Env, group, groupData):
"""PSP returns all elements in a vector group, and sub groups, parse list and return group"""
# First go through all objects in group to convert unsupported objects
# reset is used to determine if we need to reselect the vector group
reset = False
current_path = groupData['ListOfObjects'][0]['Path']
for current_object in groupData['ListOfObjects']:
if current_object['ObjectType'] in ['SymmetricShape', 'Text', 'TextEx']:
reset = True
convert_to_path(Env, current_object['Path'])
if reset:
select_vector_absolute(Env, current_path)
groupData = returnVectorProperties(Env)
# List of groups to sort through
groups = []
# Loop over all objects in list
for current_object in groupData['ListOfObjects']:
# If object is a group, the next objects will be the children up to the count in Child Count
if current_object['ObjectType'] == 'Group':
# Add group to groups list
groups.append(xml.Element('g', {'id':validName(current_object['GroupName']), 'count':current_object['Child Count']}))
elif current_object['ObjectType'] == 'Rectangle':
# Add rectangle to current group
data = current_object['RectangleData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addRect(groups[-1], validName(data['ObjectName']),
data['Top'],
data['Left'],
data['Width'],
data['Height'],
data['RadiusX'],
data['RadiusY'],
data['Matrix'], fill_color, stroke_data)
elif current_object['ObjectType'] == 'Ellipse':
# Add ellipse to current group
data = current_object['EllipseData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addEllipse(groups[-1], validName(data['ObjectName']),
data['CenterX'],
data['CenterY'],
data['RadiusX'],
data['RadiusY'],
data['Matrix'], fill_color, stroke_data)
elif current_object['ObjectType'] in ['Text', 'TextEx', 'SymmetricShape']:
convert_to_path(env, current_object['Path'])
current_object = returnVectorProperties(env)['ListOfObjects'][0]
data = current_object['ObjectData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addPath(groups[-1], data['ObjectName'], data['Path'], fill_color, stroke_data)
elif current_object['Path']:
# Add path to current group
data = current_object['ObjectData']
if not data['Visibility']:
continue
stroke_data = {'linestyle':data['LineStyle'],
'joinstyle':data['Join'],
'miter':data['MiterLimit'],
'stroke_color':data['Stroke'],
'width':data['LineWidth']}
fill_color = data['Fill']
addPath(groups[-1], data['ObjectName'], data['Path'], fill_color, stroke_data)
if groups[-1].attrib['count'] == len(groups[-1].getchildren()):
# If we've added all children that exist in group
# And there is more than one group
# Add last group as child to previous group
if len(groups) > 1:
g = groups.pop() # remove last group
g.attrib.pop('count') # remove count attribute from group
groups[-1].insert(len(groups[-1].getchildren()), g) # Add group to previous group
groups[-1].attrib.pop('count') # remove count attribute from top level group
group.insert(len(group.getchildren()), groups[-1]) # Add final group to layer group
# TODO: Add text support
def addType(data):
"""I think this is supposed to be text"""
pass
def validName(Name):
"""Format current name to match SVG specs"""
return Name.replace(" ", "_")
def SaveSVG(filename, rootTree):
"""Save SVG data to filename"""
top = "<?xml version='1.0' standalone='no'?>"
doctype = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
with open(filename, 'w') as f:
f.write(top)
f.write(doctype)
f.write(xml.tostring(rootTree))
def addEllipse(root, id, x,y,rx,ry,matrix=None, fill_color={'Color':(0,0,0)}, stroke_data = {'linestyle':None, 'joinstyle':'0', 'miter':'14', 'width':'1', 'stroke_color':{'Color':(0,0,0)}}):
"""Convert Ellipse data to SVG and add to root"""
material = parse_stroke(stroke_data, stroke_data['stroke_color'])
material.update(parse_fill(fill_color))
attribs = {'id': id, 'cx': str(x), 'cy': str(y), 'rx':str(rx), 'ry':str(ry),}
if matrix:
attribs.update({'transform':pspMatrixToSVG(matrix)})
attribs.update(material)
xml.SubElement(root, 'ellipse', attribs)
def addRect(root, id, top, left, width, height, rx, ry, matrix = None, fill_color={'Color':(0,0,0)}, stroke_data = {'linestyle':None, 'joinstyle':'0', 'miter':'14', 'width':'1', 'stroke_color':{'Color':(0,0,0)}}):
"""Convert Rectangle data to SVG and add to root"""
material = parse_stroke(stroke_data, stroke_data['stroke_color'])
material.update(parse_fill(fill_color))
attribs = {'id': id, 'x': str(left), 'y': str(top), 'width':str(width), 'height':str(height), 'rx':str(rx), 'ry':str(ry)}
if matrix:
attribs.update({'transform':pspMatrixToSVG(matrix)})
attribs.update(material)
xml.SubElement(root, 'rect', attribs)
def addPath(root, id, path, fill_color={'Color':(0,0,0)}, stroke_data = {'linestyle':None, 'joinstyle':'0', 'miter':'14', 'width':'1', 'stroke_color':{'Color':(0,0,0)}}):
"""Convert Path data to SVG and add to root"""
cmd = ['M', 'L', 'C', 'Z']
pathstr = ""
for node in path:
pathstr += cmd[node[0]] + " "
for i,d in enumerate(node):
if i == 0:
continue
pathstr += ",".join(list(map(str, d))) + " "
material = parse_stroke(stroke_data, stroke_data['stroke_color'])
material.update(parse_fill(fill_color))
attribs = {'id':id, 'd':pathstr}
attribs.update(material)
xml.SubElement(root, 'path', attribs)
def verify_filename(filename):
path,ext = os.path.splitext(filename)
if ext.lower() != ".svg":
return filename + ".svg"
return filename
def user_path(*paths):
return os.path.join(os.environ['USERPROFILE'], *paths)
def parse_stroke(stroke_data, stroke_color):
"""Returns dictionary of stroke settings to add to xml attributes"""
# dash array doesn't match PSP output, but it's the best I can do
joins = ['Miter', 'Round', "Bevel"]
stroke_attribs = {'stroke-linejoin':joins[stroke_data['joinstyle']], 'stroke-miterlimit':str(stroke_data['miter']), 'stroke-width':str(stroke_data['width'])}
line = stroke_data['linestyle']
cap = line['FirstCap'][0]
if cap.lower() not in ['butt', 'square', 'round']:
cap = 'butt'
stroke_attribs.update({'stroke-linecap':cap})
if line['Segments'] != None:
stroke_attribs.update({'stroke-dasharray': ",".join(line['Segments'])})
stroke_attribs.update({'stroke':parse_material(stroke_color)})
return stroke_attribs
def parse_fill(fill_data):
"""Returns dictionary of stroke settings to add to xml attributes"""
return {'fill': parse_material(fill_data)}
def parse_material(material):
"""Returns formatted value for fill/stroke color attributes"""
if material['Color']:
return "RGB" + str(material['Color'])
if material['Gradient']:
print(material['Gradient'])
material = material['Gradient']
if material['ColorStops'] != None:
colorStops = material['ColorStops']
#kind of stupid, PSP uses "Midpoint" for color stops and "MidPoint" for opacity stops
#So that I wouldn't have to rewrite my code I just changed "Midpoint" to "MidPoint"
for stop in colorStops:
stop['MidPoint'] = stop.pop('Midpoint')
opacityStops = material['TransparencyStops']
elif material['Name'] != None:
name = findGradient(env, material['Name'])
reader = Gradient_Reader(name)
colorStops = reader.getColorStops()
opacityStops = reader.getTransStops()
else:
return 'none'
#Make sure stops are uniform, definate beginning, end. And ensure mid-points are all 50%
colorStops = ParseStops(colorStops, 0)
opacityStops = ParseStops(opacityStops, 1)
#Make sure each Color and Transparency stop has a matching cousin
colorStops, opacityStops = PrepareMerge(colorStops, opacityStops)
#Combine the stops into one stop list
final = merge(colorStops, opacityStops)
if final == None:
print("Error processing Gradient")
return 'none'
gradient = toSVG(validName(material['Name']), final, material['Angle'], material['Invert'], material['GradientType'], material['CenterPoint'], material['FocalPoint'])
id = gradient.attrib['id']
defs.insert(len(defs.getchildren()),gradient)
return "url(#"+str(id)+")"
if material['Pattern']:
return "rgb(0,0,0)"
return 'none'
def embedImage(Environment, root, filename):
"""Open file, save as png and embed into xml"""
svgpng = user_path('AppData', 'Local', 'Temp','svgpng.png')
openImage(Environment, filename)
Doc = App.Documents[-1]
w = Doc.Width
h = Doc.Height
# FileSaveCopyAs
App.Do( Environment, 'FileSaveCopyAs', {
'Encoding': {'PNG': {'Interlaced': False, 'OptimizedPalette': True, 'AlphaChannel': True }},
'FileName': svgpng,
'FileFormat': App.Constants.FileFormat.PNG,
'FormatDesc': u'PNG Portable Network Graphics',
'WorkingMode': 0,
'GeneralSettings': genSilent,
'DefaultProperties': []
}, Doc)
App.Do( Environment, 'FileClose', {}, Doc)
with open(user_path("AppData","Local","Temp","svgpng.png"), 'rb') as f:
data = f.read()
xml.SubElement(root, 'image', {'width':str(w), 'height':str(h), 'href':'data:image/png;base64,' + data.encode("base64")})
def openImage(Environment, filename =""):
"""Open specific image"""
inter = App.Constants.ExecutionMode.Interactive
mode = genSilent.copy()
if filename:
mode['ExecutionMode'] = inter
# FileOpen
App.Do( Environment, 'FileOpen', {
'FileList':[filename],
'Folder': u'C:\\Users\\matthewjohnson\\Pictures',
'FileFormat': App.Constants.FileFormat.Unknown,
'ShowPreview': True,
'EnableBrowser': True,
'FavFileList': [],
'FileOpenScript': u'',
'EnablePreprocessing': False,
'GeneralSettings': mode
})
def pspMatrixToSVG(matrix):
"""Conver PSP matrix to SVG format"""
print("Entered Matrix")
print(matrix)
if matrix:
return "matrix"+str((matrix[0],matrix[3],matrix[1],matrix[4],matrix[2],matrix[5]))
return None
# TODO: Add pre-formatting for unsupported vector types
def convert_to_path(Env, vector_object_path):
"""Perform Convert to path on vector object"""
selectBottomLayer(Env)
select_vector(Env, vector_object_path)
# ConvertToPath
App.Do( Env, 'ConvertToPath', {})
def selectBottomLayer(Environment):
"""Selects bottom most layer in layer's palette"""
App.Do(Environment, 'SelectLayer', {'Path': (9999, -9999, [], False)})
def selectNextLayer(Environment):
"""Selects next full layer"""
return App.Do(Environment, 'SelectNextLayer', {})
def select_vector(Environment, path):
"""Selects vector identified by path"""
return App.Do(Environment, 'VectorSelectionUpdate',
{'Path':path,
'Type':App.Constants.ObjectSelection.Select})
def select_vector_absolute(Environment, path):
"""Selects vector identified by path"""
selectBottomLayer(Environment)
return App.Do(Environment, 'VectorSelectionUpdate',
{'Path':path,
'Type':App.Constants.ObjectSelection.Select})
def nextObject(Environment):
"""If layer contains another vector object return object list"""
if App.Do(Environment, 'GetNextObject')['HaveObject']:
return returnVectorProperties(Environment)
else:
return None
def returnLayerProperties(Environment):
"""Return layer properties"""
result = {}
result = App.Do(Environment, 'ReturnLayerProperties')
return result
def returnVectorProperties(Environment):
"""Return vector object properties as list of objects"""
return App.Do(Environment, 'ReturnVectorObjectProperties', {})
class Gradient_Reader:
def __init__(self, filename):
self._header = ">4sHH"
self._namelen = ">B"
self._namestring = ">{}p"
self._numstops = ">H"
self._colorStop = ">IIH6BHH"
self._transStop = ">IIH"
self._end = ">6B"
self._offset = 0
self._signature = ""
self._version = ""
self._numGradients = ""
self._cStops = []
self._tStops = []
self._name = ""
self.filename = filename
#read entire file
file = open(filename, 'rb')
buff = file.read()
file.close()
#Grab header
self._signature, self._version, self._numGradients = struct.unpack(self._header, buff[self._offset:self._offset + struct.calcsize(self._header)])
self._offset = struct.calcsize(self._header)
#Grab Name
var = struct.unpack(self._namelen, buff[self._offset:self._offset+1])[0]+1
self._name = struct.unpack(">"+str(var)+"p", buff[self._offset:self._offset + struct.calcsize(">"+str(var)+"p")])[0].replace('\x00' , '')
self._offset = self._offset + struct.calcsize(">"+str(var)+"p")
#Grab Color Stops
var = struct.unpack(self._numstops, buff[self._offset:self._offset + struct.calcsize(self._numstops)])[0]
self._offset = self._offset + struct.calcsize(self._numstops)
for i in range(var):
#print struct.unpack(self._colorStop, buff[self._offset: self._offset+struct.calcsize(self._colorStop)])
loc,mid,model, R,R, G,G, B,B, A, type = struct.unpack(self._colorStop, buff[self._offset: self._offset+struct.calcsize(self._colorStop)])
self._cStops.append(cStop(loc, mid, model, [R,G,B],type))
self._offset = self._offset + struct.calcsize(self._colorStop)
#Grab Transparency Stops
var = struct.unpack(self._numstops, buff[self._offset:self._offset + struct.calcsize(self._numstops)])[0]
self._offset = self._offset + struct.calcsize(self._numstops)
for i in range(var):
loc,mid,opacity = struct.unpack(self._transStop, buff[self._offset: self._offset+struct.calcsize(self._transStop)])
self._tStops.append(tStop(loc, mid, opacity))
self._offset = self._offset + struct.calcsize(self._transStop)
#finish end of file
self._offset = self._offset + struct.calcsize(self._end)
def getColorStops(self):
stops = []
for i in self._cStops:
stops.append({
'Color': i.getColor(),
'Location': i.getLocation(),
'MidPoint': i.getMidpoint()})
return stops
def getTransStops(self):
stops = []
for i in self._tStops:
stops.append({
'Level': i.getOpacity(),
'Location': i.getLocation(),
'MidPoint': i.getMidpoint()})
return stops
def getMaterial(self):
return {
'IsPrimary': True,
'NewMaterial': {
'Color': None,
'Pattern': None,
'Gradient': {
'Name': self._name,
'ColorStops': self.getColorStops(),
'TransparencyStops': self.getTransStops(),
},
'Texture': None,
'Art': None
}
}
class cStop:
_offset = 0
_midpoint = 0
_model = 0
_colors = []
_type = 0
def __init__(self, offset, midpoint, model, colors, type):
self._offset = offset
self._midpoint = midpoint
self._model = model
self._colors = colors
self._type = type
def __str__(self):
return self._name
def getLocation(self):
return round((self._offset/4096.0),2)
def getMidpoint(self):
return round(self._midpoint/100.0,2)
def getColor(self):
return (self._colors[0],self._colors[1],self._colors[2])
class tStop:
_offset = 0
_midpoint = 0
_opacity = 0
def __init__(self, offset, midpoint, opacity):
self._offset = offset
self._midpoint = midpoint
self._opacity = opacity
def getLocation(self):
return round((self._offset/4096.0),2)
def getMidpoint(self):
return round(self._midpoint/100.0,2)
def getOpacity(self):
return round(self._opacity/255.0,2) * 100
def enumerate(seq):
return zip(xrange(len(seq)), seq)
def findGradient(Environment, name):
GradientLocations = App.Do(Environment, 'ReturnFileLocations')['Gradients']
for loc in GradientLocations:
for root, dirs, files in walk(loc):
path = root#.split(os.sep)
for file in files:
if file.rfind(name) > -1:
return os.path.join(path,file)
def walk(top):
try:
names = os.listdir(top)
except:
pass
dirs, nondirs = [], []
for name in names:
if os.path.isdir(os.path.join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
yield (top, dirs, nondirs)
def ParseStops(stops, type):
parsedStops = []
#If the starting point is not at zero, add a point that starts at zero
if stops[0]['Location'] > 0:
newstart = stops[0].copy()
newstart['Location'] = 0
parsedStops.append(newstart)
#if the ending point is not at 100%, add a point that ends at 100
if stops[-1]['Location'] < 1:
newend = stops[-1].copy()
newend['Location'] = 1.0
stops.append(newend)
#Next go through all stops, if a stop has a midpoint at any position other than 50%
#add a color point at the current midpoint.
for i,stop in enumerate(stops):
parsedStops.append(stop)
if int(stop['MidPoint'] * 100.0) != 50:
if i == len(stops)-1:
continue
location = (stops[i+1]['Location'] - stop['Location'] ) * stop['MidPoint'] + stop['Location']
if type == 0:
r = ((stops[i+1]['Color'][0] - stop['Color'][0])/2) + stop['Color'][0]
g = ((stops[i+1]['Color'][1] - stop['Color'][1])/2) + stop['Color'][1]
b = ((stops[i+1]['Color'][2] - stop['Color'][2])/2) + stop['Color'][2]
parsedStops.append({'Color':(r,g,b),'Location':location,'MidPoint':.5})
else:
l = ((stops[i+1]['Level'] - stop['Level'])/2) + stop['Level']
parsedStops.append({'Level':l,'Location':location,'MidPoint':.5})
return parsedStops
def rgb_stop_interp(rs0, rs1, z):
z = z * 1.0
M =(z - rs0['Location'])/(rs1['Location'] - rs0['Location'])
rs = {}
rs['Location'] = z
rsr = rs0['Color'][0] + M*(rs1['Color'][0] - rs0['Color'][0])
rsg = rs0['Color'][1] + M*(rs1['Color'][1] - rs0['Color'][1])
rsb = rs0['Color'][2] + M*(rs1['Color'][2] - rs0['Color'][2])
rs['Color'] = (round(rsr),round(rsg),round(rsb))
rs['MidPoint'] = .5
return rs
def op_stop_interp(os0,os1,z):
z = z * 1.0
M =(z - os0['Location'])/(os1['Location'] - os0['Location'])
os = {}
os['Location'] = z
os['Level'] = os0['Level'] + M*(os1['Level'] - os0['Level'])
os['MidPoint'] = 0.5
return os
def PrepareMerge(cstops, tstops):
tstops = PrepareStops(cstops, tstops, op_stop_interp)
cstops = PrepareStops(tstops, cstops, rgb_stop_interp)
return cstops, tstops
def PrepareStops(src, dest, func):
for x in src:
if x['Location'] not in [y['Location'] for y in dest]:
for i,y in enumerate(dest):
if y['Location'] < x['Location']:
y0 = y
else:
y1 = y
break
dest.insert(i,func(y0, y1, x['Location']))
return dest
def merge(cstops, tstops):
if len(cstops) != len(tstops):
return
mergeStops = []
for i in range(len(cstops)):
mergeStops.append({'Color':cstops[i]['Color'], 'Level':tstops[i]['Level'], 'Location':cstops[i]['Location']})
return mergeStops
def toRadians(degrees):
return degrees / 180 * math.pi
def pointOfAngle(a):
return {'x':math.cos(a),
'y':math.sin(a)}
def degreesToRadians(d):
return ((d * math.pi) / 180)
def angleToPoints(angle):
eps = math.pow(2, -52)
angle = (angle % 360)
startPoint = pointOfAngle(degreesToRadians(90+angle))
endPoint = pointOfAngle(degreesToRadians(270 + angle))
# if you want negative values you can remove the following checks
# but most likely it will produce undesired results
if startPoint['x'] <= 0 or abs(startPoint['x']) <= eps:
startPoint['x'] = 0
if startPoint['y'] <= 0 or abs(startPoint['y']) <= eps:
startPoint['y'] = 0
if endPoint['x'] <= 0 or abs(endPoint['x']) <= eps:
endPoint['x'] = 0
if endPoint['y'] <= 0 or abs(endPoint['y']) <= eps:
endPoint['y'] = 0
return (round(startPoint['x'],2), round(startPoint['y'],2), round(endPoint['x'],2), round(endPoint['y'],2))
def toSVG(name, stops, angle, invert, type, centerpoint=(0.5,0.5), focalpoint=(0.5,0.5)):
if invert:
newstops = []
count = len(stops) -1
for i in range(count+1):
newstops.append({'Color':stops[i]['Color'], 'Level':stops[i]['Level'], 'Location': stops[count-i]['Location']})
stops = newstops
stops.reverse()
svg = ""
if type == 0:
anglePoints = angleToPoints(angle)
x1 = anglePoints[0]
y1 = anglePoints[1]
x2 = anglePoints[2]
y2 = anglePoints[3]
lg = xml.Element('linearGradient', {'id':name, 'x1':str(x1), 'y1':str(y1), 'x2':str(x2), 'y2':str(y2)})
for x in stops:
xml.SubElement(lg, 'stop', {'offset': str(round(x['Location']*100.0,2))+'%', 'stop-color':'rgb'+str(x['Color']), 'stop-opacity':str(round(x['Level']/100.0,4))})
return lg
else:
if focalpoint == None:
focalpoint = (0.5, 0.5)
id = str(uuid.uuid4())
rg = xml.Element('radialGraident', {'id':id,
'cx':str(centerpoint[0]*100)+'%',
'cy':str(centerpoint[1]*100)+'%',
'fx':str(focalpoint[0]*100)+'%',
'fy':str(focalpoint[1]*100)+'%'})
for x in stops:
xml.SubElement(rg, 'stop',{'offset':str(round(x['Location']*100.0,2)),
'stop-color':'rgb'+str(x['Color']),
'stop-opacity':str(round(x['Level']/100.0,4))})
return rg