forked from CGCookie/retopoflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontour_utilities.py
2556 lines (2023 loc) · 81.7 KB
/
contour_utilities.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
'''
Copyright (C) 2013 CG Cookie
http://cgcookie.com
Created by Patrick Moore
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
# System imports
import math
import random
import time
from collections import deque
from itertools import chain,combinations
from mathutils import Vector, Matrix, Quaternion
from mathutils.geometry import intersect_line_plane, intersect_point_line, distance_point_to_plane, intersect_line_line_2d, intersect_line_line
# Blender imports
import bgl
import blf
import bmesh
import bpy
from bpy_extras import view3d_utils
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
def edge_loops_from_bmedges(bmesh, bm_edges):
"""
Edge loops defined by edges
Takes [mesh edge indices] or a list of edges and returns the edge loops
return a list of vertex indices.
[ [1, 6, 7, 2], ...]
closed loops have matching start and end values.
"""
line_polys = []
edges = bm_edges.copy()
while edges:
current_edge = bmesh.edges[edges.pop()]
vert_e, vert_st = current_edge.verts[:]
vert_end, vert_start = vert_e.index, vert_st.index
line_poly = [vert_start, vert_end]
ok = True
while ok:
ok = False
#for i, ed in enumerate(edges):
i = len(edges)
while i:
i -= 1
ed = bmesh.edges[edges[i]]
v_1, v_2 = ed.verts
v1, v2 = v_1.index, v_2.index
if v1 == vert_end:
line_poly.append(v2)
vert_end = line_poly[-1]
ok = 1
del edges[i]
# break
elif v2 == vert_end:
line_poly.append(v1)
vert_end = line_poly[-1]
ok = 1
del edges[i]
#break
elif v1 == vert_start:
line_poly.insert(0, v2)
vert_start = line_poly[0]
ok = 1
del edges[i]
# break
elif v2 == vert_start:
line_poly.insert(0, v1)
vert_start = line_poly[0]
ok = 1
del edges[i]
#break
line_polys.append(line_poly)
return line_polys
def perp_vector_point_line(pt1, pt2, ptn):
'''
Vector bwettn pointn and line between point1
and point2
args:
pt1, and pt1 are Vectors representing line segment
return Vector
pt1 ------------------- pt
^
|
|
|<-----this vector
|
ptn
'''
pt_on_line = intersect_point_line(ptn.to_3d(), pt1.to_3d(), pt2.to_3d())[0]
alt_vect = pt_on_line - ptn
return alt_vect
def altitude(point1, point2, pointn):
edge1 = point2 - point1
edge2 = pointn - point1
if edge2.length == 0:
altitude = 0
return altitude
if edge1.length == 0:
altitude = edge2.length
return altitude
alpha = edge1.angle(edge2)
altitude = math.sin(alpha) * edge2.length
return altitude
# iterate through verts
def iterate(points, newVerts, error,method = 0):
'''
args:
points - list of vectors in order representing locations on a curve
newVerts - list of indices? (mapping to arg: points) of aready identified "new" verts
error - distance obove/below chord which makes vert considered a feature
return:
new - list of vertex indicies (mappint to arg points) representing identified feature points
or
false - no new feature points identified...algorithm is finished.
'''
new = []
for newIndex in range(len(newVerts)-1):
bigVert = 0
alti_store = 0
for i, point in enumerate(points[newVerts[newIndex]+1:newVerts[newIndex+1]]):
if method == 1:
alti = perp_vector_point_line(points[newVerts[newIndex]], points[newVerts[newIndex+1]], point).length
else:
alti = altitude(points[newVerts[newIndex]], points[newVerts[newIndex+1]], point)
if alti > alti_store:
alti_store = alti
if alti_store >= error:
bigVert = i+1+newVerts[newIndex]
if bigVert:
new.append(bigVert)
if new == []:
return False
return new
#### get SplineVertIndices to keep
def simplify_RDP(splineVerts, error, method = 0):
'''
Reduces a curve or polyline based on altitude changes globally and w.r.t. neighbors
args:
splineVerts - list of vectors representing locations along the spline/line path
error - altitude above global/neighbors which allows point to be considered a feature
return:
newVerts - a list of indicies of the simplified representation of the curve (in order, mapping to arg-splineVerts)
'''
start = time.time()
# set first and last vert
newVerts = [0, len(splineVerts)-1]
# iterate through the points
new = 1
while new != False:
new = iterate(splineVerts, newVerts, error, method = method)
if new:
newVerts += new
newVerts.sort()
print('finished simplification with method %i in %f seconds' % (method, time.time() - start))
return newVerts
def relax(verts, factor = .75, in_place = True):
'''
verts is a list of Vectors
first and last vert will not be changes
this should modify the list in place
however I have it returning verts?
'''
L = len(verts)
if L < 4:
print('not enough verts to relax')
return verts
deltas = [Vector((0,0,0))] * L
for i in range(1,L-1):
d = .5 * (verts[i-1] + verts[i+1]) - verts[i]
deltas[i] = factor * d
if in_place:
for i in range(1,L-1):
verts[i] += deltas[i]
return True
else:
new_verts = verts.copy()
for i in range(1,L-1):
new_verts[i] += deltas[i]
return new_verts
def pi_slice(x,y,r1,r2,thta1,thta2,res,t_fan = False):
'''
args:
x,y - center coordinate
r1, r2 inner and outer radius
thta1: beginning of the slice 0 = to the right
thta2: end of the slice (ccw direction)
'''
points = [[0,0]]*(2*res + 2) #the two arcs
for i in range(0,res+1):
diff = math.fmod(thta2-thta1 + 4*math.pi, 2*math.pi)
x1 = math.cos(thta1 + i*diff/res)
y1 = math.sin(thta1 + i*diff/res)
points[i]=[r1*x1 + x,r1*y1 + y]
points[(2*res) - i+1] =[x1*r2 + x, y1*r2 + y]
if t_fan: #need to shift order so GL_TRIANGLE_FAN can draw concavity
new_0 = math.floor(1.5*(2*res+2))
points = list_shift(points, new_0)
return(points)
def arrow_primitive(x,y,ang,tail_l, head_l, head_w, tail_w):
#primitive
#notice the order so that the arrow can be filled
#in by traingle fan or GL quad arrow[0:4] and arrow [4:]
prim = [Vector((-tail_w,tail_l)),
Vector((-tail_w, 0)),
Vector((tail_w, 0)),
Vector((tail_w, tail_l)),
Vector((head_w,tail_l)),
Vector((0,tail_l + head_l)),
Vector((-head_w,tail_l))]
#rotation
rmatrix = Matrix.Rotation(ang,2)
#translation
T = Vector((x,y))
arrow = [[None]] * 7
for i, loc in enumerate(prim):
arrow[i] = T + rmatrix * loc
return arrow
def arc_arrow(x,y,r1,thta1,thta2,res, arrow_size, arrow_angle, ccw = True):
'''
args:
x,y - center coordinate of cark
r1 = radius of arc
thta1: beginning of the arc 0 = to the right
thta2: end of the arc (ccw direction)
arrow_size = length of arrow point
ccw = True draw the arrow
'''
points = [Vector((0,0))]*(res +1) #The arc + 2 arrow points
for i in range(0,res+1):
#able to accept negative values?
diff = math.fmod(thta2-thta1 + 2*math.pi, 2*math.pi)
x1 = math.cos(thta1 + i*diff/res)
y1 = math.sin(thta1 + i*diff/res)
points[i]=Vector((r1*x1 + x,r1*y1 + y))
if not ccw:
points.reverse()
end_tan = points[-2] - points[-1]
end_tan.normalize()
#perpendicular vector to tangent
arrow_perp_1 = Vector((-end_tan[1],end_tan[0]))
arrow_perp_2 = Vector((end_tan[1],-end_tan[0]))
op_ov_adj = (math.tan(arrow_angle/2))**2
arrow_side_1 = end_tan + op_ov_adj * arrow_perp_1
arrow_side_2 = end_tan + op_ov_adj * arrow_perp_2
arrow_side_1.normalize()
arrow_side_2.normalize()
points.append(points[-1] + arrow_size * arrow_side_1)
points.append(points[-2] + arrow_size * arrow_side_2)
return(points)
def simple_circle(x,y,r,res):
'''
args:
x,y - center coordinate of cark
r1 = radius of arc
'''
points = [Vector((0,0))]*res #The arc + 2 arrow points
for i in range(0,res):
theta = i * 2 * math.pi / res
x1 = math.cos(theta)
y1 = math.sin(theta)
points[i]=Vector((r * x1 + x, r * y1 + y))
return(points)
def get_path_length(verts):
'''
sum up the length of a string of vertices
'''
l_tot = 0
if len(verts) < 2:
return 0
for i in range(0,len(verts)-1):
d = verts[i+1] - verts[i]
l_tot += d.length
return l_tot
def get_com(verts):
'''
args:
verts- a list of vectors to be included in the calc
mx- thw world matrix of the object, if empty assumes unity
'''
COM = Vector((0,0,0))
l = len(verts)
for v in verts:
COM += v
COM =(COM/l)
return COM
def approx_radius(verts, COM):
'''
avg distance
'''
l = len(verts)
app_rad = 0
for v in verts:
R = COM - v
app_rad += R.length
app_rad = 1/l * app_rad
return app_rad
def verts_bbox(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 diagonal_verts(verts):
xs = [v[0] for v in verts]
ys = [v[1] for v in verts]
zs = [v[2] for v in verts]
dx = max(xs) - min(xs)
dy = max(ys) - min(ys)
dz = max(zs) - min(zs)
diag = math.pow((dx**2 + dy**2 + dz**2),.5)
return diag
def calculate_com_normal(locs):
'''
computes a center of mass (CoM) and a normal of provided roughly planar locs
notes:
- uses random sampling
- does not assume a particular order of locs
- may compute the negative of "true" normal
'''
com = sum((loc for loc in locs), Vector((0,0,0))) / len(locs)
# get locations wrt to com
llocs = [loc-com for loc in locs]
ac = Vector((0,0,0))
first = True
for i in range(len(locs)):
lp0,lp1 = random.sample(llocs,2)
c = lp0.cross(lp1).normalized()
if first:
ac = c
first = False
else:
if ac.dot(c) < 0:
ac -= c
else:
ac += c
return (com, ac.normalized())
#TODO: CREDIT
#TODO: LINK
def calculate_best_plane(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()
itermax = 500
iter = 0
vec = Vector((1.0, 1.0, 1.0))
vec2 = (mat * vec)/(mat * vec).length
while vec != vec2 and iter<itermax:
iter+=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
return(com, normal)
def cross_section(bme, mx, point, normal, debug = True):
'''
Takes a mesh and associated world matrix of the object and returns a cross secion in local
space.
Args:
mesh: Blender BMesh
mx: World matrix (type Mathutils.Matrix)
point: any point on the cut plane in world coords (type Mathutils.Vector)
normal: plane normal direction (type Mathutisl.Vector)
'''
times = []
times.append(time.time())
#bme = bmesh.new()
#bme.from_mesh(me)
#bme.normal_update()
#if debug:
#n = len(times)
#times.append(time.time())
#print('succesfully created bmesh in %f sec' % (times[n]-times[n-1]))
verts =[]
eds = []
#convert point and normal into local coords
#in the mesh into world space.This saves 2*(Nverts -1) matrix multiplications
imx = mx.inverted()
pt = imx * point
no = imx.to_3x3() * normal #local normal
edge_mapping = {} #perhaps we should use bmesh becaus it stores the great cycles..answer yup
for ed in bme.edges:
A = ed.verts[0].co
B = ed.verts[1].co
V = B - A
proj = V.project(no).length
#perp to normal = parallel to plane
#only calc 2nd projection if necessary
if proj == 0:
#make sure not coplanar
p_to_A = A - pt
a_proj = p_to_A.project(no).length
if a_proj == 0:
edge_mapping[len(verts)] = ed.link_faces
verts.append(1/2 * (A +B)) #put a midpoing since both are coplanar
else:
#this handles the one point on plane case
v = intersect_line_plane(A,B,pt,no)
if v:
check = intersect_point_line(v.to_3d(),A.to_3d(),B.to_3d())
if check[1] >= 0 and check[1] <= 1:
#the vert coord index = the face indices it came from
edge_mapping[len(verts)] = [f.index for f in ed.link_faces]
verts.append(v)
if debug:
n = len(times)
times.append(time.time())
print('calced intersections %f sec' % (times[n]-times[n-1]))
#iterate through smartly to create edge keys
for i in range(0,len(verts)):
a_faces = set(edge_mapping[i])
for m in range(i,len(verts)):
if m != i:
b_faces = set(edge_mapping[m])
if a_faces & b_faces:
eds.append((i,m))
if debug:
n = len(times)
times.append(time.time())
#print('calced connectivity %f sec' % (times[n]-times[n-1]))
if len(verts):
#new_me = bpy.data.meshes.new('Cross Section')
#new_me.from_pydata(verts,eds,[])
#if debug:
#n = len(times)
#times.append(time.time())
#print('Total Time: %f sec' % (times[-1]-times[0]))
return (verts, eds)
else:
return None
def cross_edge(A,B,pt,no):
'''
wrapper of intersect_line_plane that limits intersection
to within the line segment.
args:
A - Vector endpoint of line segment
B - Vector enpoint of line segment
pt - pt on plane to intersect
no - normal of plane to intersect
return:
list [Intersection Type, Intersection Point, Intersection Point2]
eg... ['CROSS',Vector((0,1,0)), None]
eg... ['POINT',Vector((0,1,0)), None]
eg....['COPLANAR', Vector((0,1,0)),Vector((0,2,0))]
eg....[None,None,None]
'''
ret_val = [None]*3 #list [intersect type, pt 1, pt 2]
V = B - A #vect representation of the edge
proj = V.project(no).length
#perp to normal = parallel to plane
#worst case is a coplanar issue where the whole face is coplanar..we will get there
if proj == 0:
#test coplanar
#don't test both points. We have already tested once for paralellism
#simply proving one out of two points is/isn't in the plane will
#prove/disprove coplanar
p_to_A = A - pt
#truly, we could precalc all these projections to save time but use mem.
#because in the multiple edges coplanar case, we wil be testing
#their verts over and over again that share edges. So for a mesh with
#a lot of n poles, precalcing the vert projections may save time!
#Hint to future self, look at Nfaces vs Nedges vs Nverts
#may prove to be a good predictor of which method to use.
a_proj = p_to_A.project(no).length
if a_proj == 0:
print('special case co planar edge')
ret_val = ['COPLANAR',A,B]
else:
#this handles the one point on plane case
v = intersect_line_plane(A,B,pt,no)
if v:
check = intersect_point_line(v.to_3d(),A.to_3d(),B.to_3d())
if check[1] > 0 and check[1] < 1: #this is the purest cross...no co-points
#the vert coord index = the face indices it came from
ret_val = ['CROSS',v,None]
elif check[1] == 0 or check[1] == 1:
print('special case coplanar point')
#now add all edges that have that point into the already checked list
#this takes care of poles
ret_val = ['POINT',v,None]
return ret_val
def outside_loop_2d(loop):
'''
args:
loop: list of
type-Vector or type-tuple
returns:
outside = a location outside bound of loop
type-tuple
'''
xs = [v[0] for v in loop]
ys = [v[1] for v in loop]
maxx = max(xs)
maxy = max(ys)
bound = (1.1*maxx, 1.1*maxy)
return bound
def bound_box(verts):
'''
takes a list of vectors of any dimension
returns a list of (min,max) pairs
'''
if len(verts) < 4:
return verts
dim = len(verts[0])
bounds = []
for i in range(0,dim):
components = [v[i] for v in verts]
low = min(components)
high = max(components)
bounds.append((low,high))
return bounds
def diagonal(bounds):
'''
returns the diagonal dimension of min/max
pairs of bounds. Will generalize to N dimensions
however only really meaningful for 2 or 3 dim vectors
'''
diag = 0
for min_max in bounds:
l = min_max[1] - min_max[0]
diag += l * l
diag = diag ** .5
return diag
#adapted from opendentalcad then to pie menus now here
def point_inside_loop2d(loop, point):
'''
args:
loop: list of vertices representing loop
type-tuple or type-Vector
point: location of point to be tested
type-tuple or type-Vector
return:
True if point is inside loop
'''
#test arguments type
ptype = str(type(point))
ltype = str(type(loop[0]))
nverts = len(loop)
if 'Vector' not in ptype:
point = Vector(point)
if 'Vector' not in ltype:
for i in range(0,nverts):
loop[i] = Vector(loop[i])
#find a point outside the loop and count intersections
out = Vector(outside_loop_2d(loop))
intersections = 0
for i in range(0,nverts):
a = Vector(loop[i-1])
b = Vector(loop[i])
if intersect_line_line_2d(point,out,a,b):
intersections += 1
inside = False
if math.fmod(intersections,2):
inside = True
return inside
def generic_axes_from_plane_normal(p_pt, no):
'''
will take a point on a plane and normal vector
and return two orthogonal vectors which create
a right handed coordinate system with z axist aligned
to plane normal
'''
#get the equation of a plane ax + by + cz = D
#Given point P, normal N ...any point R in plane satisfies
# Nx * (Rx - Px) + Ny * (Ry - Py) + Nz * (Rz - Pz) = 0
#now pick any xy, yz or xz and solve for the other point
a = no[0]
b = no[1]
c = no[2]
Px = p_pt[0]
Py = p_pt[1]
Pz = p_pt[2]
D = a * Px + b * Py + c * Pz
#generate a randomply perturbed R from the known p_pt
R = p_pt + Vector((random.random(), random.random(), random.random()))
#z = D/c - a/c * x - b/c * y
if c != 0:
Rz = D/c - a/c * R[0] - b/c * R[1]
R[2] = Rz
#y = D/b - a/b * x - c/b * z
elif b!= 0:
Ry = D/b - a/b * R[0] - c/b * R[2]
R[1] = Ry
#x = D/a - b/a * y - c/a * z
elif a != 0:
Rx = D/a - b/a * R[1] - c/a * R[2]
R[0] = Rz
else:
print('undefined plane you wanker!')
return(False)
#now R represents some other point in the plane
#we will use this to define an arbitrary local
#x' y' and z'
X_prime = R - p_pt
X_prime.normalize()
Y_prime = no.cross(X_prime)
Y_prime.normalize()
return (X_prime, Y_prime)
def point_inside_loop_almost3D(pt, verts, no, p_pt = None, threshold = .01, debug = False, bbox = False):
'''
http://blenderartists.org/forum/showthread.php?259085-Brainstorming-for-Virtual-Buttons&highlight=point+inside+loop
args:
pt - 3d point to test of type Mathutils.Vector
verts - 3d points representing the loop
TODO: verts[0] == verts[-1] or implied?
list with elements of type Mathutils.Vector
no - plane normal
plane_pt - a point on the plane.
if None, COM of verts will be used
threshold - maximum distance to consider pt "coplanar"
default = .01
debug - Bool, default False. Will print performance if True
return: Bool True if point is inside the loop
'''
if debug:
start = time.time()
#sanity checks
if len(verts) < 3:
print('loop must have 3 verts to be a loop and even then its sketchy')
return False
if no.length == 0:
print('normal vector must be non zero')
return False
if not p_pt:
p_pt = get_com(verts)
if distance_point_to_plane(pt, p_pt, no) > threshold:
return False
(X_prime, Y_prime) = generic_axes_from_plane_normal(p_pt, no)
verts_prime = []
for v in verts:
v_trans = v - p_pt
vx = v_trans.dot(X_prime)
vy = v_trans.dot(Y_prime)
verts_prime.append(Vector((vx, vy)))
bounds = bound_box(verts_prime)
bound_loop = [Vector((bounds[0][0],bounds[1][0])),
Vector((bounds[0][1],bounds[1][0])),
Vector((bounds[0][1],bounds[1][1])),
Vector((bounds[0][0],bounds[1][1]))]
#transform the test point into the new plane x,y space
pt_trans = pt - p_pt
pt_prime = Vector((pt_trans.dot(X_prime), pt_trans.dot(Y_prime)))
if bbox:
print('intersected the bbox')
pt_in_loop = point_inside_loop2d(bound_loop, pt_prime)
else:
pt_in_loop = point_inside_loop2d(verts_prime, pt_prime)
return pt_in_loop
def face_cycle(face, pt, no, prev_eds, verts):#, connection):
'''
args:
face - Blender BMFace
pt - Vector, point on plane
no - Vector, normal of plane
These arguments will be modified
prev_eds - MUTABLE list of previous edges already tested in the bmesh
verts - MUTABLE list of Vectors representing vertex coords
connection - MUTABLE dictionary of vert indices and face connections
return:
element - either a BMVert or a BMFace depending on what it finds.
'''
if len(face.edges) > 4:
ngon = True
print('oh sh** an ngon')
else:
ngon = False
for ed in face.edges:
if ed.index not in prev_eds:
prev_eds.append(ed.index)
A = ed.verts[0].co
B = ed.verts[1].co
result = cross_edge(A, B, pt, no)
if result[0] == 'CROSS':
#connection[len(verts)] = [f.index for f in ed.link_faces]
verts.append(result[1])
next_faces = [newf for newf in ed.link_faces if newf.index != face.index]
if len(next_faces):
return next_faces[0]
else:
#guess we got to a non manifold edge
print('found end of mesh!')
return None
elif result[0] == 'POINT':
if result[1] == A:
co_point = ed.verts[0]
else:
co_point = ed.verts[1]
#connection[len(verts)] = [f.index for f in co_point.link_faces] #notice we take the face loop around the point!
verts.append(result[1]) #store the "intersection"
return co_point
def vert_cycle(vert, pt, no, prev_eds, verts):#, connection):
'''
args:
vert - Blender BMVert
pt - Vector, point on plane
no - Vector, normal of plane
These arguments will be modified
prev_eds - MUTABLE list of previous edges already tested in the bmesh
verts - MUTABLE list of Vectors representing vertex coords
connection - MUTABLE dictionary of vert indices and face connections
return:
element - either a BMVert or a BMFace depending on what it finds.
'''
for f in vert.link_faces:
for ed in f.edges:
if ed.index not in prev_eds:
prev_eds.append(ed.index)
A = ed.verts[0].co
B = ed.verts[1].co
result = cross_edge(A, B, pt, no)
if result[0] == 'CROSS':
#connection[len(verts)] = [f.index for f in ed.link_faces]
verts.append(result[1])
next_faces = [newf for newf in ed.link_faces if newf.index != f.index]
if len(next_faces):
#return face to try face cycle
return next_faces[0]
else:
#guess we got to a non manifold edge
print('found end of mesh!')
return None
elif result[0] == 'COPLANAR':
cop_face = 0
for face in ed.link_faces:
if face.normal.cross(no) == 0:
cop_face += 1
print('found a coplanar face')
if cop_face == 2:
#we have two coplanar faces with a coplanar edge
#this makes our cross section fail from a loop perspective
print("double coplanar face error, stopping here")
return None
else:
#jump down line to the next vert
if ed.verts[0].index == vert.index:
element = ed.verts[1]
else:
element = ed.verts[0]
#add the new vert coord into the mix
#connection[len(verts)] = [f.index for f in element.link_faces]
verts.append(element.co)
#return the vert to repeat the vert cycle
return element
def space_evenly_on_path(verts, edges, segments, shift = 0, debug = False): #prev deved for Open Dental CAD
'''
Gives evenly spaced location along a string of verts
Assumes that nverts > nsegments
Assumes verts are ORDERED along path
Assumes edges are ordered coherently
Yes these are lazy assumptions, but the way I build my data
guarantees these assumptions so deal with it.
args:
verts - list of vert locations type Mathutils.Vector
eds - list of index pairs type tuple(integer) eg (3,5).
should look like this though [(0,1),(1,2),(2,3),(3,4),(4,0)]
segments - number of segments to divide path into
shift - for cyclic verts chains, shifting the verts along
the loop can provide better alignment with previous
loops. This should be -1 to 1 representing a percentage of segment length.
Eg, a shift of .5 with 8 segments will shift the verts 1/16th of the loop length
return
new_verts - list of new Vert Locations type list[Mathutils.Vector]
'''