forked from Shriinivas/blenderbezierutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blenderbezierutils_2.8.py
10974 lines (9064 loc) · 416 KB
/
blenderbezierutils_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
#
#
# Blender add-on with tools to draw and edit Bezier curves along with other utility ops
#
# Supported Blender Version: 2.8x
#
# Copyright (C) 2019 Shrinivas Kulkarni
# License: GPL (https://github.com/Shriinivas/blenderbezierutils/blob/master/LICENSE)
#
import os, bpy, bmesh, bgl, blf, gpu
from bpy.props import BoolProperty, IntProperty, EnumProperty, \
FloatProperty, StringProperty, CollectionProperty, FloatVectorProperty, PointerProperty
from bpy.types import Panel, Operator, WorkSpaceTool, AddonPreferences, Menu
from mathutils import Vector, Matrix, geometry, kdtree
from math import e, pi, log, sin, cos, tan, radians, degrees, sqrt, asin, acos, atan, floor, \
ceil, pow, exp
from bpy_extras.view3d_utils import region_2d_to_vector_3d, region_2d_to_location_3d, \
region_2d_to_origin_3d
from bpy_extras.view3d_utils import location_3d_to_region_2d
from bpy_extras.object_utils import world_to_camera_view
from gpu_extras.batch import batch_for_shader
import random, time, math
from bpy.app.handlers import persistent
from xml.dom import minidom
from shutil import copyfile
bl_info = {
"name": "Bezier Utilities",
"author": "Shrinivas Kulkarni",
"version": (0, 9, 96),
"location": "Properties > Active Tool and Workspace Settings > Bezier Utilities",
"description": "Collection of Bezier curve utility ops",
"category": "Object",
"wiki_url": "https://github.com/Shriinivas/blenderbezierutils/blob/master/README.md",
"blender": (2, 80, 0),
}
DEF_ERR_MARGIN = 0.0001
# Markers for invalid data
LARGE_NO = 9e+9 # Both float and int
LARGE_VECT = Vector((LARGE_NO, LARGE_NO, LARGE_NO))
INVAL = '~'
###################### Common functions ######################
def floatCmpWithMargin(float1, float2, margin = DEF_ERR_MARGIN):
return abs(float1 - float2) < margin
def vectCmpWithMargin(v1, v2, margin = DEF_ERR_MARGIN):
return all(floatCmpWithMargin(v1[i], v2[i], margin) for i in range(0, len(v1)))
def isBezier(bObj):
return bObj.type == 'CURVE' and len(bObj.data.splines) > 0 \
and bObj.data.splines[0].type == 'BEZIER' and \
len(bObj.data.splines[0].bezier_points) > 0
def safeRemoveObj(obj):
try:
collections = obj.users_collection
for c in collections:
c.objects.unlink(obj)
if(obj.data.users == 1):
if(obj.type == 'MESH'):
bpy.data.meshes.remove(obj.data)
elif(obj.type == 'CURVE'):
bpy.data.curves.remove(obj.data)
#else? TODO
bpy.data.objects.remove(obj)
except:
pass
#TODO combine with copyObjAttr
def copyBezierPt(src, target, freeHandles = None, srcMw = Matrix(), invDestMW = Matrix()):
target.handle_left_type = 'FREE'
target.handle_right_type = 'FREE'
target.co = invDestMW @ (srcMw @ src.co)
target.handle_left = invDestMW @ (srcMw @ src.handle_left)
target.handle_right = invDestMW @ (srcMw @ src.handle_right)
if(freeHandles == None or freeHandles[0] == False):
target.handle_left_type = src.handle_left_type
if(freeHandles == None or freeHandles[1] == False):
target.handle_right_type = src.handle_right_type
def createSplineForSeg(curveData, bezierPts):
spline = curveData.splines.new('BEZIER')
spline.bezier_points.add(len(bezierPts)-1)
spline.use_cyclic_u = False
for i, pt in enumerate(bezierPts):
if(i == 0): freeHandles = [False, True]
elif(i == len(bezierPts) - 1): freeHandles = [True, False]
else: freeHandles = None
copyBezierPt(pt, spline.bezier_points[i], freeHandles = freeHandles)
return spline
def createSpline(curveData, srcSpline, excludePtIdxs = {}):
spline = curveData.splines.new('BEZIER')
spline.bezier_points.add(len(srcSpline.bezier_points) - len(excludePtIdxs) - 1)
spline.use_cyclic_u = srcSpline.use_cyclic_u
ptIdx = 0
for i in range(0, len(srcSpline.bezier_points)):
if(i not in excludePtIdxs):
copyBezierPt(srcSpline.bezier_points[i], \
spline.bezier_points[ptIdx], freeHandles = None)
ptIdx += 1
return spline
def createSkeletalCurve(obj, collections):
objCopy = obj.copy()
objCopy.name = obj.name
dataCopy = obj.data.copy()
dataCopy.splines.clear()
objCopy.data = dataCopy
for coll in collections:
coll.objects.link(objCopy)
return objCopy
def createObjFromPts(curvePts, dimensions = '3D', collection = None, \
closed = False, calcHdlTypes = True):
data = bpy.data.curves.new('BezierCurve', 'CURVE')
data.dimensions = dimensions
obj = bpy.data.objects.new('BezierCurve', data)
# ~ collection = context.collection
if(collection == None):
collection = bpy.context.scene.collection
collection.objects.link(obj)
# ~ obj.location = context.scene.cursor.location
# ~ depsgraph = context.evaluated_depsgraph_get()
# ~ depsgraph.update()
# ~ invM = obj.matrix_world.inverted_safe()
spline = data.splines.new('BEZIER')
spline.use_cyclic_u = False
if(vectCmpWithMargin(curvePts[0][1], curvePts[-1][1])):
curvePts[0][0] = curvePts[-1][0]
spline.use_cyclic_u = True
curvePts.pop()
if(closed): spline.use_cyclic_u = True
spline.bezier_points.add(len(curvePts) - 1)
prevPt = None
for i, pt in enumerate(curvePts):
currPt = spline.bezier_points[i]
currPt.co = pt[1]
currPt.handle_right = pt[2]
if(not calcHdlTypes and len(pt) > 3):
currPt.handle_right_type = pt[3]
currPt.handle_left_type = pt[4]
elif(prevPt != None and prevPt.handle_right == prevPt.co \
and pt[0] == pt[1] and currPt.co != prevPt.co): # straight line
if(prevPt.handle_left_type != 'VECTOR'):
prevPt.handle_left_type = 'FREE'
prevPt.handle_right_type = 'VECTOR'
currPt.handle_right_type = 'FREE'
currPt.handle_left_type = 'VECTOR'
else:
currPt.handle_left_type = 'FREE'
currPt.handle_right_type = 'FREE'
currPt.handle_left = pt[0]
ldiffV = (pt[1] - pt[0])
rdiffV = (pt[2] - pt[1])
if(vectCmpWithMargin(ldiffV, rdiffV) and \
not floatCmpWithMargin(ldiffV.length, 0)):
currPt.handle_left_type = 'ALIGNED'
currPt.handle_right_type = 'ALIGNED'
prevPt = currPt
bpts = spline.bezier_points
if(spline.use_cyclic_u and vectCmpWithMargin(bpts[-1].handle_right, bpts[-1].co) \
and vectCmpWithMargin(bpts[0].handle_left, bpts[0].co)):
if(bpts[-1].handle_left_type != 'VECTOR'):
bpts[-1].handle_left_type = 'FREE'
bpts[-1].handle_right_type = 'VECTOR'
if(bpts[0].handle_right_type != 'VECTOR'):
bpts[0].handle_right_type = 'FREE'
bpts[0].handle_left_type = 'VECTOR'
return obj
def removeShapeKeys(obj):
if(obj.data.shape_keys == None):
return
keyblocks = reversed(obj.data.shape_keys.key_blocks)
for sk in keyblocks:
obj.shape_key_remove(sk)
def getShapeKeyInfo(obj):
keyData = []
keyNames = []
if(obj.data.shape_keys != None):
keyblocks = obj.data.shape_keys.key_blocks
for key in keyblocks:
keyData.append([[d.handle_left.copy(), d.co.copy(), d.handle_right.copy()] \
for d in key.data])
keyNames.append(key.name)
return keyNames, keyData
def updateShapeKeyData(obj, keyData, keyNames, startIdx, cnt = None, add = False):
if(obj.data.shape_keys == None and not add):
return
currIdx = obj.active_shape_key_index
if(not add): removeShapeKeys(obj)
if(cnt == None): cnt = len(keyData[0])
for i, name in enumerate(keyNames):
key = obj.shape_key_add(name = name)
for j in range(0, cnt):
keyIdx = j + startIdx
key.data[j].handle_left = keyData[i][keyIdx][0].copy()
key.data[j].co = keyData[i][keyIdx][1].copy()
key.data[j].handle_right = keyData[i][keyIdx][2].copy()
obj.active_shape_key_index = currIdx
#TODO: Fix this hack if possible
def copyObjAttr(src, dest, invDestMW = Matrix(), mw = Matrix()):
for att in dir(src):
try:
if(att not in ['co', 'handle_left', 'handle_right', \
'handle_left_type', 'handle_right_type']):
setattr(dest, att, getattr(src, att))
except Exception as e:
pass
try:
lt = src.handle_left_type
rt = src.handle_right_type
dest.handle_left_type = 'FREE'
dest.handle_right_type = 'FREE'
dest.co = invDestMW @ (mw @ src.co)
dest.handle_left = invDestMW @ (mw @ src.handle_left)
dest.handle_right = invDestMW @ (mw @ src.handle_right)
dest.handle_left_type = lt
dest.handle_right_type = rt
pass
except Exception as e:
pass
def getLastSegIdx(obj, splineIdx):
spline = obj.data.splines[splineIdx]
ptCnt = len(spline.bezier_points)
return ptCnt - 1 if(spline.use_cyclic_u) else ptCnt - 2
def addLastSeg(spline):
if(spline.use_cyclic_u):
lt0 = spline.bezier_points[0].handle_left_type
rt0 = spline.bezier_points[0].handle_right_type
pt = spline.bezier_points[0]
pt.handle_left_type = 'FREE'
pt.handle_right_type = 'FREE'
spline.use_cyclic_u = False
spline.bezier_points.add(1)
copyObjAttr(spline.bezier_points[0], spline.bezier_points[-1])
spline.bezier_points[0].handle_left_type = lt0
spline.bezier_points[-1].handle_right_type = rt0
def moveSplineStart(obj, splineIdx, idx):
pts = obj.data.splines[splineIdx].bezier_points
cnt = len(pts)
ptCopy = [[p.co.copy(), p.handle_right.copy(), \
p.handle_left.copy(), p.handle_right_type, \
p.handle_left_type] for p in pts]
for i, pt in enumerate(pts):
srcIdx = (idx + i) % cnt
p = ptCopy[srcIdx]
pt.handle_left_type = 'FREE'
pt.handle_right_type = 'FREE'
pt.co = p[0]
pt.handle_right = p[1]
pt.handle_left = p[2]
pt.handle_right_type = p[3]
pt.handle_left_type = p[4]
def joinCurves(curves):
obj = curves[0]
invMW = obj.matrix_world.inverted_safe()
for curve in curves[1:]:
mw = curve.matrix_world
for spline in curve.data.splines:
newSpline = obj.data.splines.new('BEZIER')
copyObjAttr(spline, newSpline)
newSpline.bezier_points.add(len(spline.bezier_points)-1)
for i, pt in enumerate(spline.bezier_points):
copyObjAttr(pt, newSpline.bezier_points[i], \
invDestMW = invMW, mw = mw)
safeRemoveObj(curve)
return obj
def getObjBBoxCenter(obj):
bbox = obj.bound_box
return obj.matrix_world @ Vector(((bbox[0][0] + bbox[4][0]) / 2, \
(bbox[0][1] + bbox[3][1]) / 2, (bbox[0][2] + bbox[1][2]) / 2))
# Only mesh and Bezier curve
def shiftOrigin(obj, origin):
oLoc = obj.location.copy()
mw = obj.matrix_world
invMw = mw.inverted_safe()
if(obj.type == 'MESH'):
for vert in obj.data.vertices:
vert.co += invMw @ oLoc - invMw @ origin
elif(obj.type == 'CURVE'):
for s in obj.data.splines:
bpts = s.bezier_points
for bpt in bpts:
lht = bpt.handle_left_type
rht = bpt.handle_right_type
bpt.handle_left_type = 'FREE'
bpt.handle_right_type = 'FREE'
bpt.co += invMw @ oLoc - invMw @ origin
bpt.handle_left += invMw @ oLoc - invMw @ origin
bpt.handle_right += invMw @ oLoc - invMw @ origin
bpt.handle_left_type = lht
bpt.handle_right_type = rht
obj.location = origin
# Only mesh and Bezier curve; depsgraph not updated
def shiftMatrixWorld(obj, mw):
invMw = mw.inverted_safe()
omw = obj.matrix_world
if(obj.type == 'MESH'):
for vert in obj.data.vertices:
vert.co = invMw @ (omw @ vert.co)
elif(obj.type == 'CURVE'):
for s in obj.data.splines:
bpts = s.bezier_points
for bpt in bpts:
lht = bpt.handle_left_type
rht = bpt.handle_right_type
bpt.handle_left_type = 'FREE'
bpt.handle_right_type = 'FREE'
bpt.co = invMw @ (omw @ bpt.co)
bpt.handle_left = invMw @ (omw @ bpt.handle_left)
bpt.handle_right = invMw @ (omw @ bpt.handle_right)
bpt.handle_left_type = lht
bpt.handle_right_type = rht
obj.matrix_world = mw
# Also shifts origin; depsgraph not updated
def alignToNormal(curve):
depsgraph = bpy.context.evaluated_depsgraph_get()
depsgraph.update()
mw = curve.matrix_world.copy()
normals = []
for spline in curve.data.splines:
bpts = spline.bezier_points
bptCnt = len(bpts)
if(bptCnt > 2):
normals.append(geometry.normal(mw @ bpts[i].co for i in range(bptCnt)))
cnt = len(normals)
if(cnt > 0):
normal = Vector([sum(normals[i][j] for i in range(cnt)) \
for j in range(3)]) / cnt
quatMat = normal.to_track_quat('Z', 'X').to_matrix().to_4x4()
shiftMatrixWorld(curve, quatMat)
def copyProperties(srcObj, destCurve):
if(srcObj == None or destCurve == None):
return
destData = destCurve.data
srcData = srcObj.data
# If object is bezier curve copy curve properties and material
if(isBezier(srcObj)):
# Copying just a few attributes
destData.dimensions = srcData.dimensions
destData.resolution_u = srcData.resolution_u
destData.render_resolution_u = srcData.render_resolution_u
destData.fill_mode = srcData.fill_mode
destData.use_fill_deform = srcData.use_fill_deform
destData.use_radius = srcData.use_radius
destData.use_stretch = srcData.use_stretch
destData.use_deform_bounds = srcData.use_deform_bounds
destData.twist_smooth = srcData.twist_smooth
destData.twist_mode = srcData.twist_mode
destData.offset = srcData.offset
destData.extrude = srcData.extrude
destData.bevel_depth = srcData.bevel_depth
destData.bevel_resolution = srcData.bevel_resolution
destData.bevel_object = srcData.bevel_object
destData.taper_object = srcData.taper_object
destData.use_fill_caps = srcData.use_fill_caps
if(hasattr(srcData, 'materials') and len(srcData.materials) > 0):
mat = srcData.materials[srcObj.active_material_index]
if(len(destData.materials) == 0 or mat.name not in destData.materials):
destData.materials.append(mat)
activeIdx = -1 #Last
else:
activeIdx = destData.materials.find(mat.name)
destCurve.active_material_index = activeIdx
def reverseCurve(curve):
cp = curve.data.copy()
curve.data.splines.clear()
for s in reversed(cp.splines):
ns = curve.data.splines.new('BEZIER')
copyObjAttr(s, ns)
ns.bezier_points.add(len(s.bezier_points) - 1)
for i, p in enumerate(reversed(s.bezier_points)):
copyObjAttr(p, ns.bezier_points[i])
ns.bezier_points[i].handle_left_type = 'FREE'
ns.bezier_points[i].handle_right_type = 'FREE'
ns.bezier_points[i].handle_left = p.handle_right
ns.bezier_points[i].handle_right = p.handle_left
ns.bezier_points[i].handle_left_type = p.handle_right_type
ns.bezier_points[i].handle_right_type = p.handle_left_type
bpy.data.curves.remove(cp)
# Insert spline at location insertIdx, duplicated from existing spline at
# location srcSplineIdx and remove points with indices in removePtIdxs from new spline
def insertSpline(obj, srcSplineIdx, insertIdx, removePtIdxs):
srcSpline = obj.data.splines[srcSplineIdx]
# Appended at end
createSpline(obj.data, srcSpline, removePtIdxs)
splineCnt = len(obj.data.splines)
nextIdx = insertIdx
for idx in range(nextIdx, splineCnt - 1):
srcSpline = obj.data.splines[nextIdx]
createSpline(obj.data, srcSpline)
obj.data.splines.remove(srcSpline)
def removeBezierPts(obj, splineIdx, removePtIdxs):
oldSpline = obj.data.splines[splineIdx]
bpts = oldSpline.bezier_points
if(min(removePtIdxs) >= len(bpts)):
return
if(len(set(range(len(bpts))) - set(removePtIdxs)) == 0) :
obj.data.splines.remove(oldSpline)
if(len(obj.data.splines) == 0):
safeRemoveObj(obj)
return
insertSpline(obj, splineIdx, splineIdx, removePtIdxs)
obj.data.splines.remove(obj.data.splines[splineIdx + 1])
# Returns a tuple with first value indicating change in spline index (-1, 0, 1)
# and second indicating shift in seg index (negative) due to removal
def removeBezierSeg(obj, splineIdx, segIdx):
nextIdx = getAdjIdx(obj, splineIdx, segIdx)
if(nextIdx == None): return
spline = obj.data.splines[splineIdx]
bpts = spline.bezier_points
ptCnt = len(bpts)
lastSegIdx = getLastSegIdx(obj, splineIdx)
splineIdxIncr = 0
segIdxIncr = 0
if(ptCnt <= 2):
removeBezierPts(obj, splineIdx, {segIdx, nextIdx})
# Spline removed by above call
splineIdxIncr = -1
else:
bpt = obj.data.splines[splineIdx].bezier_points[segIdx]
bpt.handle_right_type = 'FREE'
bpt.handle_left_type = 'FREE'
nextIdx = getAdjIdx(obj, splineIdx, segIdx)
bpt = obj.data.splines[splineIdx].bezier_points[nextIdx]
bpt.handle_right_type = 'FREE'
bpt.handle_left_type = 'FREE'
if(spline.use_cyclic_u):
spline.use_cyclic_u = False
if(segIdx != lastSegIdx):
moveSplineStart(obj, splineIdx, getAdjIdx(obj, splineIdx, segIdx))
segIdxIncr = - (segIdx + 1)
else:
if(segIdx == lastSegIdx):
removeBezierPts(obj, splineIdx, {lastSegIdx + 1})
elif(segIdx == 0):
removeBezierPts(obj, splineIdx, {0})
segIdxIncr = -1
else:
insertSpline(obj, splineIdx, splineIdx, set(range(segIdx + 1, ptCnt)))
removeBezierPts(obj, splineIdx + 1, range(segIdx + 1))
splineIdxIncr = 1
segIdxIncr = - (segIdx + 1)
return splineIdxIncr, segIdxIncr
def insertBezierPts(obj, splineIdx, startIdx, cos, handleType, margin = DEF_ERR_MARGIN):
spline = obj.data.splines[splineIdx]
bpts = spline.bezier_points
nextIdx = getAdjIdx(obj, splineIdx, startIdx)
firstPt = bpts[startIdx]
nextPt = bpts[nextIdx]
if(firstPt.handle_right_type == 'AUTO'):
firstPt.handle_left_type = 'ALIGNED'
firstPt.handle_right_type = 'ALIGNED'
if(nextPt.handle_left_type == 'AUTO'):
nextPt.handle_left_type = 'ALIGNED'
nextPt.handle_right_type = 'ALIGNED'
fhdl = firstPt.handle_right_type
nhdl = nextPt.handle_left_type
firstPt.handle_right_type = 'FREE'
nextPt.handle_left_type = 'FREE'
ptCnt = len(bpts)
addCnt = len(cos)
bpts.add(addCnt)
nextIdx = startIdx + 1
for i in range(0, (ptCnt - nextIdx)):
idx = ptCnt - i - 1# reversed
offsetIdx = idx + addCnt
copyObjAttr(bpts[idx], bpts[offsetIdx])
endIdx = getAdjIdx(obj, splineIdx, nextIdx, addCnt)
firstPt = bpts[startIdx]
nextPt = bpts[endIdx]
prevPt = firstPt
for i, pt in enumerate(bpts[nextIdx:nextIdx + addCnt]):
pt.handle_left_type = 'FREE'
pt.handle_right_type = 'FREE'
co = cos[i]
seg = [prevPt.co, prevPt.handle_right, nextPt.handle_left, nextPt.co]
t = getTForPt(seg, co, margin)
ctrlPts0 = getPartialSeg(seg, 0, t)
ctrlPts1 = getPartialSeg(seg, t, 1)
segPt = [ctrlPts0[2], ctrlPts1[0], ctrlPts1[1]]
prevRight = ctrlPts0[1]
nextLeft = ctrlPts1[2]
pt.handle_left = segPt[0]
pt.co = segPt[1]
pt.handle_right = segPt[2]
pt.handle_left_type = handleType
pt.handle_right_type = handleType
prevPt.handle_right = prevRight
prevPt = pt
nextPt.handle_left = nextLeft
firstPt.handle_right_type = fhdl
nextPt.handle_left_type = nhdl
# https://devtalk.blender.org/t/get-hex-gamma-corrected-color/2422/2
def toHexStr(rgba):
ch = []
for c in rgba[:3]:
if c < 0.0031308:
cc = 0.0 if c < 0.0 else c * 12.92
else:
cc = 1.055 * pow(c, 1.0 / 2.4) - 0.055
ch.append(hex(max(min(int(cc * 255 + 0.5), 255), 0))[2:])
return ''.join(ch), str(rgba[-1])
# Change position of bezier points according to new matrix_world
def changeMW(obj, newMW):
invMW = newMW.inverted_safe()
for spline in obj.data.splines:
for pt in spline.bezier_points:
pt.co = invMW @ (obj.mw @ pt.co)
pt.handle_left = invMW @ (obj.mw @ pt.handle_left)
pt.handle_right = invMW @ (obj.mw @ pt.handle_right)
obj.matrix_world = newMW
# Return map in the form of objName->[splineIdx, [startPt, endPt]]
# Remove the invalid keys (if any) from it.
def updateCurveEndPtMap(endPtMap, addObjNames = None, removeObjNames = None):
invalOs = set()
if(addObjNames == None):
addObjNames = [o.name for o in bpy.context.scene.objects]
invalOs = endPtMap.keys() - set(addObjNames) # In case of redo
if(removeObjNames != None):
invalOs.union(set(removeObjNames))
for o in invalOs:
del endPtMap[o]
for objName in addObjNames:
obj = bpy.context.scene.objects.get(objName)
if(obj != None and isBezier(obj) and obj.visible_get()):
endPtMap[objName] = []
mw = obj.matrix_world
for i, s in enumerate(obj.data.splines):
pts = [mw @ pt.co for pt in s.bezier_points]
endPtMap[objName].append([i, pts])
elif(endPtMap.get(objName) != None):
del endPtMap[objName]
return endPtMap
#Round to logarithmic scale .1, 0, 10, 100 etc.
#(47.538, -1) -> 47.5; (47.538, 0) -> 48.0; (47.538, 1) -> 50.0; (47.538, 2) -> 0,
# TODO: Rework after grid subdiv is enabled (in a version later than 2.8)
def roundedVect(space3d, vect, rounding, axes):
rounding += 1
subdiv = getGridSubdiv(space3d)
# TODO: Separate logic for 1
if(subdiv == 1): subdiv = 10
fact = ((subdiv ** rounding) / subdiv) / getUnitScale()
retVect = vect.copy()
# ~ Vector([round(vect[i] / fact) * fact for i in axes])
for i in axes: retVect[i] = round(vect[i] / fact) * fact
return retVect
###################### Screen functions ######################
def getGridSubdiv(space3d):
return space3d.overlay.grid_subdivisions
def getUnit():
return bpy.context.scene.unit_settings.length_unit
def getUnitSystem():
return bpy.context.scene.unit_settings.system
def getUnitScale():
fact = 3.28084 if(getUnitSystem() == 'IMPERIAL') else 1
return fact * bpy.context.scene.unit_settings.scale_length
def get3dLoc(region, rv3d, xy, vec = None):
if(vec == None):
vec = region_2d_to_vector_3d(region, rv3d, xy)
return region_2d_to_location_3d(region, rv3d, xy, vec)
# TODO: Rework after grid subdiv is enabled (in a version later than 2.8)
def getViewDistRounding(space3d, rv3d):
viewDist = rv3d.view_distance * getUnitScale()
gridDiv = getGridSubdiv(space3d)
subFact = 1
# TODO: Separate logic for 1
if(gridDiv == 1): gridDiv = 10
elif(gridDiv == 2): subFact = 5
elif(viewDist < 0.5): subFact = 2
return int(log(viewDist, gridDiv)) - subFact
# Return axis-indices (x:0, y:1, z:2) of plane with closest orientation
# to view
def getClosestPlaneToView(rv3d):
viewmat = rv3d.view_matrix
trans, quat, scale = viewmat.decompose()
tm = quat.to_matrix().to_4x4()
viewnormal = tm.inverted() @ Vector((0, 0, 1))
xynormal = [Vector((0, 0, 1)), [0, 1]]
yznormal = [Vector((1, 0, 0)), [1, 2]]
xznormal = [Vector((0, 1, 0)), [0, 2]]
normals = [xynormal, yznormal, xznormal]
minAngle = pi
minIdx = None
for idx, normal in enumerate(normals):
rotDiff = viewnormal.rotation_difference(normal[0]).angle
if(rotDiff > pi / 2):
rotDiff = pi - rotDiff
if(rotDiff < minAngle):
minIdx = idx
minAngle = rotDiff
return normals[minIdx][1]
def getCoordFromLoc(region, rv3d, loc):
coord = location_3d_to_region_2d(region, rv3d, loc)
# return a unlocatable pt if None to avoid errors
return coord if(coord != None) else Vector((9000, 9000))
# To be called only from 3d view
def getCurrAreaRegion(context):
a, r = [(a, r) for a in bpy.context.screen.areas if a.type == 'VIEW_3D' \
for r in a.regions if(r == context.region)][0]
return a, r
def isOutside(context, event, exclInRgns = True):
x = event.mouse_region_x
y = event.mouse_region_y
region = context.region
if(x < 0 or x > region.width or y < 0 or y > region.height):
return True
elif(not exclInRgns):
return False
area, r = getCurrAreaRegion(context)
for r in area.regions:
if(r == region):
continue
xR = r.x - region.x
yR = r.y - region.y
if(x >= xR and y >= yR and x <= (xR + r.width) and y <= (yR + r.height)):
return True
return False
def getPtProjOnPlane(region, rv3d, xy, p1, p2, p3, p4 = None):
vec = region_2d_to_vector_3d(region, rv3d, xy)
orig = region_2d_to_origin_3d(region, rv3d, xy)
pt = geometry.intersect_ray_tri(p1, p2, p3, vec, orig, False)#p4 != None)
# ~ if(not pt and p4):
# ~ pt = geometry.intersect_ray_tri(p2, p4, p3, vec, orig, True)
return pt
# find the location on 3d line p1-p2 if xy is already on 2d projection (in rv3d) of p1-p2
def getPtProjOnLine(region, rv3d, xy, p1, p2):
# Just find a non-linear point (TODO: simpler way)
pd1 = p2 - p1
pd2 = Vector(sorted(pd1, key=lambda x: abs(x), reverse = True))
maxIdx0 = [i for i in range(3) if abs(pd1[i]) == abs(pd2[0])][0]
maxIdx1 = [i for i in range(3) if abs(pd1[i]) == abs(pd2[1])][0]
pd = Vector()
pd[maxIdx0] = -pd2[1]
pd[maxIdx1] = pd2[0]
p3 = p2 + pd
# Raycast from 2d point onto the plane
return getPtProjOnPlane(region, rv3d, xy[:2], p1, p2, p3)
def getLineTransMatrices(pt0, pt1):
diffV = (pt1 - pt0)
invTm = diffV.to_track_quat('X', 'Z').to_matrix().to_4x4()
tm = invTm.inverted_safe()
return tm, invTm
def getWindowRegionIdx(area, regionIdx): # For finding quad view index
idx = 0
for j, r in enumerate(area.regions):
if(j == regionIdx): return idx
if(r.type == 'WINDOW'): idx += 1
return None
def getAreaRegionIdxs(xy, exclInRgns = True):
x, y = xy
areas = [a for a in bpy.context.screen.areas]
idxs = None
for i, a in enumerate(areas):
if(a.type != 'VIEW_3D'): continue
regions = [r for r in a.regions]
for j, r in enumerate(regions):
if(x > r.x and x < r.x + r.width and y > r.y and y < r.y + r.height):
if(r.type == 'WINDOW'):
if(not exclInRgns):
return [i, j]
idxs = [i, j]
elif(exclInRgns):
return None
return idxs
# ~ def getMinViewDistRegion():
# ~ viewDist = 9e+99
# ~ rv3d = None
# ~ area = None
# ~ region = None
# ~ areas = [a for a in bpy.context.screen.areas if(a.type == 'VIEW_3D')]
# ~ for a in areas:
# ~ regions = [r for r in a.regions if r.type == 'WINDOW']
# ~ if(len(a.spaces[0].region_quadviews) > 0):
# ~ for i, r in enumerate(a.spaces[0].region_quadviews):
# ~ if(r.view_distance < viewDist):
# ~ viewDist = r.view_distance
# ~ rv3d = r
# ~ area = a
# ~ region = regions[i]
# ~ else:
# ~ r = a.spaces[0].region_3d
# ~ if(r.view_distance < viewDist):
# ~ viewDist = r.view_distance
# ~ rv3d = r
# ~ area = a
# ~ region = regions[0]
# ~ return a, region, rv3d#, viewDist
def getAllAreaRegions():
info = []
areas = []
i = 0
areas = [a for a in bpy.context.screen.areas if(a.type == 'VIEW_3D')]
# bpy.context.screen doesn't work in case of Add-on Config window
while(len(areas) == 0 and i < len(bpy.data.screens)):
areas = [a for a in bpy.data.screens[i].areas if(a.type == 'VIEW_3D')]
i += 1
for a in areas:
regions = [r for r in a.regions if r.type == 'WINDOW']
if(len(a.spaces[0].region_quadviews) > 0):
for i, r in enumerate(a.spaces[0].region_quadviews):
info.append([a, regions[i], r])
else:
r = a.spaces[0].region_3d
info.append([a, regions[0], r])
return info
def getResetBatch(shader, btype): # "LINES" or "POINTS"
return batch_for_shader(shader, btype, {"pos": [], "color": []})
# From python template
def getFaceUnderMouse(obj, region, rv3d, xy, maxFaceCnt):
if(obj == None or obj.type != 'MESH' \
or len(obj.data.polygons) > maxFaceCnt):
return None, None, None
viewVect = region_2d_to_vector_3d(region, rv3d, xy)
rayOrig = region_2d_to_origin_3d(region, rv3d, xy)
mw = obj.matrix_world
invMw = mw.inverted_safe()
rayTarget = rayOrig + viewVect
rayOrigObj = invMw @ rayOrig
rayTargetObj = invMw @ rayTarget
rayDirObj = rayTargetObj - rayOrigObj
success, location, normal, faceIdx = obj.ray_cast(rayOrigObj, rayDirObj)
if(success):
return mw @ location, normal, faceIdx
else:
return None, None, None
def getSnappableObjs(region, rv3d, xy):
objs = bpy.context.selected_objects
if(bpy.context.object != None):
objs.append(bpy.context.object)
return [o for o in objs if(o.type == 'MESH' and len(o.modifiers) == 0 and \
isPtIn2dBBox(o, region, rv3d, xy))]
# precise can be pretty expensive with large vert count
def get2dBBox(obj, region, rv3d, precise = False):
mw = obj.matrix_world
if(precise):
co2ds = [getCoordFromLoc(region, rv3d, mw @ Vector(v.co)) \
for v in obj.data.vertices]
else:
co2ds = [getCoordFromLoc(region, rv3d, mw @ Vector(b)) for b in obj.bound_box]
minX = min(c[0] for c in co2ds)
maxX = max(c[0] for c in co2ds)
minY = min(c[1] for c in co2ds)
maxY = max(c[1] for c in co2ds)
return minX, minY, maxX, maxY
def isPtIn2dBBox(obj, region, rv3d, xy, extendBy = 0, precise = False):
minX, minY, maxX, maxY = get2dBBox(obj, region, rv3d, precise)
if(xy[0] > (minX - extendBy) and xy[0] < (maxX + extendBy) \
and xy[1] > (minY - extendBy) and xy[1] < (maxY + extendBy)):
return True
else: return False
# ~ def isLocIn2dBBox(obj, region, rv3d, loc, extendBy = 0, precise = False):
# ~ xy = getCoordFromLoc(region, rv3d, loc)
# ~ return isPtIn2dBBox(obj, region, rv3d, xy, extendBy, precise)
def getClosestEdgeLoc2d(obj, region, rv3d, xy, faceIdx = None):
mw = obj.matrix_world
minDist = LARGE_NO
closestLoc = None
pt = Vector(xy).to_3d()
edgeWSCos = None
edgeIdx = None
closestIntersect = None
vertPairs = obj.data.polygons[faceIdx].edge_keys if faceIdx != None \
else [e.vertices for e in obj.data.edges]
for i, vertPair in enumerate(vertPairs):
co0 = mw @ obj.data.vertices[vertPair[0]].co
co1 = mw @ obj.data.vertices[vertPair[1]].co
pt0 = getCoordFromLoc(region, rv3d, co0).to_3d()
pt1 = getCoordFromLoc(region, rv3d, co1).to_3d()
intersect, percDist = geometry.intersect_point_line(pt, pt0, pt1)
if(percDist < 0):
intersect = pt0
percDist = 0
elif(percDist > 1):
intersect = pt1
percDist = 1
dist = (intersect - pt).length
if(dist < minDist):
minDist = dist
closestIntersect = intersect
edgeWSCos = [co0, co1]
edgeIdx = i
if(edgeWSCos != None):
closestLoc = getPtProjOnLine(region, rv3d, closestIntersect, \
edgeWSCos[0], edgeWSCos[1])
return edgeIdx, edgeWSCos, closestLoc, minDist
# TODO: Fix the signature
def getSelFaceLoc(region, rv3d, xy, maxFaceCnt, objs = None, checkEdge = False):
if(objs == None): objs = getSnappableObjs(region, rv3d, xy)
if(len(objs) > maxFaceCnt): return None, None, None, None
for obj in objs:
loc, normal, faceIdx = getFaceUnderMouse(obj, region, rv3d, xy, maxFaceCnt)
if(loc != None):
if(checkEdge):
edgeIdx, edgeWSCos, closestLoc, minDist = \
getClosestEdgeLoc2d(obj, region, rv3d, xy, faceIdx)
if(closestLoc != None and minDist < FTProps.snapDist):
return obj, closestLoc, normal, faceIdx
return obj, loc, normal, faceIdx
return None, None, None, None
# TODO: Fix the signature
# ~ def getSelEdgeLoc(region, rv3d, xy, maxFaceCnt, objs = None):
# ~ if(objs == None): objs = getSnappableObjs()
# ~ if(len(objs) > maxFaceCnt): return None, None, None, None
# ~ minDist = LARGE_NO
# ~ closestLoc = None
# ~ closestEdgeIdx = None
# ~ closestObj = None
# ~ objCnt = 0
# ~ objs = bpy.context.selected_objects
# ~ if(bpy.context.object != None): objs.append(bpy.context.object)
# ~ for obj in objs:
# ~ edgeIdx, edgeWSCos, loc, dist = \
# ~ getClosestEdgeLoc2d(obj, region, rv3d, xy)
# ~ if(dist < minDist):
# ~ minDist = dist
# ~ closestLoc = loc
# ~ closestEdgeIdx = edgeIdx
# ~ closestObj = obj
# ~ return closestObj, closestLoc, minDist, closestEdgeIdx
###################### Op Specific functions ######################
def closeSplines(curve, htype = None):
for spline in curve.data.splines:
if(htype != None):
spline.bezier_points[0].handle_left_type = htype
spline.bezier_points[-1].handle_right_type = htype
spline.use_cyclic_u = True
# TODO: Update shapekey (not working due to moving of start pt in cyclic)
def splitCurveSelPts(selPtMap, newColl = True):
changeCnt = 0
newObjs = []
if(len(selPtMap) == 0): return newObjs, changeCnt
for obj in selPtMap.keys():
splinePtMap = selPtMap.get(obj)
if((len(obj.data.splines) == 1 and \
len(obj.data.splines[0].bezier_points) <= 2 and \
not obj.data.splines[0].use_cyclic_u) or len(splinePtMap) == 0):
continue
keyNames, keyData = getShapeKeyInfo(obj)
collections = obj.users_collection
if(newColl):
objGrp = bpy.data.collections.new(obj.name)
parentColls = [objGrp]
else:
parentColls = collections
splineCnt = len(obj.data.splines)
endSplineIdx = splineCnt- 1
if(endSplineIdx not in splinePtMap.keys()):
splinePtMap[endSplineIdx] = \