-
Notifications
You must be signed in to change notification settings - Fork 1
/
odcutils.py
2638 lines (2112 loc) · 86.6 KB
/
odcutils.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
#----------------------------------------------------------
# File utils.py
#----------------------------------------------------------
'''
Created on Nov 20, 2012
#test commit tracker
This module has all the little extra tasks I need to keep the other code cleanish.
Things like 3d math, matrix math, selections, mundane bookkeeping, contextual management etc.
Some License might be in the source directory. Summary: don't be an asshole, but do whatever you want with this code
Author: Patrick Moore: patrick.moore.bu@gmail.com
'''
import os
import bpy
import addon_utils
import time
import math
import random
import bmesh
import mesh_cut
from mesh_cut import edge_loops_from_bmedges
from mathutils import Vector, Matrix, Quaternion
from bpy_extras.mesh_utils import edge_loops_from_edges
from mathutils.geometry import intersect_point_line
from common_utilities import bversion
#Borrowed from retopoflow @CGCookie, Jonathan Wiliamson, Jon Denning, Patrick Moore
def get_settings():
if not get_settings.cached_settings:
addons = bpy.context.user_preferences.addons
#frame = inspect.currentframe()
#frame.f_code.co_filename
folderpath = os.path.dirname(os.path.abspath(__file__))
while folderpath:
folderpath,foldername = os.path.split(folderpath)
if foldername in {'lib','addons'}: continue
if foldername in addons: break
else:
assert False, 'Could not find non-"lib" folder'
get_settings.cached_settings = addons[foldername].preferences
return get_settings.cached_settings
get_settings.cached_settings = None
#global universal_intntl
universal_intntl = {}
#global intntl_universal
intntl_universal = {}
international = [18,17,16,15,14,13,12,11,
21,22,23,24,25,26,27,28,
38,37,36,35,34,33,32,31,
41,42,43,44,45,46,47,48]
for i in range(1,33):
intntl_universal[international[i-1]] = i
universal_intntl[i] = international[i-1]
def unvi_to_intntl(a):
b = universal_intntl(a)
return b
#initial function for testing importing etc
def util_func(a,b,c):
print("the util function %f and %d and %f" %(a,b,c))
def list_shift(seq, n):
n = n % len(seq)
return seq[n:] + seq[:n]
def running_sum(a):
tot = 0
for item in a:
tot += item
return tot
def project_report(scene):
if scene.odc_props:
for pair in scene.odc_props.items():
print(pair)
if scene.odc_teeth:
for tooth in scene.odc_teeth:
print(tooth.name)
for pair in tooth.items():
print(pair)
if scene.odc_implants:
for tooth in scene.odc_implants:
print(tooth.name)
for pair in tooth.items():
print(pair)
if scene.odc_bridges:
for tooth in scene.odc_bridges:
print(tooth.name)
for pair in tooth.items():
print(pair)
if scene.odc_splints:
for tooth in scene.odc_splints:
print(tooth.name)
for pair in tooth.items():
print(pair)
#TODO: Layers get messed up if in another layer when object added. make sure layer management forces other layers off....
#TODO: Using layers may cause data access problems...may have to manage this in scene preservation/reconstruction
def scene_preserv(context, objects = True, tools = True, space = True, debug = False):
'''
#TODO: write this docstring
basically collects a lot of settings so you can mess with them
in an operator and then put everytying back like you found it.
'''
if debug:
start = time.time()
ret_list = []
if objects:
objects_dict = {}
for setting in ["object","selected_objects","mode"]:
objects_dict[setting] = getattr(context, setting)
hidden_obs = [ob for ob in bpy.data.objects if ob.hide]
objects_dict["hidden"] = hidden_obs
ret_list.append(objects_dict)
if tools:
tools_dict = {}
for setting in ["vertex_group_weight", "mesh_select_mode","use_proportional_edit_objects", "proportional_edit", "proportional_edit_falloff","proportional_size","use_snap","snap_element"]:
tools_dict[setting] = getattr(context.tool_settings, setting)
ret_list.append(tools_dict)
if space:
space_dict = {}
for setting in ["pivot_point","transform_orientation","use_pivot_point_align","use_occlude_geometry","show_manipulator"]:
space_dict[setting] = getattr(context.space_data, setting)
ret_list.append(space_dict)
if debug:
print('preserved the scene in %f seconds' % (time.time() - start))
elif debug > 1:
for key in objects_dict.keys():
print("%s : %s" % (key, objects_dict[key]))
return ret_list
def scene_reconstruct(context, obj_dict = {}, tools_dict = {}, space_dict = {}, debug = False):
'''
#TODO: write this docstring
basically collects a lot of settings so you can mess with them
in an operator and then put everytying back like you found it.
'''
if debug:
start = time.time()
if obj_dict:
context.scene.objects.active = obj_dict["object"]
for ob in bpy.data.objects:
if ob in obj_dict["selected_objects"]:
ob.select = True
else:
ob.select = False
if ob in obj_dict["hidden"]:
ob.hide = True
else:
ob.hide = False
if context.mode != obj_dict["mode"]:
if 'EDIT' in obj_dict["mode"]:
bpy.ops.object.mode_set(mode='EDIT')
else:
bpy.ops.object.mode_set(mode=obj_dict["mode"])
if tools_dict:
for setting in tools_dict.keys():
setattr(context.tool_settings, setting, tools_dict[setting])
if space_dict:
for setting in space_dict.keys():
setattr(context.space_data, setting,space_dict[setting])
if debug:
print('reconstructed the scene in %f seconds' % (time.time() - start))
return None
def get_all_addons(display=False):
"""
Prints the addon state based on the user preferences.
"""
import sys
# RELEASE SCRIPTS: official scripts distributed in Blender releases
paths_list = addon_utils.paths()
addon_list = []
for path in paths_list:
bpy.utils._sys_path_ensure(path)
for mod_name, mod_path in bpy.path.module_names(path):
is_enabled, is_loaded = addon_utils.check(mod_name)
addon_list.append(mod_name)
if display: #for example
print("%s default:%s loaded:%s"%(mod_name,is_enabled,is_loaded))
return(addon_list)
def get_com(me,verts,mx):
'''
args:
me - the Blender Mesh data
verts- a list of indices to be included in the calc
mx- thw world matrix of the object, if empty assumes unity
'''
if not mx:
mx = Matrix()
COM = Vector((0,0,0))
l = len(verts)
for v in verts:
COM = COM + me.vertices[v].co
COM = mx * (COM/l)
return COM
def get_com_bme(bme,vert_inds,mx):
'''
args:
me - the Blender Mesh data
verts- a list of indices to be included in the calc
mx- thw world matrix of the object, if empty assumes unity
'''
if not mx:
mx = Matrix()
COM = Vector((0,0,0))
l = len(vert_inds)
for v in vert_inds:
COM = COM + bme.verts[v].co
COM = mx * (COM/l)
return COM
def primitive_flattened_cylinder(R, r, N, H):
#http://mathworld.wolfram.com/Circle-LineIntersection.html
if r >= R:
#make a primitive cylinder and return it
bm = bmesh.new()
ret = bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=N, diameter1=R, diameter2=R, depth=H)
for vert in bm.verts:
vert.co[2] += H/2
return bm
xr = (R*R - r*r)**0.5
xs = []
ys = []
inserts = []
toggle = True
for i in range(0,N):
x = R * math.cos(i * 2 * math.pi / N)
y = R * math.sin(i * 2 * math.pi / N)
if abs(x) <= xr:
if toggle == True:
toggle = False
inserts.append(i)
if y < 0:
ys.append(-r)
else:
ys.append(r)
else:
if toggle == False:
toggle = True
inserts.append(i)
ys.append(y)
xs.append(x)
xs.insert(inserts[0],xr)
xs.insert(inserts[1]+1,-xr)
xs.insert(inserts[2]+2,-xr)
xs.insert(inserts[3]+3,xr)
ys.insert(inserts[0],r)
ys.insert(inserts[1]+1,r)
ys.insert(inserts[2]+2,-r)
ys.insert(inserts[3]+3,-r)
print(xs)
print(ys)
print(inserts)
print(xr)
bm = bmesh.new()
bmverts = []
for i in range(0,len(xs)):
bmverts.append(bm.verts.new((xs[i], ys[i], 0)))
bmverts.append(bm.verts.new((xs[i], ys[i], H)))
for i in range(0,N+3):
new_face = bm.faces.new((
bmverts[2*i+2],
bmverts[2*i+3],
bmverts[2*i+1],
bmverts[2*i],
))
new_face = bm.faces.new((
bmverts[0],
bmverts[1],
bmverts[2*(N+4)-1],
bmverts[2*(N+4)-2]
))
top_verts = [bmverts[2*i] for i in range(0,N+4)]
bottom_verts = [bmverts[2*i+1] for i in range(0,N+4)]
top_verts.reverse()
end_cap = bm.faces.new(tuple(top_verts))
end_cap = bm.faces.new(tuple(bottom_verts))
return bm
def primitive_wedge_cylinder(R, pct, N, H):
'''
not precise, will round to nearest integer vert.
Radius
pct: fraction of circle to make. between 0 and 1
N: Resolution of circle
H: Height of cylinder
'''
if pct >= .99 or pct < .1:
#error, bad input...
bm = bmesh.new()
ret = bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=N, diameter1=R, diameter2=R, depth=H)
for vert in bm.verts:
vert.co[2] += H/2
return bm
#start out with a 0 vert
xs = [0]
ys = [0]
Nmax = round(pct*N) + 1
for i in range(0,Nmax):
x = R * math.cos(i * 2 * math.pi / N)
y = R * math.sin(i * 2 * math.pi / N)
xs.append(x)
ys.append(y)
bm = bmesh.new()
bmverts = []
for i in range(0,len(xs)):
bmverts.append(bm.verts.new((xs[i], ys[i], 0)))
bmverts.append(bm.verts.new((xs[i], ys[i], H)))
for i in range(0,Nmax):
new_face = bm.faces.new((
bmverts[2*i],
bmverts[2*i+2],
bmverts[2*i+3],
bmverts[2*i+1]))
new_face = bm.faces.new((
bmverts[0],
bmverts[1],
bmverts[2*(Nmax+1)-1],
bmverts[2*(Nmax+1)-2]))
top_verts = [bmverts[2*i+1] for i in range(0,Nmax+1)]
bottom_verts = [bmverts[2*i] for i in range(0,Nmax+1)]
bottom_verts.reverse()
top = bm.faces.new(tuple(top_verts))
bottom = bm.faces.new(tuple(bottom_verts))
return bm
def get_bbox_center(ob, world = True):
if world:
mx = ob.matrix_world
else:
mx = Matrix.Identity(3)
box = Vector((0,0,0))
for v in ob.bound_box:
box += mx * Vector(v)
box *= 1/8
return box
def bbox_to_lattice(scene, ob):
mx = ob.matrix_world
loc = get_bbox_center(ob, world=True)
size = Vector((ob.dimensions[0], ob.dimensions[1], ob.dimensions[2]))
lat_data = bpy.data.lattices.new(ob.name[0:2] + "_control")
lat = bpy.data.objects.new(lat_data.name, lat_data)
lat.location = loc
lat.scale = 1.05*size
lat.layers[1] = True
lat.layers[0] = True
if lat.rotation_mode != 'QUATERNION':
lat.rotation_mode = 'QUATERNION'
lat.rotation_quaternion = mx.to_quaternion()
lat.update_tag()
scene.objects.link(lat)
scene.update()
lat.data.points_u = 3
lat.data.points_v = 3
lat.data.points_w = 3
lat_mod = ob.modifiers.new('Lattice','LATTICE')
lat_mod.object = lat
return lat #in case you want to delete it after youe apply it.
def box_feature_locations(ob, specify):
'''
returns the location on the bounding box in global coords
args:
ob - blender object
specify - vector of type Mathutils Vector specifying location eg.. which corner, edge or face
examples:
vector = ((0,0,1)) :: middle of top face
vector = ((-1,-1,0)) :: left, back, edge midpoint
vector = ((1,-1,1)) :: right, back, top corner
'''
#construct the correct matrix
xyz = Matrix()
xyz = xyz.to_3x3()
for i in range(0,3):
for j in range(0,3):
if i == j:
xyz[j][i] = specify[i]
dim = ob.dimensions
#calc bbox_center
b_cent = get_bbox_center(ob, world=True)
location = b_cent + ob.matrix_world.to_quaternion() * (xyz * dim/2)
return location
def get_linear_density(me, edges, mx = None, debug = False):
'''
args:
me - the Blender Mesh data
edges - the mesh edges to be calculated
mx- the world matrix of the object, if empty assumes unity and will return local value
return: average vert spacing of edges
'''
if debug:
start = time.time()
if not mx:
mx = Matrix.Identity(3)
N_edges = len(edges)
sum_edge_length = 0
for e in edges:
v0= mx * me.vertices[e.vertices[0]].co
v1= mx * me.vertices[e.vertices[1]].co
V = Vector(v1 - v0)
sum_edge_length += pow((V.length*V.length),.5)
linear_density = sum_edge_length/N_edges
if debug:
time_taken = time.time() - start
print("calced the linear density of %d edges in %f seconds" % (N_edges, time_taken))
return linear_density
def edge_loop_curvature(me, edges, neighbors = 3, mx = None, debug = False, assume_even = True):
'''
args:
me - the Blender Mesh data
edges - the mesh edges to be calculated
mx- the world matrix of the object, if empty assumes unity and will return local values
return: a dict of curvature values and vertex indices
'''
if debug:
start = time.time()
if not mx:
mx = Matrix.Identity(3)
if assume_even:
s_len = get_linear_density(me, edges, mx, debug = False)
loops = edge_loops_from_edges(me, edges)
if len(loops)>1:
longest_loop_index = 0
biggest_len = 0
for i, loop in enumerate(loops):
if len(loop) > biggest_len:
biggest_len = len(loop)
longest_loop_index = i
#later add support to return as many lists as there are loops
verts_indx_order = loops[longest_loop_index]
#test if cyclic or not (edge_loops_from_edges will repeat first index at end of list if closed loop)
linear = verts_indx_order[0] != verts_indx_order[-1]
if not linear:
verts_indx_order.pop()
#one less vertex than indices in the list if cyclic
N_verts = len(verts_indx_order)
verts = [me.vertices[i] for i in verts_indx_order]
#forward vector representation of all the edges
ed_vecs = [verts[i+1].co - verts[i].co for i in range(0,len(verts)-2)]
if not linear:
ed_vecs.append(verts[0].co - verts[-1].co)
curvatures = [0]*N_verts - neighbors * 2 * linear
indices = [0]*N_verts - neighbors * 2 * linear
#linear indexing starts 0 +neigbors to len(verts) -1 - neighbors
#cyclic indexing starts 0 - neighbors to len(verts) -1 - neighbors
for i in range(neighbors, N_verts -1 - neighbors):
d_thetas = [0]*neighbors
curve = 0
if not assume_even:
s_len = 0
for n in range(0,neighbors):
d_thetas = ed_vecs[i-1-n].angle(ed_vecs[i+n])
if not assume_even:
s_len += ed_vecs[i-1-n].length + ed_vecs[i+n].length
#this results in a 1/n weighted average
curve += 1/(2 * neighbors) * (neighbors - n) * (1/((2 * (n + 1) * s_len)))
curvatures[i - neighbors] = curve
indices = verts_indx_order[i]
if debug:
time_taken = time.time() - start
print("calced discrete curvature of %d verts in %f seconds" % (N_verts,time_taken))
return curvatures
def active_tooth_from_index(scene):
j = scene.odc_tooth_index
tooth = scene.odc_teeth[j]
return tooth
def parent_in_place(child,parent):
'''
context, selection, hidden etc insensitive parenting
args: child and parent are blender objects
Return: finished? nothing?
'''
current_matrix = child.matrix_world.copy()
child.parent = parent
child.matrix_world = current_matrix
def active_odc_item_candidate(items, ob, exclude, debug = False):
'''
items: ToothRestoration, Bridge Restoration or Implant Restoration in scene.odc_teeth (collection of ToothRestorations)
objects: list of blender objects
exclude: properties to exclude for guessing which tooth is being workied on...eg, mesial, distal
return: ODC Tooth object wich has this Blender Object as one of it's property values
iteartes through the props in a property group and tests the object's name agains it
'''
candidate = None
for tooth in items:
prop_keys = tooth.keys()
prop_vals = tooth.values()
if ob.name in prop_vals:
n = prop_vals.index(ob.name)
this_key = prop_keys[n]
if debug:
print("found the object named %s as the property value: %s" %(ob.name, this_key))
if this_key and (this_key not in exclude):
candidate = tooth
return candidate
def splint_selction(context):
'''
looks at addon preferences
returns a list,
'''
sce = context.scene
splint = sce.odc_splints[sce.odc_splint_index]
return [splint]
def tooth_selection(context):
'''
looks at addon preferences and selected objects in scene
returns a list or selected units
'''
sce = context.scene
selected_items = []
if not hasattr(sce, "odc_props"):
print('addon may be broken')
return selected_items
settings = get_settings()
b = settings.behavior
behave_mode = settings.behavior_modes[int(b)]
if behave_mode == 'LIST' and len(context.scene.odc_teeth):
#choose just one tooth in the list
tooth = sce.odc_teeth[sce.odc_tooth_index]
selected_items.append(tooth)
elif behave_mode == 'ACTIVE':
#test the active object, if nothing...default to item_list
if context.object and context.object.select == True:
ob = context.object
tooth = active_odc_item_candidate(sce.odc_teeth, ob,[])
if tooth:
selected_items.append(tooth)
#sce.odc_tooth_index = sce.odc_teeth.find(tooth.name) #force the active tooth index..seems like a good idea?
elif behave_mode == 'ACTIVE_SELECTED':
#test active object and selected objects
if context.object and context.object.select == True:
#test the active object
ob = context.object
tooth = active_odc_item_candidate(sce.odc_teeth, ob,[])
if tooth and tooth not in selected_items:
selected_items.append(tooth)
if context.selected_editable_objects and context.object:
obs = [ob for ob in context.selected_editable_objects if ob.name != context.object.name]
for ob in obs:
tooth = active_odc_item_candidate(sce.odc_teeth, ob,[])
if tooth and tooth not in selected_items:
selected_items.append(tooth)
if len(selected_items) == 0 and len(context.scene.odc_teeth): #meaning previous method found nothing
tooth = sce.odc_teeth[sce.odc_tooth_index]
selected_items.append(tooth)
return selected_items
def implant_selection(context):
'''
looks at addon preferences
returns a list,
'''
sce = context.scene
implants = []
if not hasattr(sce, 'odc_props'): return implants
if len(context.scene.odc_implants) == 0: return implants
settings = get_settings()
b = settings.behavior
behave_mode = settings.behavior_modes[int(b)]
if len(context.scene.odc_implants) == 0:
return implants
if behave_mode == 'LIST'and len(context.scene.odc_implants):
#choose just one tooth in the list
implant = sce.odc_implants[sce.odc_implant_index]
implants.append(implant)
elif behave_mode == 'ACTIVE':
#test the active object, if nothing...default to item_list
if context.object:
ob = context.object
implant = active_odc_item_candidate(sce.odc_implants, ob,[])
if implant:
implants.append(implant)
#sce.odc_tooth_index = sce.odc_teeth.find(tooth.name) #force the active tooth index..seems like a good idea?
elif behave_mode == 'ACTIVE_SELECTED':
#test active object and selected objects
if context.object:
#test the active object, if nothing...default to item_list
ob = context.object
implant = active_odc_item_candidate(sce.odc_implants, ob,[])
if implant and implant not in implants:
implants.append(implant)
if context.selected_editable_objects and context.object:
obs = [ob for ob in context.selected_editable_objects if ob.name != context.object.name]
for ob in obs:
implant = active_odc_item_candidate(sce.odc_implants, ob,[])
if implant and implant not in implants:
implants.append(implant)
if len(implants) == 0 and len(context.scene.odc_implants): #meaning previous method found nothing
implant = sce.odc_implants[sce.odc_implant_index]
implants.append(implant)
return implants
'''
if context.object:
tooth_candidates = active_odc_item_candidate(sce.odc_teeth, [context.selected_editable_objects],[])
if tooth_candidates:
tooth = sce.odc_teeth[tooth_candidates[0]]
sce.odc_tooth_index = sce.odc_teeth.find(tooth.name) #force the active tooth index..seems like a good idea?
if not tooth:
self.report({'WARNING'},"I'm not sure which tooth you want, guessing based on active tooth in list")
tooth = sce.odc_teeth[sce.odc_tooth_index]
return tooth
'''
def add_proximity_mod(ob1, ob2, min_d, max_d, group_name = None, n = None, over = 0):
'''
args:
ob1 - object to have mod added to
ob2 - target object for modifier calc
group - NAME of vertex group for modifier to affect, if None, will make a new one.
min_d - minimum distance
max_d - max distance to color
n - place in mod stack. None goes to end.
over = value to overwrite the Proximity vertex group with first. None to leave group as is
'''
#pre-op setting code
#make sure ob1 is how it needs to be
bpy.ops.object.select_all(action='DESELECT')
bpy.context.scene.objects.active = ob1
ob1.select = True
#take care of vertex group business
group = None
if group_name:
group = ob1.vertex_groups.get(group_name)
if not group:
group = ob1.vertex_groups.get("Proximity")
if not group:
n=len(ob1.vertex_groups)
bpy.ops.object.vertex_group_add()
ob1.vertex_groups[n].name = "Proximity"
bpy.ops.object.mode_set(mode='EDIT')
bpy.context.tool_settings.vertex_group_weight = 1
bpy.context.tool_settings.mesh_select_mode = [True,False,False]
bpy.ops.object.vertex_group_set_active(group = 'Proximity')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.object.vertex_group_assign()
bpy.ops.object.mode_set(mode='OBJECT')
group = ob1.vertex_groups[n]
i=len(ob1.modifiers)
bpy.ops.object.modifier_add(type='VERTEX_WEIGHT_PROXIMITY')
mod = ob1.modifiers[i]
mod.target=ob2
mod.proximity_mode = 'GEOMETRY'
mod.proximity_geometry = {'EDGE','VERTEX','FACE'}
mod.min_dist = min_d
mod.max_dist = max_d
mod.vertex_group=group.name
return mod
def scale_vec_mult(a,b):
'''
performs item wise multiplication return Vec(a0*b0,a1*b1,a2*b2)
args:
a - vector of type mathutils.Vector
b - vector of type mathutils.Vector
'''
out = Vector((a[0]*b[0],a[1]*b[1],a[2]*b[2]))
return out
def extrude_edges_in(me, edges, mx, axis, res, debug = False):
'''
takes a CLOSED LOOP of edges and moves them in
eg..take a loop and turn it into a railroad track
sorry for the naming convetion...doesn't actually extrude them, just moves them.
you should extrude them first
needs an axis to move perpendicular too...typically 3d view direction
args:
me - Blender Mesh Data
edges - edges (not indices of edges) that form a closed loop
mx - world matrix of object
z - the world axis which to extrude perpendicular to type Vector...probably the insertion axis
res - distance step for each extrusion...world size
'''
if debug:
start = time.time() #monitor performance
#take the appropriate steps to go to local coords
imx = mx.copy()
imx.invert()
irot = imx.to_quaternion()
iscl = imx.to_scale()
z = irot*axis
verts_in_order = edge_loops_from_edges(me,edges)
verts_in_order = verts_in_order[0]
verts_in_order.append(verts_in_order[1]) #the first (n=0) element of the list already repeated, adding the 2nd to the end as well.
l = len(verts_in_order)
verts_alone = verts_in_order[0:l-2]
lerps = [Vector((0,0,0))]*(l-2)
vcoords = [me.vertices[index].co for index in verts_in_order]
curl = 0
for n in range(0,l-2):
#Vec representation of the two edges
V0 = (vcoords[n+1] - vcoords[n])
V1 = (vcoords[n+2] - vcoords[n+1])
##XY projection
T0 = V0 - V0.project(z)
T1 = V1 - V1.project(z)
cross = T0.cross(T1)
sign = 1
if cross.dot(z) < 0:
sign = -1
rot = T0.rotation_difference(T1)
ang = rot.angle
curl = curl + ang*sign
lerps[n] = V0.lerp(V1,.5)
clockwise = 1
if curl < 0:
clockwise = -1
if debug:
print(curl)
print('you can double check the curl/CCW by examining first 10 vertex indices')
print(verts_in_order[0:10])
for n in range(0,l-2):
index = verts_in_order[n+1]
v = me.vertices[index]
V = lerps[n]
trans = z.cross(V)*clockwise
trans.normalize()
delta = scale_vec_mult(trans, iscl)
delta *= res
v.co += delta
if debug:
print("moved %d verts in %f seconds" %(l-2,time.time()-start))
'''
ob = bpy.context.object
me = ob.data
mx = ob.matrix_world
axis = Vector((0,0,1))
edges = [e for e in me.edges if e.select]
res = 0.5
utils.extrude_edges_in(me, edges, mx, axis, res):
'''
def offset_bmesh_edge_loop(bme, bmedges, axis, res, debug = False):
'''
takes a CLOSED LOOP of bmesh edges and moves them in
eg..take a loop and turn it into a railroad track
needs an axis to move perpendicular too...typically 3d view direction
args:
bme - Blender BMesh Data
bmedges - indices of edges that form a closed loop
axis - the local axis which to extrude perpendicular to type Vector...probably the insertion axis
res - distance step for each extrusion...world size
'''
if debug:
start = time.time() #monitor performance
z = axis
bme.edges.ensure_lookup_table()
bme.verts.ensure_lookup_table()
loops = edge_loops_from_bmedges(bme, bmedges)
verts_in_order = loops[0]
verts_in_order.append(verts_in_order[1]) #the first (n=0) element of the list already repeated, adding the 2nd to the end as well.
l = len(verts_in_order)
verts_alone = verts_in_order[0:l-2]
lerps = [Vector((0,0,0))]*(l-2)
vcoords = [bme.verts[index].co for index in verts_in_order]
curl = 0
for n in range(0,l-2):
#Vec representation of the two edges
V0 = (vcoords[n+1] - vcoords[n])
V1 = (vcoords[n+2] - vcoords[n+1])
##XY projection
T0 = V0 - V0.project(z)
T1 = V1 - V1.project(z)
cross = T0.cross(T1)
sign = 1
if cross.dot(z) < 0:
sign = -1
rot = T0.rotation_difference(T1)
ang = rot.angle
curl = curl + ang*sign
lerps[n] = V0.lerp(V1,.5)
clockwise = 1
if curl < 0:
clockwise = -1
if debug:
print(curl)
print('you can double check the curl/CCW by examining first 10 vertex indices')
print(verts_in_order[0:10])
for n in range(0,l-2):
index = verts_in_order[n+1]
v = bme.verts[index]
V = lerps[n]
trans = z.cross(V)*clockwise
trans.normalize()
#delta = scale_vec_mult(trans, iscl)
#delta *= res
delta = res * trans
v.co += delta
if debug:
print("moved %d verts in %f seconds" %(l-2,time.time()-start))
'''
ob = bpy.context.object
me = ob.data
mx = ob.matrix_world
axis = Vector((0,0,1))
edges = [e for e in me.edges if e.select]
res = 0.5
utils.extrude_edges_in(me, edges, mx, axis, res):
'''
def material_management(context, odc_items, force = False, debug = False):
'''
goes through all the items in project
checks them for a material slot
if none, adds the apporpriate material fom the material library, linking if necesary
It will not change an existing material slot in case the user wants to modify colors unless force = True
'''
material_dictionary = {"prep_model":"prep",
"opposing":"opposing",
"bubble":"opposing",
"restoration":"restoration",
"contour":"restoration",
"coping":"restoration",
"acoping":"restoration",
"intaglio":"connector",
"outer":"aligner",
"inner":"collision",
"tissue":"tissue",
"splint":"splint",
"model":"prep",
"master":"master"}
if debug:
starttime = time.time()