-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path__init__.py
More file actions
2124 lines (1618 loc) · 69.1 KB
/
Copy path__init__.py
File metadata and controls
2124 lines (1618 loc) · 69.1 KB
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
'''
Created on Mar 7, 2015
@author: Patrick
'''
bl_info = {
"name": "Curvature Features",
"author": "Patrick Moore",
"version": (1, 0),
"blender": (2, 74, 0),
"location": "",
"description": "Curvature and Harmonic utilities for analsis and segmentation",
"warning": "",
"wiki_url": "",
"category": "Object"}
import math
import random
import time
from collections import Counter
import numpy as np
from scipy import sparse
from scipy.sparse import linalg
import bpy
import bgl
import blf
import bmesh
from mathutils import Matrix, Vector
from bpy_extras import view3d_utils
from bpy.props import BoolProperty, FloatProperty, IntProperty
from bpy_extras.view3d_utils import location_3d_to_region_2d, region_2d_to_vector_3d, region_2d_to_location_3d, region_2d_to_origin_3d
#from retopoflow.polystrips_utilities import cubic_bezier_fit_points, cubic_bezier_blend_t
def vector_average(l_vecs):
v_mean = Vector((0,0,0))
for vec in l_vecs:
v_mean += vec
v_mean *= 1/len(l_vecs)
return v_mean
def bbox(bme_verts):
'''
takes a lsit of BMverts ora list of vectors
'''
if hasattr(bme_verts[0], 'co'):
verts = [v.co for v in bme_verts]
else:
verts = [v for v in bme_verts]
xs = [v[0] for v in verts]
ys = [v[1] for v in verts]
zs = [v[2] for v in verts]
return (min(xs), max(xs), min(ys), max(ys), min(zs), max(zs))
def vert_neighbors(bmv):
'''
todo, locations, indices or actual verts.
reverse?
'''
verts = [ed.other_vert(bmv) for ed in bmv.link_edges]
return verts
def closest_point(pt, locs):
ds = [(loc - pt).length for loc in locs]
best = ds.index(min(ds))
return (best, locs[best], ds[best])
def closest_point_in_list(pt, locs):
'''
the test point is included in the list
'''
ds = [(loc - pt).length for loc in locs if pt != loc]
best = ds.index(min(ds))
return (best, locs[best], ds[best])
def points_within_radius(pt, locs, R):
'''
the test point is included in the list
'''
dist_inds = {}
ds = []
for i, loc in enumerate(locs):
if pt != loc:
D = (loc -pt).length
dist_inds[D] = i
if D < R:
ds.append(D)
ds.sort()
inds = [dist_inds[D] for D in ds]
vs = [locs[i] for i in inds]
return (ds, inds, vs)
def calculate_plane(locs, itermax = 500, debug = False):
'''
args:
vertex_locs - a list of type Vector
return:
normal of best fit plane
'''
if debug:
start = time.time()
n_verts = len(locs)
# calculating the center of masss
com = Vector()
for loc in locs:
com += loc
com /= len(locs)
x, y, z = com
# creating the covariance matrix
mat = Matrix(((0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
))
for loc in locs:
mat[0][0] += (loc[0]-x)**2
mat[1][0] += (loc[0]-x)*(loc[1]-y)
mat[2][0] += (loc[0]-x)*(loc[2]-z)
mat[0][1] += (loc[1]-y)*(loc[0]-x)
mat[1][1] += (loc[1]-y)**2
mat[2][1] += (loc[1]-y)*(loc[2]-z)
mat[0][2] += (loc[2]-z)*(loc[0]-x)
mat[1][2] += (loc[2]-z)*(loc[1]-y)
mat[2][2] += (loc[2]-z)**2
# calculating the normal to the plane
normal = False
try:
mat.invert()
except:
if sum(mat[0]) == 0.0:
normal = Vector((1.0, 0.0, 0.0))
elif sum(mat[1]) == 0.0:
normal = Vector((0.0, 1.0, 0.0))
elif sum(mat[2]) == 0.0:
normal = Vector((0.0, 0.0, 1.0))
if not normal:
# warning! this is different from .normalize()
iters = 0
vec = Vector((1.0, 1.0, 1.0))
vec2 = (mat * vec)/(mat * vec).length
while vec != vec2 and iters < itermax:
iters+=1
vec = vec2
vec2 = mat * vec
if vec2.length != 0:
vec2 /= vec2.length
if vec2.length == 0:
vec2 = Vector((1.0, 1.0, 1.0))
normal = vec2
if debug:
if iters == itermax:
print("looks like we maxed out our iterations")
print("found plane normal for %d verts in %f seconds" % (n_verts, time.time() - start))
return com, normal
def concave(bmvert, lam):
'''
bmverts - BMVert in a BMesh
lam(bda) - small float value 1e-4 to 1e-6 seems to work well.
can be small negative value too.
this fn has been verified
'''
if len(bmvert.link_edges) == 0:
return 0
vks = [v.co for v in vert_neighbors(bmvert)]
vavg = vector_average(vks)
vdiff = vavg - bmvert.co
vdiff.normalize()
no = bmvert.normal
if vdiff.dot(no) > lam:
#bmvert.select = True #used for ferification
return 1
else:
return 0
def gammaij(bmedge, conc_id, fs, fl):
'''
bmedge - the bemseh edge
conc_id - the flag for id data stored on bmesh verst
This fn is unsure because of ambiguity with fs and fl
'''
vi = bmedge.verts[0]
vj = bmedge.verts[1]
if vi[conc_id] == 1 or vj[conc_id] == 1:
return fs
else:
return fl
def alpha_beta(bmed):
'''
this fn has been tested and verified
'''
if len(bmed.link_faces) != 2:
return None, None
else:
falpha = bmed.link_faces[0]
fbeta = bmed.link_faces[1]
valpha = [v for v in falpha.verts if not bmed.other_vert(v)][0]
vbeta = [v for v in fbeta.verts if not bmed.other_vert(v)][0]
#valpha.select = True
#vbeta.select = True
V0a = bmed.verts[0].co - valpha.co
V1a = bmed.verts[1].co - valpha.co
V0b = bmed.verts[0].co - vbeta.co
V1b = bmed.verts[1].co - vbeta.co
alpha = V0a.angle(V1a)
beta = V0b.angle(V1b)
return alpha, beta
def wij(bmed, conc_id, fs, fl):
'''
cotangent weight function
fn unsure until gammaij and fs and fl are verified
'''
alpha, beta = alpha_beta(bmed)
gamma = gammaij(bmed, conc_id, fs, fl)
if math.tan(alpha) * math.tan(alpha) < .0000001:
return 100000
weight = 1/2 * gamma * ( 1/math.tan(alpha) + 1/math.tan(beta))
return weight
def manifold_eds(bme):
'''
make sure to exclude non manifold edges
'''
man_eds_L= [ed.index for ed in bme.edges if ed.is_manifold]
manifold_eds = set(man_eds_L)
return manifold_eds
def non_manifold_eds(bme):
'''
make sure to exclude non manifold edges
'''
non_man_eds= [ed.index for ed in bme.edges if not ed.is_manifold]
return non_man_eds
def manifold_verts(bme):
'''
make sure to exclude non manifold verts?
'''
all_verts = set([v.index for v in bme.verts])
non_man_verts = set()
non_man_eds = non_manifold_eds(bme)
for i in non_man_eds:
non_man_verts.add(bme.edges[i].verts[0].index)
non_man_verts.add(bme.edges[i].verts[1].index)
manifold_vs = all_verts - non_man_verts
return manifold_vs
def get_constraint_verts(ob):
g1 = ob.vertex_groups["Verts 1"].index # get group index
g0 = ob.vertex_groups["Verts 0"].index # get group index
g5 = ob.vertex_groups["Verts 0.5"].index # get group index
verts0 = set()
verts1 = set()
verts5 = set()
for v in ob.data.vertices:
for g in v.groups:
if g.group == g0: # compare with index in VertexGroupElement
verts0.add(v.index)
elif g.group == g1:
verts1.add(v.index)
elif g.group == g5:
verts5.add(v.index)
return verts0, verts1, verts5
class CuspWaterDroplet(object):
def __init__(self, bmvert, pln_pt, pln_no, curv_id):
self.up_vert = bmvert
self.dn_vert = bmvert
self.ind_path = [bmvert.index]
self.curv_id = curv_id
self.settled = False
self.peaked = False
self.pln_no = pln_no
self.pln_pt = pln_pt
self.alpha = 0.5 #good values 0.4 to 0.6
self.upH = self.hfunc(bmvert)
self.dnH = self.hfunc(bmvert)
def hfunc(self,bvert):
#possible to cache hfunc over whole mesh?
vz = self.pln_no.dot(bvert.co - self.pln_pt)
K = bvert[self.curv_id] #curvatures are precalced and saved in ID layer
H = (1 - self.alpha) * K - self.alpha * vz #perhaps height and curvature need to be normalized somehow?
return H
def roll_downhill(self):
vs = vert_neighbors(self.dn_vert)
Hs = [self.hfunc(v) for v in vs]
if self.dnH < min(Hs):
self.settled = True
return
else:
V = vs[Hs.index(min(Hs))]
self.dn_vert = V
self.ind_path.append(self.dn_vert.index)
self.dnH = min(Hs)
def roll_uphill(self):
vs = vert_neighbors(self.up_vert)
Hs = [self.hfunc(v) for v in vs]
if self.upH > max(Hs):
self.peaked = True
return
else:
V = vs[Hs.index(max(Hs))]
self.up_vert = V
self.ind_path.insert(0, self.up_vert.index)
self.upH = max(Hs)
def walk_from_vert(vert, prev_vert, steps, scalar_id, dir = None):
'''
will take steps away from vertex and test scalar
sum over path.
#TODO direcionality?
#TODO normalize by path length
#TODO normalize by average scalar value per vertex?
'''
#assume they are connected
if not dir:
dir = vert.co - prev_vert.co
dir.normalize()
v_paths = []
ring = [v for v in vert_neighbors(vert) if v.index != prev_vert.index]
for v in ring:
v_paths.append([vert, v])
for i in range(steps):
new_paths = []
for n, vpath in enumerate(v_paths):
#print('%i iteration and %i path' % (i,n))
#print(vpath)
#find the tip of the path and all it's branches
branches = [v for v in vert_neighbors(vpath[-1]) if v.index != vpath[-2].index]
if len(branches):
for b in branches:
np = vpath.copy()
np.append(b)
new_paths.append(np)
else:
new_paths.append(vpath)
v_paths = new_paths
qualities = []
for path in v_paths:
quality = 0
for v in path:
quality += v[scalar_id]
quality *= 1/len(path)
pdir = path[-1].co - path[0].co
pdir.normalize()
quality *= pdir.dot(dir)
qualities.append(quality)
#print(max(qualities))
best = qualities.index(max(qualities))
return v_paths[best]
def walk_down_path (path, steps, scalar_id, dir = None):
'''
will take steps away from vertex and test scalar
sum over path.
#TODO direcionality?
#TODO normalize by path length
#TODO normalize by average scalar value per vertex?
'''
inds = set([v.index for v in path])
#assume they are connected
if not dir:
dir = path[-1].co - path[-4].co
dir.normalize()
v_paths = []
ring = [v for v in vert_neighbors(path[-1]) if v.index not in inds]
for v in ring:
v_paths.append([path[-1], v])
for i in range(steps):
new_paths = []
for n, vpath in enumerate(v_paths):
#print('%i iteration and %i path' % (i,n))
#print(vpath)
#find the tip of the path and all it's branches, and terminate any which loop back onto original path
branches = [v for v in vert_neighbors(vpath[-1]) if v.index != vpath[-2].index and v.index not in inds]
if len(branches):
for b in branches:
np = vpath.copy()
np.append(b)
new_paths.append(np)
else:
new_paths.append(path)
v_paths = new_paths
qualities = []
for path in v_paths:
quality = 0
for v in path:
quality += v[scalar_id]
quality *= 1/len(path)
pdir = path[-1].co - path[0].co
pdir.normalize()
quality *= pdir.dot(dir)
qualities.append(quality)
#print(max(qualities))
best = qualities.index(max(qualities))
return v_paths[best]
def calc_curvature(v):
if False in [ed.is_manifold for ed in v.link_edges]:
return 0
if not v.is_manifold:
return 0
position = v.co
# get vertex normal as a matrix
normal = v.normal
Nvi = np.matrix(normal)
# get sorted 1-ring
ring = vert_neighbors(v)
# calculate face weightings, wij
wij = []
n = len(ring)
for j in range(n):
vec0 = ring[(j+(n-1))%n].co - position
vec1 = ring[j].co - position
vec2 = ring[(j+1)%n].co - position
# Assumes closed manifold
# TODO: handle boundaries
wij.append(0.5 * (vec0.cross(vec1).length +
vec1.cross(vec2).length))
wijSum = sum(wij)
# calculate matrix, Mvi
Mvi = np.matrix(np.zeros((3,3)))
I = np.matrix(np.identity(3))
for j in range(n):
vec = ring[j].co - position
edgeAsMatrix = np.matrix(vec)
Tij = edgeAsMatrix * (I - (Nvi * Nvi.transpose()))
Tij *= 1 / np.linalg.norm(Tij)
kij = (Nvi.transpose() * 2 * edgeAsMatrix)[0,0] / math.pow(vec.length, 2) #may try transposing this once i get into GIT Rep
Mvi += np.multiply(Tij * Tij.transpose() , wij[j]/wijSum * kij)
# get eigenvalues and eigenvectors for Mvi
evals, evecs = np.linalg.eig(Mvi)
# replace eigenvector matrix with list of Vector3f
evecs = [Vector((evecs[0,k], evecs[1,k], evecs[2,k]))for k in range(3)]
# scale eigenvectors by corresponding eigenvalues
#[e.Unitize() for e in evecs] alreadt normalized from numpy
evecs = [evals[k] * evecs[k] for k in range(3)]
# sort by absolute value of eigenvalues (norm < min < max)
# sortv: abs curvature, curvature, Vector3f dir
mags = [abs(ev) for ev in evals]
max_ind = mags.index(max(mags))
norm_ind = mags.index(min(mags))
min_ind = list(set([0,1,2]) - set([max_ind, norm_ind]))[0]
return evals[max_ind]
def aniso_smooth(bmv, max_id):
if bmv[max_id] == 0:
return 0
ring = vert_neighbors(bmv)
curvs = [vert[max_id] for vert in ring]
if bmv[max_id] < 0:
curvs.sort(reverse = True)
else:
curvs.sort()
new_curv = .6 * bmv[max_id] +.3*curvs[0] + .1*curvs[1]
return new_curv
def curvature_on_mesh(bme):
'''calc initial curvature on bmesh'''
#create custom data layers
if 'max_curve' in bme.verts.layers.float:
print('Data Layer Exists')
max_id = bme.verts.layers.float['max_curve']
else:
max_id = bme.verts.layers.float.new('max_curve')
print('Created Data Layer')
for v in bme.verts:
v[max_id] = calc_curvature(v)
def smooth_scalar_mesh_curvature(bme):
max_id = bme.verts.layers.float['max_curve']
new_curves = [aniso_smooth(bmv, max_id) for bmv in bme.verts]
for v in bme.verts:
v[max_id] = new_curves[v.index]
return np.mean(new_curves), np.std(new_curves)
def main():
ob = bpy.context.object
bme = bmesh.new()
bme.from_mesh(ob.data)
curvature_on_mesh(bme)
max_id = max_id = bme.verts.layers.float['max_curve']
for i in range(0,5):
avg, std_dev = smooth_scalar_mesh_curvature(bme)
curves = [v[max_id] for v in bme.verts]
avg = np.mean(curves)
std_dev = np.std(curves)
for v in bme.verts:
if v[max_id] > avg + .2 * std_dev:
v.select = True
bme.to_mesh(ob.data)
bme.free()
def draw_polyline_from_3dpoints(context, points_3d, color, thickness, LINE_TYPE = "GL_LINE_STIPPLE"):
'''
a simple way to draw a line
slow...becuase it must convert to screen every time
but allows you to pan and zoom around
args:
points_3d: a list of tuples representing x,y SCREEN coordinate eg [(10,30),(11,31),...]
color: tuple (r,g,b,a)
thickness: integer? maybe a float
LINE_TYPE: eg...bgl.GL_LINE_STIPPLE or
'''
points = [location_3d_to_region_2d(context.region, context.space_data.region_3d, loc) for loc in points_3d]
#if LINE_TYPE == "GL_LINE_STIPPLE":
# bgl.glLineStipple(4, 0x5555) #play with this later
# bgl.glEnable(bgl.GL_LINE_STIPPLE)
bgl.glEnable(bgl.GL_BLEND)
bgl.glColor4f(*color)
bgl.glLineWidth(thickness)
bgl.glBegin(bgl.GL_LINE_STRIP)
for coord in points:
if coord:
bgl.glVertex2f(*coord)
bgl.glEnd()
if LINE_TYPE == "GL_LINE_STIPPLE":
bgl.glDisable(bgl.GL_LINE_STIPPLE)
bgl.glEnable(bgl.GL_BLEND) # back to uninterupted lines
bgl.glLineWidth(1)
return
def draw_3d_points(context, points, color, size):
'''
draw a bunch of dots
args:
points: a list of tuples representing x,y SCREEN coordinate eg [(10,30),(11,31),...]
color: tuple (r,g,b,a)
size: integer? maybe a float
'''
points_2d = [location_3d_to_region_2d(context.region, context.space_data.region_3d, loc) for loc in points]
bgl.glColor4f(*color)
bgl.glPointSize(size)
bgl.glBegin(bgl.GL_POINTS)
for coord in points_2d:
#TODO: Debug this problem....perhaps loc_3d is returning points off of the screen.
if coord:
bgl.glVertex2f(*coord)
else:
print('how the f did nones get in here')
print(coord)
bgl.glEnd()
return
def draw_3d_text(context, pt, msg, size):
'''
draw text at a given pt
'''
point_2d = location_3d_to_region_2d(context.region, context.space_data.region_3d, pt)
bgl.glColor4f(0.9, 0.9, 0.9, 0.8)
font_id = 0 # XXX, need to find out how best to get this.
# draw some text
blf.position(font_id, point_2d[0], point_2d[1], 0)
blf.size(font_id, size, 72)
blf.draw(font_id, msg)
return
class ViewOperatorObjectCurve(bpy.types.Operator):
"""Modal object selection with a ray cast"""
bl_idname = "view3d.modal_operator_raycast"
bl_label = "RayCast View Operator"
recalc_curvature = BoolProperty(
name="recalc curvature",
description = "Recalc Curvature (Slow)",
default=False,
)
smooth_curvature = BoolProperty(
name="smooth curvature",
description = "Smooth Existing Curvature",
default=False,
)
smooth = IntProperty(
name="Smooth Iters",
default=1,
min = 0,
max = 4,
)
def draw_callback_verts(self, context):
mx = context.object.matrix_world
coords = [v.co for v in self.path]
draw_3d_points(context, coords, (1,.1,.1,1), 4)
def modal(self, context, event):
context.area.tag_redraw()
if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
# allow navigation
return {'PASS_THROUGH'}
elif event.type == 'MOUSEMOVE':
return {'RUNNING_MODAL'}
elif event.type == 'G' and event.value == 'PRESS':
self.start_walking(context, event)
return {'RUNNING_MODAL'}
elif event.type == 'E' and event.value == 'PRESS':
self.take_step(context,event)
return {'RUNNING_MODAL'}
elif event.type == 'LEFTMOUSE':
self.pick_face(context, event)
return {'RUNNING_MODAL'}
elif event.type == 'UP_ARROW' and event.value == 'PRESS':
self.big_steps += 1
return {'RUNNING_MODAL'}
elif event.type == 'DOWN_ARROW' and event.value == 'PRESS':
if self.stpes > 3:
self.big_steps -= 1
return {'RUNNING_MODAL'}
elif event.type in {'RIGHTMOUSE', 'ESC'}:
bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
self.bme.to_mesh(context.object.data)
self.bme.free()
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
self.steps = 4
self.seed = None
self.seed1 = None
self.path = []
self.path_inds = set()
ob = bpy.context.object
self.bme = bmesh.new()
self.bme.from_mesh(ob.data)
self.bme.verts.ensure_lookup_table()
self.bme.faces.ensure_lookup_table()
if self.recalc_curvature or 'max_curve' not in self.bme.verts.layers.float:
curvature_on_mesh(self.bme)
self.max_id = self.bme.verts.layers.float['max_curve']
if self.smooth_curvature:
for i in range(0,self.smooth):
smooth_scalar_mesh_curvature(self.bme)
if context.space_data.type == 'VIEW_3D':
self._handle = bpy.types.SpaceView3D.draw_handler_add(self.draw_callback_verts, (context,), 'WINDOW', 'POST_PIXEL')
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "Active space must be a View3d")
return {'CANCELLED'}
def pick_face(self, context, event, ray_max=1000.0):
"""Run this function on left mouse, execute the ray cast"""
# get the context arguments
scene = context.scene
region = context.region
rv3d = context.region_data
coord = event.mouse_region_x, event.mouse_region_y
obj = context.object
# get the ray from the viewport and mouse
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
if rv3d.view_perspective == 'ORTHO':
# move ortho origin back
ray_origin = ray_origin - (view_vector * (ray_max / 2.0))
ray_target = ray_origin + (view_vector * ray_max)
def obj_ray_cast(obj, matrix):
"""Wrapper for ray casting that moves the ray into object space"""
# get the ray relative to the object
matrix_inv = matrix.inverted()
ray_origin_obj = matrix_inv * ray_origin
ray_target_obj = matrix_inv * ray_target
# cast the ray
hit, normal, face_index = obj.ray_cast(ray_origin_obj, ray_target_obj)
if face_index != -1:
return hit, normal, face_index
else:
return None, None, None
hit, normal, face_index = obj_ray_cast(obj, obj.matrix_world)
if hit is not None:
curvs = [v[self.max_id] for v in self.bme.faces[face_index].verts]
self.seed = self.bme.faces[face_index].verts[curvs.index(max(curvs))]
def start_walking(self,context, event):
if not self.seed:
return
# get the context arguments
scene = context.scene
region = context.region
rv3d = context.region_data
coord = event.mouse_region_x, event.mouse_region_y
obj = context.object
ray_max = 1000.0
# get the ray from the viewport and mouse
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
if rv3d.view_perspective == 'ORTHO':
# move ortho origin back
ray_origin = ray_origin - (view_vector * (ray_max / 2.0))
ray_target = ray_origin + (view_vector * ray_max)
def obj_ray_cast(obj, matrix):
"""Wrapper for ray casting that moves the ray into object space"""
# get the ray relative to the object
matrix_inv = matrix.inverted()
ray_origin_obj = matrix_inv * ray_origin
ray_target_obj = matrix_inv * ray_target
# cast the ray
hit, normal, face_index = obj.ray_cast(ray_origin_obj, ray_target_obj)
if face_index != -1:
return hit, normal, face_index
else:
return None, None, None
hit, normal, face_index = obj_ray_cast(obj, obj.matrix_world)
if hit is not None:
dir = hit - self.seed.co
dir.normalize()
qualities = []
neighbors = vert_neighbors(self.seed)
for v in neighbors:
qdir = v.co - self.seed.co
qdir.normalize()
#qdir *= -1
q = qdir.dot(dir) * v[self.max_id]
qualities.append(q)
self.seed1 = neighbors[qualities.index(max(qualities))]
self.path = walk_from_vert(self.seed1, self.seed, self.steps, self.max_id, dir = dir)
for v in self.path:
self.path_inds.add(v.index)
v.select = True
def take_step(self,context, event):
print('take step')
if not len(self.path):
return
dir = self.path[-1].co - self.path[-4].co
dir.normalize()
extension = walk_down_path(self.path, self.steps, self.max_id, dir = dir)
print(extension[1:])
#print("the extension is %i long" % len(extension))
self.path.extend(extension[1:])
print(len(self.path))
for v in self.path:
v.select = True
class ViewObjectSalience(bpy.types.Operator):
"""View Object Salience"""
bl_idname = "view3d.live_preview_salience"
bl_label = "View Salience"
def draw_callback_salient(self, context):
# draw some text
blf.position(0, 15, 30, 0)
blf.size(0, 20, 72)
blf.draw(0, "Salient Width " + str(self.width)[0:4])
blf.position(0, 15, 80, 0)
blf.size(0, 20, 72)
blf.draw(0, "Island Size " + str(self.island_min)[0:4])
mx = context.object.matrix_world
if len(self.islands):
for island in self.islands:
coords = [mx * self.bme.verts[i].co for i in island]
draw_3d_points(context, coords, (.1,.5,1,1), 3)
else:
coords = [mx * self.bme.verts[i].co for i in self.salient_verts]
draw_3d_points(context, coords, (1,.1,.1,1), 2)
def find_salient_islands(self,context):
untested = set(self.salient_verts)
still_salient = set()
def get_island(v):
tested = set()
tested.add(v)
new_verts = [v.index for v in vert_neighbors(self.bme.verts[v]) if v.index in untested]
tested = tested.union(set(new_verts))
n_iters = 0
while new_verts and n_iters < 400:
new_neighbors = set()
for nv in new_verts:
ring = set([v.index for v in vert_neighbors(self.bme.verts[nv]) if v.index in untested])
new_immediate_neighbors = ring - tested
new_neighbors = new_neighbors.union(new_immediate_neighbors)
tested = tested.union(set(new_neighbors))
n_iters += 1
new_verts = list(new_neighbors)
if n_iters == 30:
print("found %i verts but itered out" % len(tested))
return tested
iters = 0
while len(untested) and iters < 5000:
vrt = untested.pop()
island = get_island(vrt)
untested = untested.difference(island)
if len(island) > self.island_min:
self.islands.append(list(island))
iters += 1
print('%i salient verts remaining' % len(untested))
def update_salience(self,context):
self.salient_verts = [v.index for v in self.bme.verts if v[self.max_id] > self.avg + self.width * self.std_dev]
self.islands = []
def invoke(self,context, event):
ob = bpy.context.object
self.bme = bmesh.new()
self.bme.from_mesh(ob.data)
self.bme.verts.ensure_lookup_table()
self.bme.faces.ensure_lookup_table()
self.max_id = self.bme.verts.layers.float['max_curve']
curves = [v[self.max_id] for v in self.bme.verts]
self.avg = np.mean(curves)
self.std_dev = np.std(curves)
self.width = .5
self.island_min = 80
self.islands = []
self.salient_verts = [v.index for v in self.bme.verts if v[self.max_id] > self.avg + self.width * self.std_dev]
self._handle = bpy.types.SpaceView3D.draw_handler_add(self.draw_callback_salient, (context,), 'WINDOW', 'POST_PIXEL')
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self,context,event):
context.area.tag_redraw()
if event.type == 'RET' and event.value == 'PRESS':
for i in self.salient_verts:
self.bme.verts[i].select = True
bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
self.bme.to_mesh(context.object.data)
self.bme.free()
return {'FINISHED'}
elif event.type == 'U' and event.value == 'PRESS':
self.update_salience(context)
return {'RUNNING_MODAL'}
elif event.type == 'UP_ARROW' and event.value == 'PRESS':
if event.shift:
self.width += .05
else:
self.width += .1
self.update_salience(context)
return {'RUNNING_MODAL'}
elif event.type == 'DOWN_ARROW' and event.value == 'PRESS':
if event.shift:
self.width -= .05
else: