-
Notifications
You must be signed in to change notification settings - Fork 7
/
shapekeyimport_2_8.py
2075 lines (1631 loc) · 71.7 KB
/
shapekeyimport_2_8.py
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
# This Blender add-on imports paths and shapeKeys from an SVG file
# Supported Blender Version: 2.8 Beta
#
# Copyright (C) 2018 Shrinivas Kulkarni
#
# License: GPL (https://github.com/Shriinivas/shapeKeyimport/blob/master/LICENSE)
#
# Not yet pep8 compliant
# Scaling not done based on the unit of the SVG document, but based simply on value
# If precise scaling is needed, appropriate unit (mm) needs to be set in the source SVG
import bpy, copy, math, re, time, os
from bpy.props import IntProperty, FloatProperty, BoolProperty, StringProperty
from bpy.props import CollectionProperty, EnumProperty
from xml.dom import minidom
from collections import OrderedDict
from mathutils import Vector, Matrix
from math import sqrt, cos, sin, acos, degrees, radians, tan
from cmath import exp, sqrt as csqrt, phase
from collections.abc import MutableSequence
#################### UI and Registration Stuff ####################
bl_info = {
"name": "Import Paths and Shape Keys from SVG",
"author": "Shrinivas Kulkarni",
"location": "File > Import > Import Paths & Shape Keys (.svg)",
"category": "Import-Export",
"blender": (2, 80, 0),
}
noneStr = "-None-"
CURVE_NAME_PREFIX = 'Curve'
def getCurveNames(scene, context):
return [(noneStr, noneStr, '-1')] + [(obj.name, obj.name, str(i)) for i, obj in
enumerate(context.scene.objects) if obj.type == 'CURVE']
def getAlignmentList(scene, context):
alignListStrs = [*getAlignSegsFn().keys()]
return [(noneStr, noneStr, '-1')] + [(str(align), str(align), str(i))
for i, align in enumerate(alignListStrs)]
def getMatchPartList(scene, context):
arrangeListStrs = [*getAlignPartsFn().keys()]
return [(noneStr, noneStr, '-1')] + [(str(arrange), str(arrange), str(i))
for i, arrange in enumerate(arrangeListStrs)]
class ObjectImportShapeKeys(bpy.types.Operator):
bl_idname = "object.import_shapekeys"
bl_label = "Import Paths & Shape Keys"
bl_options = {'REGISTER', 'UNDO'}
filter_glob : StringProperty(default="*.svg")
filepath : StringProperty(subtype='FILE_PATH')
#User input
byGroup : BoolProperty(name="Import By Group", \
description = "Import target and shape key paths forming a group in SVG", \
default = True)
byAttrib : BoolProperty(name="Import By Attribute", \
description = "Import targets having attribute defining shape key path IDs in SVG", \
default = True)
shapeKeyAttribName : StringProperty(name="Attribute", \
description = "Name of target path attribute used to define shape keys in SVG",
default = 'shapekeys')
addShapeKeyPaths : BoolProperty(name="Retain Shape Key Paths", \
description = "Import shape key paths as paths as well as shape keys", \
default = False)
addNontargetPaths : BoolProperty(name="Import Non-target Paths", \
description = "Import paths that are neither targets nor shape keys", \
default = True)
addPathsFromHiddenLayer : BoolProperty(name="Import Hidden Layer Paths",
description='Import paths from layers marked as hidden in SVG', \
default = False)
originToGeometry : BoolProperty(name="Origin To Geometry", \
description="Shift the imported path's origin to its geometry center", \
default = False)
xScale : FloatProperty(name="X", \
description="X scale factor for imported paths", \
default = 0.01)
yScale : FloatProperty(name="Y", \
description="Y scale factor for imported paths", \
default = 0.01)
zLocation : FloatProperty(name="Z Location", \
description='Z coordiate value for imported paths', default = 0)
resolution : IntProperty(name="Resolution", \
description='Higher value gives smoother transition but more complex geometry', \
default = 0, min=0)
objList : EnumProperty(name="Copy Properties From", items = getCurveNames, \
description='Curve whose material, depth etc. should be copied on to imported paths')
partMatchList : EnumProperty(name="Match Parts By", items = getMatchPartList, \
description='Match disconnected parts of target and shape key based on (BBox -> Bounding Box)')
alignList : EnumProperty(name="Node Alignment Order", items = getAlignmentList, \
description = 'Start aligning the nodes of target and shape keys (paths or parts) from')
def execute(self, context):
createdObjsMap = main(infilePath = self.filepath, \
shapeKeyAttribName = self.shapeKeyAttribName, \
byGroup = self.byGroup, \
byAttrib = self.byAttrib, \
addShapeKeyPaths = self.addShapeKeyPaths, \
addNontargetPaths = self.addNontargetPaths, \
scale = [self.xScale, -self.yScale, 1], \
zVal = self.zLocation, \
resolution = self.resolution, \
copyObjName = self.objList, \
partArrangeOrder = self.partMatchList, \
alignOrder = self.alignList, \
pathsFromHiddenLayer = self.addPathsFromHiddenLayer, \
originToGeometry = self.originToGeometry)
return {'FINISHED'}
def draw(self, context):
layout = self.layout
col = layout.column()
row = col.row()
row.prop(self, "byGroup")
row = col.row()
row.prop(self, "byAttrib")
row = col.row()
row.prop(self, "shapeKeyAttribName")
row = col.row()
row.prop(self, "addShapeKeyPaths")
row = col.row()
row.prop(self, "addNontargetPaths")
row = col.row()
row.prop(self, "addPathsFromHiddenLayer")
row = col.row()
row.prop(self, "originToGeometry")
layout.row().separator()
row = col.row()
row.label(text = 'Scale')
row = col.row()
row.prop(self, "xScale")
row.prop(self, "yScale")
row = col.row()
row.prop(self, "zLocation")
layout.row().separator()
row = col.row()
row.prop(self, "resolution")
row = col.row()
row.prop(self, "objList")
row = col.row()
row.prop(self, "partMatchList")
row = col.row()
row.prop(self, "alignList")
def invoke(self, context, event):
alignListStrs = [*getAlignSegsFn().keys()]
arrangeListStrs = [*getAlignPartsFn().keys()]
#default values
self.objList = noneStr
self.partMatchList = str(arrangeListStrs[-1])
self.alignList = str(alignListStrs[-1])
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def menuImportShapeKeys(self, context):
self.layout.operator(ObjectImportShapeKeys.bl_idname,
text="Import Paths & Shape Keys (.svg)")
def register():
bpy.utils.register_class(ObjectImportShapeKeys)
bpy.types.TOPBAR_MT_file_import.append(menuImportShapeKeys)
def unregister():
bpy.utils.unregister_class(ObjectImportShapeKeys)
bpy.types.TOPBAR_MT_file_import.remove(menuImportShapeKeys)
if __name__ == "__main__":
register()
###################### addon code start ####################
DEF_ERR_MARGIN = 0.0001
hiddenLayerAttr = 'display:none'
def isValidPath(pathElem):
dVal = pathElem.getAttribute('d')
return (dVal != None) and (dVal.strip() != "") and \
(dVal[0] in set('MLHVCSQTAmlhvcsqa'))
class OrderedSet(OrderedDict):
def add(self, item):
super(OrderedSet, self).__setitem__(item, '')
def __iter__(self):
return super.keys().__iter__()
#...Other methods to be added when needed
class Part():
def __init__(self, segments, isClosed):
self.segs = segments
self.isClosed = isClosed
if(len(segments) > 0):
self.partToClose = self.isContinuous()
def copy(self, start, end):
if(start == None):
start = 0
if(end == None):
end = len(self.segs)
return Part(self.segs[start:end], None)#IsClosing not defined, so set to None
def getSeg(self, idx):
return self.segs[idx]
def getSegs(self):
return self.segs
def getSegsCopy(self, start, end):
if(start == None):
start = 0
if(end == None):
end = len(self.segs)
return self.segs[start:end]
def bbox(self):
leftBot_rgtTop = [[None]*2,[None]*2]
for seg in self.segs:
bb = bboxCubicBezier(seg)
for i in range(0, 2):
if (leftBot_rgtTop[0][i] == None or bb[0][i] < leftBot_rgtTop[0][i]):
leftBot_rgtTop[0][i] = bb[0][i]
for i in range(0, 2):
if (leftBot_rgtTop[1][i] == None or bb[1][i] > leftBot_rgtTop[1][i]):
leftBot_rgtTop[1][i] = bb[1][i]
return leftBot_rgtTop
def isContinuous(self):
return cmplxCmpWithMargin(self.segs[0].start, self.segs[-1].end)
def getSegCnt(self):
return len(self.segs)
def length(self, error):
return sum(seg.length(error = error) for seg in self.segs)
class PathElem:
def __init__(self, path, attributes, transList, seqId):
self.parts = getDisconnParts(path)
self.pathId = attributes['id'].value
self.attributes = attributes
self.transList = transList
self.seqId = seqId
def getPartCnt(self):
return len(self.parts)
def getPartView(self):
p = Part([seg for part in self.parts for seg in part.getSegs()], None)
return p
def getPartBoundaryIdxs(self):
cumulCntList = set()
cumulCnt = 0
for p in self.parts:
cumulCnt += p.getSegCnt()
cumulCntList.add(cumulCnt)
return cumulCntList
def updatePartsList(self, segCntsPerPart, byPart):
monolithicSegList = [seg for part in self.parts for seg in part.getSegs()]
self.parts.clear()
for i in range(0, len(segCntsPerPart)):
if( i == 0):
currIdx = 0
else:
currIdx = segCntsPerPart[i-1]
nextIdx = segCntsPerPart[i]
isClosed = None
if(byPart == True and i < len(self.parts)):
isClosed = self.parts[i].isClosed # Let's retain as far as possible
self.parts.append(Part(monolithicSegList[currIdx:nextIdx], isClosed))
def __repr__(self):
return self.pathId
class BlenderBezierPoint:
#all points are complex values not 3d vectors
def __init__(self, pt, handleLeft, handleRight):
self.pt = pt
self.handleLeft = handleLeft
self.handleRight = handleRight
def __repr__(self):
return str(self.pt)
def getPathElemMap(doc, pathsFromHiddenLayer):
elemMap = {}
seqId = 0
for pathXMLElem in doc.getElementsByTagName('path'):
if (isElemSelectable(pathXMLElem, pathsFromHiddenLayer) and
isValidPath(pathXMLElem)):
dVal = pathXMLElem.getAttribute('d')
transList = []
idAttr = pathXMLElem.getAttribute('id')
parsedPath = parse_path(dVal)
getTransformAttribs(pathXMLElem, transList)
pathElem = PathElem(parsedPath, pathXMLElem.attributes, transList, seqId)
elemMap[idAttr] = pathElem
seqId += 1
return elemMap
def main(infilePath, shapeKeyAttribName, byGroup, byAttrib, addShapeKeyPaths,
addNontargetPaths, scale, zVal, resolution, copyObjName, partArrangeOrder, alignOrder,
pathsFromHiddenLayer, originToGeometry):
doc = minidom.parse(infilePath)
pathElemsMap = getPathElemMap(doc, pathsFromHiddenLayer)
pathElems = [*pathElemsMap.values()]
normalizePathElems(pathElems, alignOrder, partArrangeOrder)
targetShapeKeyMap = {}
allShapeKeyIdsSet = set()
if(byGroup == True):
updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer)
if(byAttrib == True):
updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, allShapeKeyIdsSet, shapeKeyAttribName)
#List of lists with all the interdependent paths that need to be homogenized
dependentPathIdsSets = getDependentPathIdsSets(targetShapeKeyMap)
byPart = (partArrangeOrder != noneStr)
for prntIdx, dependentPathIdsSet in enumerate(dependentPathIdsSets):
dependentPathsSet = [pathElemsMap.get(dependentPathId) for dependentPathId in dependentPathIdsSet
if pathElemsMap.get(dependentPathId) != None]
addMissingSegs(dependentPathsSet, byPart = byPart, resolution = resolution)
bIdxs = set()
for pathElem in dependentPathsSet:
bIdxs = bIdxs.union(pathElem.getPartBoundaryIdxs())
for pathElem in dependentPathsSet:
pathElem.updatePartsList(sorted(list(bIdxs)), byPart)
#All will have same part count by now
allToClose = [all(pathElem.parts[j].partToClose for pathElem in dependentPathsSet)
for j in range(0, len(dependentPathsSet[0].parts))]
#All interdependent paths will have the same no of splines with the same no of bezier points
for pathElem in dependentPathsSet:
for j, part in enumerate(pathElem.parts):
part.partToClose = allToClose[j]
objPathIds = set(targetShapeKeyMap.keys())
if(addNontargetPaths == True):
nontargetIds = (pathElemsMap.keys() - targetShapeKeyMap.keys()) - allShapeKeyIdsSet
objPathIds = objPathIds.union(nontargetIds)
if(addShapeKeyPaths == True):
#in case shapeKeys are also targets
shapeKeyIdsToAdd = allShapeKeyIdsSet - targetShapeKeyMap.keys()
objPathIds = objPathIds.union(shapeKeyIdsToAdd.intersection(pathElemsMap.keys()))
copyObj = bpy.data.objects.get(copyObjName)#Can be None
objMap = {}
if(len(objPathIds) > 0):
groupName = os.path.basename(infilePath)
group = bpy.data.collections.new(groupName)
bpy.context.scene.collection.children.link(group)
for objPathId in objPathIds:
addSvg2Blender(group, objMap, pathElemsMap[objPathId], scale, zVal, copyObj, originToGeometry)
for pathElemId in targetShapeKeyMap.keys():
pathObj = objMap[pathElemId]
pathObj.shape_key_add(name = 'Basis')
shapeKeyElemIds = targetShapeKeyMap[pathElemId].keys()
for shapeKeyElemId in shapeKeyElemIds:
shapeKeyElem = pathElemsMap.get(shapeKeyElemId)
if(shapeKeyElem != None):#Maybe no need after so many checks earlier
addShapeKey(pathObj, shapeKeyElem, shapeKeyElemId, scale, zVal, originToGeometry)
return objMap
#Avoid errors due to floating point conversions/comparisons
def cmplxCmpWithMargin(complex1, complex2, margin = DEF_ERR_MARGIN):
return floatCmpWithMargin(complex1.real, complex2.real, margin) and \
floatCmpWithMargin(complex1.imag, complex2.imag, margin)
def floatCmpWithMargin(float1, float2, margin = DEF_ERR_MARGIN):
return abs(float1 - float2) < margin
#TODO: Would be more conditions like defs. Need a better solution
def isElemSelectable(elem, pathsFromHiddenLayer):
return getParentInHierarchy(elem, 'defs') == None and \
(pathsFromHiddenLayer == True or not isInHiddenLayer(elem))
def getParentInHierarchy(elem, parentTag):
parent = elem.parentNode
while(parent != None and parent.parentNode != None and parent.tagName != parentTag):
parent = parent.parentNode
#TODO: Better way to detect the Document node
if(parent.parentNode == None):
return None
return parent
def getTransformAttribs(elem, transList):
if(elem.nodeType == elem.DOCUMENT_NODE):
return
transAttr = elem.getAttribute('transform')
if(transAttr != None):
transList.append(transAttr)
if(elem.parentNode != None):
getTransformAttribs(elem.parentNode, transList)
def isInHiddenLayer(elem):
parent = elem.parentNode
while(parent != None and parent.nodeType == parent.ELEMENT_NODE and \
(parent.tagName != 'g' or (parent.parentNode != None and \
parent.parentNode.tagName != 'svg'))):
parent = parent.parentNode
if(parent != None and parent.nodeType == parent.ELEMENT_NODE):
return parent.getAttribute('style').startswith(hiddenLayerAttr)
return False
def getDependentPathIdsSets(shapeKeyMap):
pathIdSets = []
allAddedPathIds = set()
for targetId in shapeKeyMap.keys():
#Keep track of the added path Ids since the target can be a shapeKey,
#or a target of one of the shapeKeys of this target (many->many relation)
if(targetId not in allAddedPathIds):
pathIdSet = set()
addDependentPathsToList(shapeKeyMap, pathIdSet, targetId)
pathIdSets.append(pathIdSet)
allAddedPathIds = allAddedPathIds.union(pathIdSet)
return pathIdSets
#Reverse lookup
def getKeysetWithValue(srcMap, value):
keySet = set()
for key in srcMap:
if(value in srcMap[key]):
keySet.add(key)
return keySet
#All the shape keys and their other targets are added recursively
def addDependentPathsToList(shapeKeyMap, pathIdSet, targetId):
if(targetId in pathIdSet):
return pathIdSet
pathIdSet.add(targetId)
shapeKeyElemIdMap = shapeKeyMap.get(targetId)
if(shapeKeyElemIdMap == None):
return pathIdSet
shapeKeyElemIdList = shapeKeyElemIdMap.keys()
if(shapeKeyElemIdList == None):
return pathIdSet
for shapeKeyElemId in shapeKeyElemIdList:
#Recuresively add the Ids that are shape key of this shape key
addDependentPathsToList(shapeKeyMap, pathIdSet, shapeKeyElemId)
#Recursively add the Ids that are other targets of this shape key
keyset = getKeysetWithValue(shapeKeyMap, shapeKeyElemId)
for key in keyset:
addDependentPathsToList(shapeKeyMap, pathIdSet, key)
return pathIdSet
def getAllPathElemsInGroup(parentElem, pathElems):
for childNode in parentElem.childNodes:
if childNode.nodeType == childNode.ELEMENT_NODE:
if(childNode.tagName == 'path' and isValidPath(childNode)):
pathElems.append(childNode)
elif(childNode.tagName == 'g'):
getAllPathElemsInGroup(childNode, pathElems)
def updateShapeKeyMapByGroup(targetShapeKeyMap, allShapeKeyIdsSet, doc, pathsFromHiddenLayer):
groupElems = [groupElem for groupElem in doc.getElementsByTagName('g')
if (groupElem.parentNode.tagName != 'svg' and
isElemSelectable(groupElem, pathsFromHiddenLayer))]
for groupElem in groupElems:
pathElems = []
getAllPathElemsInGroup(groupElem, pathElems)
if(pathElems != None and len(pathElems) > 1 ):
targetId = pathElems[0].getAttribute('id')
if(targetShapeKeyMap.get(targetId) == None):
targetShapeKeyMap[targetId] = OrderedSet()
for i in range(1, len(pathElems)):
shapeKeyId = pathElems[i].getAttribute('id')
targetShapeKeyMap[targetId].add(shapeKeyId)
allShapeKeyIdsSet.add(shapeKeyId)
def updateShapeKeyMapByAttrib(targetShapeKeyMap, pathElemsMap, \
allShapeKeyIdsSet, shapeKeyAttribName):
for key in pathElemsMap.keys():
targetPathElem = pathElemsMap[key]
attributes = targetPathElem.attributes
shapeKeyIdAttrs = attributes.get(shapeKeyAttribName)
if(shapeKeyIdAttrs != None):
shapeKeyIds = shapeKeyIdAttrs.value
shapeKeyIdsStr = str(shapeKeyIds)
shapeKeyIdList = shapeKeyIdsStr.replace(' ','').split(',')
if(targetShapeKeyMap.get(key) == None):
targetShapeKeyMap[key] = OrderedSet()
for keyId in shapeKeyIdList:
if(pathElemsMap.get(keyId) != None):
targetShapeKeyMap[key].add(keyId)
allShapeKeyIdsSet.add(keyId)
def bboxArea(leftBot_rgtTop):
return abs((leftBot_rgtTop[1][0]-leftBot_rgtTop[0][0]) * \
(leftBot_rgtTop[1][1]-leftBot_rgtTop[0][1]))
#see https://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve
#(3 D - 9 C + 9 B - 3 A) t^2 + (6 A - 12 B + 6 C) t + 3 (B - A)
def bboxCubicBezier(bezier):
def evalBez(AA, BB, CC, DD, t):
return AA * (1 - t) * (1 - t) * (1 - t) + \
3 * BB * t * (1 - t) * (1 - t) + \
3 * CC * t * t * (1 - t) + \
DD * t * t * t
A = [bezier.start.real, bezier.start.imag]
B = [bezier.control1.real, bezier.control1.imag]
C = [bezier.control2.real, bezier.control2.imag]
D = [bezier.end.real, bezier.end.imag]
MINXY = [min([A[0], D[0]]), min([A[1], D[1]])]
MAXXY = [max([A[0], D[0]]), max([A[1], D[1]])]
leftBot_rgtTop = [MINXY, MAXXY]
a = [3 * D[i] - 9 * C[i] + 9 * B[i] - 3 * A[i] for i in range(0, 2)]
b = [6 * A[i] - 12 * B[i] + 6 * C[i] for i in range(0, 2)]
c = [3 * (B[i] - A[i]) for i in range(0, 2)]
solnsxy = []
for i in range(0, 2):
solns = []
if(a[i] == 0):
if(b[i] == 0):
solns.append(0)#Independent of t so lets take the starting pt
else:
solns.append(c[i] / b[i])
else:
rootFact = b[i] * b[i] - 4 * a[i] * c[i]
if(rootFact >=0 ):
#Two solutions with + and - sqrt
solns.append((-b[i] + sqrt(rootFact)) / (2 * a[i]))
solns.append((-b[i] - sqrt(rootFact)) / (2 * a[i]))
solnsxy.append(solns)
for i, soln in enumerate(solnsxy):
for j, t in enumerate(soln):
if(t < 1 and t > 0):
co = evalBez(A[i], B[i], C[i], D[i], t)
if(co < leftBot_rgtTop[0][i]):
leftBot_rgtTop[0][i] = co
if(co > leftBot_rgtTop[1][i]):
leftBot_rgtTop[1][i] = co
return leftBot_rgtTop
def getLineSegment(start, end, t0, t1):
xt0, yt0 = (1 - t0) * start.real + t0 * end.real , (1 - t0) * start.imag + t0 * end.imag
xt1, yt1 = (1 - t1) * start.real + t1 * end.real , (1 - t1) * start.imag + t1 * end.imag
return CubicBezier(complex(xt0, yt0), complex(xt0, yt0),
complex(xt1, yt1), complex(xt1, yt1))
#see https://stackoverflow.com/questions/878862/drawing-part-of-a-b%c3%a9zier-curve-by-reusing-a-basic-b%c3%a9zier-curve-function/879213#879213
def getCurveSegment(seg, t0, t1):
ctrlPts = seg
if(t0 > t1):
tt = t1
t1 = t0
t0 = tt
#Let's make at least the line segments of predictable length :)
if(ctrlPts[0] == ctrlPts[1] and ctrlPts[2] == ctrlPts[3]):
return getLineSegment(ctrlPts[0], ctrlPts[2], t0, t1)
x1, y1 = ctrlPts[0].real, ctrlPts[0].imag
bx1, by1 = ctrlPts[1].real, ctrlPts[1].imag
bx2, by2 = ctrlPts[2].real, ctrlPts[2].imag
x2, y2 = ctrlPts[3].real, ctrlPts[3].imag
u0 = 1.0 - t0
u1 = 1.0 - t1
qxa = x1*u0*u0 + bx1*2*t0*u0 + bx2*t0*t0
qxb = x1*u1*u1 + bx1*2*t1*u1 + bx2*t1*t1
qxc = bx1*u0*u0 + bx2*2*t0*u0 + x2*t0*t0
qxd = bx1*u1*u1 + bx2*2*t1*u1 + x2*t1*t1
qya = y1*u0*u0 + by1*2*t0*u0 + by2*t0*t0
qyb = y1*u1*u1 + by1*2*t1*u1 + by2*t1*t1
qyc = by1*u0*u0 + by2*2*t0*u0 + y2*t0*t0
qyd = by1*u1*u1 + by2*2*t1*u1 + y2*t1*t1
xa = qxa*u0 + qxc*t0
xb = qxa*u1 + qxc*t1
xc = qxb*u0 + qxd*t0
xd = qxb*u1 + qxd*t1
ya = qya*u0 + qyc*t0
yb = qya*u1 + qyc*t1
yc = qyb*u0 + qyd*t0
yd = qyb*u1 + qyd*t1
return CubicBezier(complex(xa, ya), complex(xb, yb),
complex(xc, yc), complex(xd, yd))
def subdivideSeg(origSeg, noSegs):
if(noSegs < 2):
return [origSeg]
segs = []
oldT = 0
segLen = origSeg.length(error = DEF_ERR_MARGIN) / noSegs
for i in range(0, noSegs-1):
t = float(i+1) / noSegs
cBezier = getCurveSegment(origSeg, oldT, t)
segs.append(cBezier)
oldT = t
cBezier = getCurveSegment(origSeg, oldT, 1)
segs.append(cBezier)
return segs
def getSubdivCntPerSeg(part, toAddCnt):
class ItemWrapper:
def __init__(self, idx, item):
self.idx = idx
self.item = item
self.length = item.length(error = DEF_ERR_MARGIN)
class PartWrapper:
def __init__(self, part):
self.itemList = []
self.itemCnt = len(part.getSegs())
for idx, seg in enumerate(part.getSegs()):
self.itemList.append(ItemWrapper(idx, seg))
partWrapper = PartWrapper(part)
partLen = part.length(DEF_ERR_MARGIN)
avgLen = partLen / (partWrapper.itemCnt + toAddCnt)
segsToDivide = [item for item in partWrapper.itemList if item.length >= avgLen]
segToDivideCnt = len(segsToDivide)
avgLen = sum(item.length for item in segsToDivide) / (segToDivideCnt + toAddCnt)
segsToDivide = sorted(segsToDivide, key=lambda x: x.length, reverse = True)
cnts = [0] * partWrapper.itemCnt
addedCnt = 0
for i in range(0, segToDivideCnt):
segLen = segsToDivide[i].length
divideCnt = int(round(segLen/avgLen)) - 1
if(divideCnt == 0):
break
if((addedCnt + divideCnt) >= toAddCnt):
cnts[segsToDivide[i].idx] = toAddCnt - addedCnt
addedCnt = toAddCnt
break
cnts[segsToDivide[i].idx] = divideCnt
addedCnt += divideCnt
#TODO: Verify if needed
while(toAddCnt > addedCnt):
for i in range(0, segToDivideCnt):
cnts[segsToDivide[i].idx] += 1
addedCnt += 1
if(toAddCnt == addedCnt):
break
return cnts
def getDisconnParts(path):
prevSeg = None
disconnParts = []
segs = []
for i in range(0, len(path)):
seg = path[i]
if((prevSeg== None) or not cmplxCmpWithMargin(prevSeg.end, seg.start)):
if(len(segs) > 0):
disconnParts.append(Part(segs, segs[-1].isClosing))
segs = []
prevSeg = seg
segs.append(seg)
if(len(path) > 0 and len(segs) > 0):
disconnParts.append(Part(segs, segs[-1].isClosing))
return disconnParts
def normalizePathElems(pathElems, alignOrder, partArrangeOrder):
for pathElem in pathElems:
toTransformedCBezier(pathElem)
alignPath(pathElem, alignOrder, partArrangeOrder)
#Resolution is mapped to parts
#The value 100 means 1 segment per unit length (whatever it is in source SVG) of Part
def getSegCntForResolution(part, resolution):
segCnt = part.getSegCnt()
segCntForRes = int(part.length(error = DEF_ERR_MARGIN) * resolution / 100)
if(segCnt > segCntForRes):
return segCnt
else:
return segCntForRes
#Distribute equally; this is likely a rare condition. So why complicate?
def distributeCnt(maxSegCntsByPart, startIdx, extraCnt):
added = 0
elemCnt = len(maxSegCntsByPart) - startIdx
cntPerElem = math.floor(extraCnt / elemCnt)
remainder = extraCnt % elemCnt
for i in range(startIdx, len(maxSegCntsByPart)):
maxSegCntsByPart[i] += cntPerElem
if(i < remainder + startIdx):
maxSegCntsByPart[i] += 1
#Make all the paths to have the maximum number of segments in the set
def addMissingSegs(pathElems, byPart, resolution):
maxSegCntsByPart = []
samePartCnt = True
maxSegCnt = 0
resSegCnt = []
sortedElems = sorted(pathElems, key = lambda p: -len(p.parts))
for i, pathElem in enumerate(sortedElems):
if(byPart == False):
segCnt = getSegCntForResolution(pathElem.getPartView(), resolution)
if(segCnt > maxSegCnt):
maxSegCnt = segCnt
else:
resSegCnt.append([])
for j, part in enumerate(pathElem.parts):
partSegCnt = getSegCntForResolution(part, resolution)
resSegCnt[i].append(partSegCnt)
#First path
if(j == len(maxSegCntsByPart)):
maxSegCntsByPart.append(partSegCnt)
#last part of this path, but other paths in set have more parts
elif((j == len(pathElem.parts) - 1) and
len(maxSegCntsByPart) > len(pathElem.parts)):
remainingSegs = sum(maxSegCntsByPart[j:])
if(partSegCnt <= remainingSegs):
resSegCnt[i][j] = remainingSegs
else:
#This part has more segs than the sum of the remaining part segs
#So distribute the extra count
distributeCnt(maxSegCntsByPart, j, (partSegCnt - remainingSegs))
#Also, adjust the seg count of the last part of the previous
#segments that had fewer than max number of parts
for k in range(0, i):
if(len(sortedElems[k].parts) < len(maxSegCntsByPart)):
totalSegs = sum(maxSegCntsByPart)
existingSegs = sum(maxSegCntsByPart[:len(sortedElems[k].parts)-1])
resSegCnt[k][-1] = totalSegs - existingSegs
elif(partSegCnt > maxSegCntsByPart[j]):
maxSegCntsByPart[j] = partSegCnt
for i, pathElem in enumerate(sortedElems):
if(byPart == False):
partView = pathElem.getPartView()
segCnt = partView.getSegCnt()
diff = maxSegCnt - segCnt
if(diff > 0):
cnts = getSubdivCntPerSeg(partView, diff)
cumulSegIdx = 0
for j in range(0, len(pathElem.parts)):
part = pathElem.parts[j]
newSegs = []
for k, seg in enumerate(part.getSegs()):
numSubdivs = cnts[cumulSegIdx] + 1
newSegs += subdivideSeg(seg, numSubdivs)
cumulSegIdx += 1
#isClosed won't be used, but let's update anyway
pathElem.parts[j] = Part(newSegs, part.isClosed)
else:
for j in range(0, len(pathElem.parts)):
part = pathElem.parts[j]
newSegs = []
partSegCnt = part.getSegCnt()
#TODO: Adding everything in the last part?
if(j == (len(pathElem.parts)-1) and
len(maxSegCntsByPart) > len(pathElem.parts)):
diff = resSegCnt[i][j] - partSegCnt
else:
diff = maxSegCntsByPart[j] - partSegCnt
if(diff > 0):
cnts = getSubdivCntPerSeg(part, diff)
for k, seg in enumerate(part.getSegs()):
seg = part.getSeg(k)
subdivCnt = cnts[k] + 1 #1 for the existing one
newSegs += subdivideSeg(seg, subdivCnt)
#isClosed won't be used, but let's update anyway
pathElem.parts[j] = Part(newSegs, part.isClosed)
def transTranslate(elems):
y = 0
if(len(elems) > 1):
y = elems[1]
return Matrix.Translation((elems[0], y, 0))
def transScale(elems):
y = 0
if(len(elems) > 1):
y = elems[1]
return Matrix.Scale(elems[0], 4, (1, 0, 0)) @ \
Matrix.Scale(y, 4, (0, 1, 0))
def transRotate(elems):
m = Matrix()
if(len(elems) > 1):
m = transTranslate(elems[1:])
return m @ Matrix.Rotation(radians(elems[0]), 4, Vector((0, 0, 1))) \
@ m.inverted()
def transSkewX(elems):
mat = Matrix()
mat[0][1] = tan(radians(elems[0]))
return mat
def transSkewY(elems):
mat = Matrix()
mat[1][0] = tan(radians(elems[0]))
return mat
def transMatrix(elems):
#standard matrix with diagonal elems = 1
mat = Matrix()
mat[0][0] = elems[0]
mat[0][1] = elems[2]
mat[0][3] = elems[4]
mat[1][0] = elems[1]
mat[1][1] = elems[3]
mat[1][3] = elems[5]
return mat
transforms = {'translate': transTranslate,
'scale': transScale,
'rotate': transRotate,
'skewX': transSkewX,
'skewY': transSkewY,
'matrix': transMatrix}
def getTransformMatrix(transList):
mat = Matrix()
regEx = re.compile('([^\(]+)\(([^\)]+)\)')
for transform in transList:
results = regEx.findall(transform)
if(results != None and len(results) > 0):
for res in results:
fnStr = res[0]
elems = [float(e) for e in res[1].split(',')]
fn = transforms.get(fnStr)
if(fn != None):
mat = fn(elems) @ mat
res = regEx.search(transform)
return mat
def getTransformedSeg(bezierSeg, mat):
pts = []
for pt in bezierSeg:
pt3d = Vector((pt.real, pt.imag, 0))
pt3d = mat @ pt3d
pts.append(complex(pt3d[0], pt3d[1]))
return CubicBezier(*pts)
#format (key, value): [(order_str, seg_cmp_fn), ...]
#(Listed clockwise in the dropdown)
#round-off to int as we don't want to be over-precise with the comparison...
#...der Gleichheitsbedingung wird lediglich visuell geprueft werden :)
def getAlignSegsFn():
return OrderedDict([
('Top-Left', lambda x, y: ((int(x.imag) < int(y.imag)) or \
(int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))),
('Top-Right', lambda x, y: ((int(x.imag) < int(y.imag)) or \
(int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))),
('Right-Top', lambda x, y: ((int(x.real) > int(y.real)) or \
(int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))),
('Right-Bottom', lambda x, y: ((int(x.real) > int(y.real)) or \
(int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))),
('Bottom-Right', lambda x, y: ((int(x.imag) > int(y.imag)) or \
(int(x.imag) == int(y.imag) and int(x.real) > int(y.real)))),
('Bottom-left', lambda x, y: ((int(x.imag) > int(y.imag)) or \
(int(x.imag) == int(y.imag) and int(x.real) < int(y.real)))),
('Left-Bottom', lambda x, y: ((int(x.real) < int(y.real)) or \
(int(x.real) == int(y.real) and int(x.imag) > int(y.imag)))),
('Left-Top', lambda x, y: ((int(x.real) < int(y.real)) or \
(int(x.real) == int(y.real) and int(x.imag) < int(y.imag)))),
])
def getAlignPartsFn():
#Order of the list returned by bbox - Left[0,0]-bottom[0,1]-right[1,0]-top[1,1]
return OrderedDict([
#Sorting in reverse order so that the bigger parts get matched first
('Node Count ', lambda part: -1 * part.getSegCnt()),
('BBox Area', lambda part: -1 * bboxArea(part.bbox())),
('BBox Height', lambda part: -1 * (part.bbox()[1][1] - part.bbox()[0][1])),
('BBox Width', lambda part: -1 * (part.bbox()[1][0] - part.bbox()[0][0])),
('BBox:Top-Left', lambda part: (part.bbox()[0][1], #Top of SVG is bottom of blender
part.bbox()[0][0])),
('BBox:Top-Right', lambda part: (part.bbox()[0][1],
part.bbox()[1][0])),
('BBox:Right-Top', lambda part: (part.bbox()[1][0],
part.bbox()[0][1])),