-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path__init__.py
1249 lines (1095 loc) · 47.2 KB
/
__init__.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
bl_info = {
"name": "SwiftBlock",
"author": "Karl-Johan Nogenmyr",
"version": (0, 1),
"blender": (2, 6, 6),
"api": 44000,
"location": "Tool Shelf",
"description": "Writes block geometry as blockMeshDict file",
"warning": "not much tested yet",
"wiki_url": "http://openfoamwiki.net/index.php/SwiftBlock",
"tracker_url": "",
"support": 'COMMUNITY',
"category": "OpenFOAM"}
#----------------------------------------------------------
# File scene_props.py
#----------------------------------------------------------
import bpy
from bpy.props import *
def getPolyLines(verts, edges, obj):
scn = bpy.context.scene
polyLinesPoints = []
polyLines = ''
polyLinesLengths = [[], []]
def isPointOnEdge(point, A, B):
eps = (((A - B).magnitude - (point-B).magnitude) - (A-point).magnitude)
return True if (abs(eps) < scn.tol) else False
nosnap= [False for i in range(len(edges))]
for eid, e in enumerate(obj.data.edges):
nosnap[eid] = e.use_edge_sharp
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)")
geoobj = bpy.data.objects[scn.geoobjName]
geo_verts = list(blender_utils.vertices_from_mesh(geoobj))
geo_edges = list(blender_utils.edges_from_mesh(geoobj))
geoobj.select = False # avoid deletion
# First go through all vertices in the block structure and find vertices snapped to edges
# When found, add a vertex at that location to the polyLine object by splitting the edge
# Create a new Blender object containing the newly inserted verts. Then use Blender's
# shortest path algo to find polyLines.
for vid, v in enumerate(verts):
found = False
for gvid, gv in enumerate(geo_verts):
mag = (v-gv).magnitude
if mag < scn.tol:
found = True
break # We have found a vertex co-located, continue with next block vertex
if not found:
for geid, ge in enumerate(geo_edges):
if (isPointOnEdge(v, geo_verts[ge[0]], geo_verts[ge[1]])):
geo_verts.append(v)
geo_edges.append([geo_edges[geid][1],len(geo_verts)-1]) # Putting the vert on the edge, by splitting it in two.
geo_edges[geid][1] = len(geo_verts)-1
break # No more iteration, go to next block vertex
mesh_data = bpy.data.meshes.new("deleteme")
mesh_data.from_pydata(geo_verts, geo_edges, [])
mesh_data.update()
geoobj = bpy.data.objects.new('deleteme', mesh_data)
bpy.context.scene.objects.link(geoobj)
geo_verts = list(blender_utils.vertices_from_mesh(geoobj))
geo_edges = list(blender_utils.edges_from_mesh(geoobj))
bpy.context.scene.objects.active=geoobj
# Now start the search over again on the new object with more verts
snapped_verts = {}
for vid, v in enumerate(verts):
for gvid, gv in enumerate(geo_verts):
mag = (v-gv).magnitude
if mag < scn.tol:
snapped_verts[vid] = gvid
break # We have found a vertex co-located, continue with next block vertex
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)")
for edid, ed in enumerate(edges):
if ed[0] in snapped_verts and ed[1] in snapped_verts and not nosnap[edid]:
geoobj.hide = False
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
geoobj.data.vertices[snapped_verts[ed[0]]].select = True
geoobj.data.vertices[snapped_verts[ed[1]]].select = True
bpy.ops.object.mode_set(mode='EDIT')
try:
bpy.ops.mesh.select_vertex_path(type='EDGE_LENGTH')
except:
bpy.ops.mesh.shortest_path_select(use_length=True)
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.duplicate()
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.separate(type='SELECTED')
bpy.ops.object.mode_set(mode='OBJECT')
polyLineobj = bpy.data.objects['deleteme.001']
if len(polyLineobj.data.vertices) > 2:
polyLineverts = list(blender_utils.vertices_from_mesh(polyLineobj))
polyLineedges = list(blender_utils.edges_from_mesh(polyLineobj))
for vid, v in enumerate(polyLineverts):
mag = (v-verts[ed[0]]).magnitude
if mag < scn.tol:
startVertex = vid
break
polyLineStr, vectors, length = sortedVertices(polyLineverts,polyLineedges,startVertex)
polyLinesPoints.append([ed[0],ed[1],vectors])
polyLinesLengths[0].append([min(ed[0],ed[1]), max(ed[0],ed[1])]) # write out sorted
polyLinesLengths[1].append(length)
polyLine = 'polyLine {} {} ('.format(*ed)
polyLine += polyLineStr
polyLine += ')\n'
polyLines += polyLine
geoobj.select = False
polyLineobj.select = True
bpy.ops.object.delete()
geoobj.select = True
bpy.ops.object.delete()
return polyLines, polyLinesPoints, polyLinesLengths
def sortedVertices(verts,edges,startVert):
sorted = []
vectors = []
sorted.append(startVert)
vert = startVert
length = len(edges)+1
for i in range(len(verts)):
for eid, e in enumerate(edges):
if vert in e:
if e[0] == vert:
sorted.append(e[1])
else:
sorted.append(e[0])
edges.pop(eid)
vert = sorted[-1]
break
polyLine = ''
length = 0.
for vid, v in enumerate(sorted):
polyLine += '({} {} {})'.format(*verts[v])
vectors.append(verts[v])
if vid>=1:
length += (vectors[vid] - vectors[vid-1]).magnitude
return polyLine, vectors, length
def patchColor(patch_no):
color = [(1.0,0.,0.), (0.0,1.,0.),(0.0,0.,1.),(0.707,0.707,0),(0,0.707,0.707),(0.707,0,0.707)]
return color[patch_no % len(color)]
def initProperties():
bpy.types.Scene.tol = FloatProperty(
name = "tol",
description = "Snapping tolerance",
default = 1e-6,
min = 0.)
bpy.types.Scene.ctmFloat = FloatProperty(
name = "convertToMeters",
description = "Conversion factor: Blender coords to meter",
default = 1.0,
min = 0.)
bpy.types.Scene.resFloat = FloatProperty(
name = "Resolution",
description = "The average spatial resolution of generated mesh in meter",
default = 1.0,
min = 0)
bpy.types.Scene.resForce = IntProperty(
name = "# cells",
description = "For forcing the number of cells on edge (0 disables)",
default = 0,
min = 0)
bpy.types.Scene.grading = FloatProperty(
name = "Grading",
description = "The size ratio of first and last cell on edge",
default = 1.0)
bpy.types.Scene.whichCell = EnumProperty(
items = [('Coarse', 'Coarse', 'Let the coarse cells have the target resolution'),
('Fine', 'Fine', 'Let the fine cells have the target resolution')
],
name = "Cell resolution")
bpy.types.Scene.setEdges = BoolProperty(
name = "Set edges",
description = "Should edges be fetched from another object?",
default = False)
bpy.types.Scene.geoobjName = StringProperty(
name = "Object",
description = "Name of object to get edges from (this box disappears when object is found)",
default = '')
bpy.types.Scene.bcTypeEnum = EnumProperty(
items = [('wall', 'wall', 'Defines the patch as wall'),
('patch', 'patch', 'Defines the patch as generic patch'),
('empty', 'empty', 'Defines the patch as empty'),
('symmetryPlane', 'symmetryPlane', 'Defines the patch as symmetryPlane'),
],
name = "Patch type")
bpy.types.Scene.patchName = StringProperty(
name = "Patch name",
description = "Specify name of patch (max 31 chars)",
default = "defaultName")
bpy.types.Scene.snapping = EnumProperty(
items = [('yes', 'Yes', 'The edge gets a polyLine if its vertices are snapped'),
('no', 'No', 'The edge will be meshed as a straight line')
],
name = "Edge snapping")
bpy.types.Scene.removeInternal = BoolProperty(
name = "Remove internal faces",
description = "Should internal faces be removed?",
default = False)
bpy.types.Scene.createBoundary = BoolProperty(
name = "Create boundary faces",
description = "Should boundary faces be created?",
default = False)
return
#
# Menu in UI region
#
class UIPanel(bpy.types.Panel):
bl_label = "SwiftBlock settings"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
layout = self.layout
scn = context.scene
obj = context.active_object
settings = context.tool_settings
try:
obj['swiftblock']
except:
try:
obj['swiftBlockObj']
layout.operator("delete.preview")
except:
layout.operator("enable.swiftblock")
else:
layout = layout.column()
layout.operator("write.bmdfile")
layout.operator("create.preview")
layout.operator("find.broken")
layout.prop(scn, 'ctmFloat')
layout.prop(scn, 'resFloat')
box = layout.box()
box = box.column()
box.label(text='Edge settings')
box.prop(scn, 'setEdges')
if scn.setEdges:
try:
geoojb = bpy.data.objects[scn.geoobjName]
textstr = "Fetching egde's polyLines from " + geoojb.name
box.operator("change.geoobj", text=textstr, emboss=False)
# box.prop(scn, 'tol') # the tolerance setting do not behave as I expected... do not adjust for now
split = box.split()
col = split.column()
col.operator('nosnap.edge', text='Curved').snapping = True
col = split.column()
col.operator('nosnap.edge', text='Straight')
box.separator()
except:
box.prop(scn, 'geoobjName')
split = box.split()
col = split.column()
col.prop(scn, 'resForce')
col.prop(scn, 'grading')
col.operator("flip.edge")
col = split.column()
col.operator("set.edgeres")
col.row().prop(scn,"whichCell", expand=True)
col.operator("set.grading")
col.operator("show.edgeinfo", text="Edge settings")
box = layout.box()
box = box.column()
box.label(text='Patch settings')
box.prop(scn, 'patchName')
box.prop(scn, 'bcTypeEnum')
box.operator("set.patchname")
for m in obj.data.materials:
try:
patchtype = str(' ' + m['patchtype'])
split = box.split(percentage=0.2, align=True)
col = split.column()
col.prop(m, "diffuse_color", text="")
col = split.column()
col.operator("set.getpatch", text=m.name + patchtype, emboss=False).whichPatch = m.name
except:
pass
box.operator("repair.faces")
group = obj.vertex_groups.active
rows = 2
if group:
rows = 4
layout.label('Block\'s name settings')
row = layout.row()
row.template_list("MESH_UL_vgroups", "", obj, "vertex_groups", obj.vertex_groups, "active_index", rows=rows)
col = row.column(align=True)
col.operator("object.vertex_group_add", icon='ZOOMIN', text="")
col.operator("object.vertex_group_remove", icon='ZOOMOUT', text="").all = False
if group:
col.separator()
col.operator("object.vertex_group_move", icon='TRIA_UP', text="").direction = 'UP'
col.operator("object.vertex_group_move", icon='TRIA_DOWN', text="").direction = 'DOWN'
if group:
row = layout.row()
row.prop(group, "name")
if obj.vertex_groups and obj.mode == 'EDIT':
row = layout.row()
sub = row.row(align=True)
sub.operator("object.vertex_group_assign", text="Assign")
sub.operator("object.vertex_group_remove_from", text="Remove")
sub = row.row(align=True)
sub.operator("object.vertex_group_select", text="Select")
sub.operator("object.vertex_group_deselect", text="Deselect")
class OBJECT_OT_edgeInfo(bpy.types.Operator):
'''Show/edit settings for one selected edge'''
bl_idname = "show.edgeinfo"
bl_label = "Show and edit settings for selected edge"
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
obj = context.active_object
scn = context.scene
for e in obj.data.edges:
if e.select:
if scn.snapping == 'yes':
e.use_edge_sharp = False
else:
e.use_edge_sharp = True
bpy.ops.set.edgeres()
bpy.ops.set.grading()
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
obj = context.active_object
scn = context.scene
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
NoSelected = 0
for e in obj.data.edges:
if e.select:
NoSelected += 1
if e.use_seam:
scn.whichCell = 'Fine'
else:
scn.whichCell = 'Coarse'
if e.bevel_weight >= 0.001:
scn.resForce = obj['bevelToResMap'][str(round(e.bevel_weight*100))]
else:
scn.resForce = 0
if e.crease == 0:
scn.grading = 1
else:
scn.grading = obj['creaseToGradMap'][str(round(e.crease*100))]
if e.use_edge_sharp:
scn.snapping = 'no'
else:
scn.snapping = 'yes'
if NoSelected >= 2:
self.report({'INFO'}, "More than one edge selected!")
return{'CANCELLED'}
elif NoSelected == 0:
self.report({'INFO'}, "Please select an edge!")
return{'CANCELLED'}
context.window_manager.invoke_props_dialog(self, width=400)
return {'RUNNING_MODAL'}
def draw(self, context):
scn = context.scene
split = self.layout.split(percentage=0.5)
col = split.column()
col.label("Define polyLine:")
col.label("Grading:")
col.label("Which cell gets target res:")
col.label("Forced resolution:")
col = split.column()
col.row().prop(scn, "snapping", expand=True)
col.prop(scn, "grading")
col.row().prop(scn,"whichCell", expand=True)
col.prop(scn, "resForce")
class OBJECT_OT_nosnapEdge(bpy.types.Operator):
'''Force selected edge(s) straight or curved'''
bl_idname = "nosnap.edge"
bl_label = "No snap"
snapping = BoolProperty(default = False)
def invoke(self, context, event):
bpy.ops.object.mode_set(mode='OBJECT')
obj = context.active_object
NoSelect = 0
for e in obj.data.edges:
if e.select:
NoSelect += 1
if not self.snapping:
e.use_edge_sharp = True
else:
e.use_edge_sharp = False
if not NoSelect:
self.report({'INFO'}, "No edge(s) selected!")
bpy.ops.object.mode_set(mode='EDIT')
return{'CANCELLED'}
bpy.ops.object.mode_set(mode='EDIT')
return {'RUNNING_MODAL'}
class OBJECT_OT_insertSmoother(bpy.types.Operator):
'''Inserts a smoother'''
bl_idname = "insert.smoother"
bl_label = "Insert smoother"
def execute(self, context):
try:
bpy.data.objects[context.scene.geoobjName]
except:
self.report({'INFO'}, "Cannot find object for edges!")
return{'CANCELLED'}
import mathutils
from . import utils
bpy.ops.object.mode_set(mode='OBJECT')
scn = context.scene
obj = context.active_object
obj.select=False
geoobj = bpy.data.objects[scn.geoobjName]
geoobj.hide = False
centre = mathutils.Vector((0,0,0))
no_verts = 0
profile = utils.smootherProfile()
res = profile.__len__()
matrix = obj.matrix_world.copy()
for v in obj.data.vertices:
if v.select:
centre += matrix*v.co
no_verts += 1
if no_verts == 0:
self.report({'INFO'}, "Nothing selected!")
return{'CANCELLED'}
centre /= no_verts
if no_verts <= 2:
centre = mathutils.Vector((0,0,centre[2]))
for e in obj.data.edges:
if e.select:
(v0id, v1id) = e.vertices
v0 = matrix*obj.data.vertices[v0id].co
v1 = matrix*obj.data.vertices[v1id].co
edgevector = v1-v0
normal = centre-v0
tang = normal.project(edgevector)
normal -= tang
normal.normalize()
normal *= -edgevector.length
p = [v0 for i in range(res)]
e = [[0,1] for i in range(res)]
for i in range(res):
linecoord = float(i)/(res-1)
p[i] = (1-linecoord)*v0+linecoord*v1
p[i] += 0.05*normal*profile[i]
for i in range(res-1):
e[i] = [i,i+1]
mesh_data = bpy.data.meshes.new("deleteme")
mesh_data.from_pydata(p, e, [])
mesh_data.update()
addtoobj = bpy.data.objects.new('deleteme', mesh_data)
bpy.context.scene.objects.link(addtoobj)
bpy.data.objects['deleteme'].select = True
geoobj.select = True
scn.objects.active = geoobj
bpy.ops.object.join()
geoobj.select = False
geoobj.select = True
scn.objects.active = geoobj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.remove_doubles(threshold=0.0001, use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
geoobj.select = False
obj.select = True
scn.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class OBJECT_OT_flipEdge(bpy.types.Operator):
'''Flip direction of selected edge(s). This is useful if you want to \
set grading on several edges which are initially misaligned'''
bl_idname = "flip.edge"
bl_label = "Flip edge"
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
obj = context.active_object
for e in obj.data.edges:
if e.select:
(e0, e1) = e.vertices
e.vertices = (e1, e0)
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class OBJECT_OT_deletePreview(bpy.types.Operator):
'''Delete preview mesh object'''
bl_idname = "delete.preview"
bl_label = "Delete preview mesh"
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
name = ''
for obj in bpy.data.objects:
try:
name = obj['swiftBlockObj']
except:
obj.select = False
bpy.ops.object.delete()
try:
obj = bpy.data.objects[name]
obj.select = True
obj.hide = False
bpy.context.scene.objects.active = obj
except:
pass
return {'FINISHED'}
class OBJECT_OT_ChangeGeoObj(bpy.types.Operator):
'''Click to change object'''
bl_idname = "change.geoobj"
bl_label = "Change"
def execute(self, context):
context.scene.geoobjName = ''
return {'FINISHED'}
class OBJECT_OT_Enable(bpy.types.Operator):
'''Enables SwiftBlock for the active object'''
bl_idname = "enable.swiftblock"
bl_label = "Enable SwiftBlock"
def execute(self, context):
obj = context.active_object
obj['swiftblock'] = True
bpy.context.tool_settings.use_mesh_automerge = True
bpy.ops.object.mode_set(mode='OBJECT')
obj.data.use_customdata_edge_crease = True
obj.data.use_customdata_edge_bevel = True
bpy.ops.object.material_slot_remove()
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
try:
mat = bpy.data.materials['defaultName']
patchindex = list(obj.data.materials).index(mat)
obj.active_material_index = patchindex
except:
mat = bpy.data.materials.new('defaultName')
mat.diffuse_color = (0.5,0.5,0.5)
bpy.ops.object.material_slot_add()
obj.material_slots[-1].material = mat
mat['patchtype'] = 'wall'
bpy.ops.object.editmode_toggle()
bpy.ops.object.material_slot_assign()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.editmode_toggle()
return{'FINISHED'}
class OBJECT_OT_SetPatchName(bpy.types.Operator):
'''Set the given name to the selected faces'''
bl_idname = "set.patchname"
bl_label = "Set name"
def execute(self, context):
scn = context.scene
obj = context.active_object
bpy.ops.object.mode_set(mode='OBJECT')
NoSelected = 0
for f in obj.data.polygons:
if f.select:
NoSelected += 1
if NoSelected:
namestr = scn.patchName
namestr = namestr.strip()
namestr = namestr.replace(' ', '_')
try:
mat = bpy.data.materials[namestr]
patchindex = list(obj.data.materials).index(mat)
obj.active_material_index = patchindex
except: # add a new patchname (as a blender material, as such face props are conserved during mesh mods)
mat = bpy.data.materials.new(namestr)
mat.diffuse_color = patchColor(len(obj.data.materials)-1)
bpy.ops.object.material_slot_add()
obj.material_slots[-1].material = mat
mat['patchtype'] = scn.bcTypeEnum
bpy.ops.object.editmode_toggle()
bpy.ops.object.material_slot_assign()
else:
self.report({'INFO'}, "No faces selected!")
return{'CANCELLED'}
return {'FINISHED'}
class OBJECT_OT_SetEdgeRes(bpy.types.Operator):
'''Force a resolution on selected edge(s)'''
bl_idname = "set.edgeres"
bl_label = "Force resolution"
# This very messy way to keep track of resolution is needed as we have to store the info
# in edges native properties. Here bevel_weight is used which is a float in range [0,1]
# The float can store approx. 100 different values. By mult. by 100, int in range [0,100]
# is achieved. This int is mapped to user-set resolution with the 'bevelToResMap'
def execute(self, context):
scn = context.scene
obj = context.active_object
res = scn.resForce
bpy.ops.object.mode_set(mode='OBJECT')
NoSelect = 0
for e in obj.data.edges:
if e.select == True:
NoSelect += 1
if not NoSelect:
self.report({'INFO'}, "No edge(s) selected!")
bpy.ops.object.mode_set(mode='EDIT')
return{'CANCELLED'}
try:
obj['bevelToResMap']
except:
obj['bevelToResMap']= {}
existingRes = set()
for e in obj.data.edges:
if str(round(e.bevel_weight*100)) in obj['bevelToResMap']:
existingRes.add(round(e.bevel_weight*100))
else:
e.bevel_weight = 0 #remove bevel if no entry in bevelToResMap was found
mapEntryToRemove = set()
for entry in obj['bevelToResMap']:
if not int(entry) in existingRes:
mapEntryToRemove.add(entry)
for entry in mapEntryToRemove:
obj['bevelToResMap'].pop(entry)
if res == 0:
for e in obj.data.edges:
if e.select == True:
e.bevel_weight = 0
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
bevelToResMap = obj['bevelToResMap']
foundRes = False
for bevelInt in bevelToResMap:
if bevelToResMap[bevelInt] == res: # previously used resolution - reuse!
bevel = int(bevelInt)
foundRes = True
if not foundRes:
allEntries = set(range(1,101)) #all possible bevel entries
newEntry = min(list(allEntries.difference(existingRes)))
bevelToResMap[str(newEntry)] = res # create a new entry in map
bevel = newEntry
for e in obj.data.edges:
if e.select == True:
e.bevel_weight = bevel/100.
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class OBJECT_OT_SetGrading(bpy.types.Operator):
'''Set grading on selected edge(s). Use Ctrl-Alt-Space to find out orientation of each edge. \
Cells will be coarser in the edge's z-direction for grading > 1'''
bl_idname = "set.grading"
bl_label = "Set grading"
# This very messy way to keep track of grading is needed as we have to store the info
# in edges native properties. Here crease is used which is a float in range [0,1]
# The float can store approx. 100 different values. By mult. by 100, int in range [0,100]
# is achieved. This int is mapped to user-set grading with the 'creaseToGradMap'
def execute(self, context):
scn = context.scene
obj = context.active_object
grad = scn.grading
if scn.whichCell == 'Fine':
use_seam = True
else:
use_seam = False
bpy.ops.object.mode_set(mode='OBJECT')
NoSelect = 0
for e in obj.data.edges:
if e.select == True:
NoSelect += 1
if not NoSelect:
self.report({'INFO'}, "No edge(s) selected!")
bpy.ops.object.mode_set(mode='EDIT')
return{'CANCELLED'}
try:
obj['creaseToGradMap']
except:
obj['creaseToGradMap']= {}
obj.data.show_edge_crease = False # could be set true to show which edges have grading
if grad == 1:
for e in obj.data.edges:
if e.select == True:
e.crease = 0
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
existingGrad = set()
for e in obj.data.edges:
if str(round(e.crease*100)) in obj['creaseToGradMap']:
existingGrad.add(round(e.crease*100))
else:
e.crease = 0 #remove bevel if no entry in bevelToResMap was found
mapEntryToRemove = set()
for entry in obj['creaseToGradMap']:
if not int(entry) in existingGrad:
mapEntryToRemove.add(entry)
for entry in mapEntryToRemove:
obj['creaseToGradMap'].pop(entry)
creaseToGradMap = obj['creaseToGradMap']
foundGrad = False
for creaseInt in creaseToGradMap:
if creaseToGradMap[creaseInt] == grad: # previously used grading - reuse!
crease = int(creaseInt)
foundGrad = True
if not foundGrad:
allEntries = set(range(1,101)) #all possible bevel entries
newEntry = min(list(allEntries.difference(existingGrad)))
creaseToGradMap[str(newEntry)] = grad # create a new entry in map
crease = newEntry
for e in obj.data.edges:
if e.select == True:
e.crease = crease/100.
e.use_seam = use_seam
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class OBJECT_OT_FindBroken(bpy.types.Operator):
'''Detect blocks and mark unused edges'''
bl_idname = "find.broken"
bl_label = "Diagnose"
def execute(self, context):
from . import utils
import imp
imp.reload(utils)
from . import blender_utils
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
obj = context.active_object
verts = list(blender_utils.vertices_from_mesh(obj))
edges = list(blender_utils.edges_from_mesh(obj))
refEdges = list(blender_utils.edges_from_mesh(obj))
log, block_print_out, dependent_edges, face_info, all_edges, faces_as_list_of_nodes = utils.blockFinder(edges, verts, '','', [])
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(False,True,False)")
for e in obj.data.edges:
e.select = True
def edgeFinder(v0, v1, edgeList):
if [v0, v1] in edgeList:
return edgeList.index([v0, v1])
if [v1, v0] in edgeList:
return edgeList.index([v1, v0])
return -1
edgeOrder = [[0,1], [1,2], [2,3], [0,3], [4,5], [5,6], [6,7], [4,7], [0,4], [1,5], [2,6], [3,7]]
for vl in block_print_out:
for e in edgeOrder:
v0 = vl[e[0]]
v1 = vl[e[1]]
obj.data.edges[edgeFinder(v0, v1, refEdges)].select = False
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class OBJECT_OT_RepairFaces(bpy.types.Operator):
'''Delete internal face and create boundary faces'''
bl_idname = "repair.faces"
bl_label = "Repair"
c = EnumProperty(
items = [('wall', 'wall', 'Defines the patch as wall'),
('patch', 'patch', 'Defines the patch as generic patch'),
('empty', 'empty', 'Defines the patch as empty'),
('symmetryPlane', 'symmetryPlane', 'Defines the patch as symmetryPlane'),
],
name = "Patch type")
def execute(self, context):
from . import utils
import imp
imp.reload(utils)
from . import blender_utils
removeInternal = bpy.context.scene.removeInternal
createBoundary = bpy.context.scene.createBoundary
if not createBoundary and not removeInternal:
self.report({'INFO'}, "Repair: Nothing to do!")
return{'CANCELLED'}
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
obj = context.active_object
verts = list(blender_utils.vertices_from_mesh(obj))
edges = list(blender_utils.edges_from_mesh(obj))
disabled = []
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)")
for group in obj.vertex_groups:
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
if group.name == 'disabled':
bpy.ops.object.vertex_group_set_active(group=group.name)
bpy.ops.object.vertex_group_select()
bpy.ops.object.mode_set(mode='OBJECT')
vlist = []
for v in obj.data.vertices:
if v.select == True:
disabled += [v.index]
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
nRemoved, nCreated = utils.repairFaces(edges, verts, disabled, obj, removeInternal, createBoundary)
self.report({'INFO'}, "Created {} boundary faces and removed {} internal faces".format(nCreated, nRemoved))
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.invoke_props_dialog(self, width=200)
return {'RUNNING_MODAL'}
def draw(self, context):
scn = context.scene
obj = context.object
nPatches = obj.material_slots.__len__()
self.layout.prop(scn, "removeInternal")
self.layout.prop(scn, "createBoundary")
self.layout.label("Assign new faces to patch")
self.layout.template_list("MATERIAL_UL_matslots", "", obj, "material_slots", obj, "active_material_index", rows=nPatches)
class OBJECT_OT_GetPatch(bpy.types.Operator):
'''Click to select faces belonging to this patch'''
bl_idname = "set.getpatch"
bl_label = "Get patch"
whichPatch = StringProperty()
def execute(self, context):
scn = context.scene
obj = context.active_object
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(False,False,True)")
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
mat = bpy.data.materials[self.whichPatch]
patchindex = list(obj.data.materials).index(mat)
obj.active_material_index = patchindex
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.material_slot_select()
scn.bcTypeEnum = mat['patchtype']
scn.patchName = self.whichPatch
return {'FINISHED'}
class OBJECT_OT_createPreview(bpy.types.Operator):
'''Creates a mesh preview as a separate object from selected vertices'''
bl_idname = "create.preview"
bl_label = "Preview"
def execute(self, context):
if context.scene.setEdges:
try:
bpy.data.objects[context.scene.geoobjName]
except:
self.report({'INFO'}, "Cannot find object for edges!")
return{'CANCELLED'}
import locale
from . import utils
import imp, math
imp.reload(utils)
from . import blender_utils
locale.setlocale(locale.LC_ALL, '')
scn = context.scene
obj = context.active_object
bpy.ops.object.mode_set(mode='OBJECT') #update
bpy.ops.object.mode_set(mode='EDIT')
verts = list(blender_utils.vertices_from_mesh(obj))
edges = list(blender_utils.edges_from_mesh(obj))
toShow = [0 for i in range(len(verts))] # A block is previewed if all vertices are selected
allOff = True
for vid in range(len(verts)):
if obj.data.vertices[vid].select:
toShow[vid] = 1
allOff = False
if allOff: # All vertices were unselected - proceed with previewing all blocks
toShow = [1 for i in range(len(verts))]
disabled = []
bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)")
for group in obj.vertex_groups:
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
if group.name == 'disabled':
bpy.ops.object.vertex_group_set_active(group=group.name)
bpy.ops.object.vertex_group_select()
bpy.ops.object.mode_set(mode='OBJECT')
vlist = []
for v in obj.data.vertices:
if v.select == True:
disabled += [v.index]
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
if not allOff:
for vid, v in enumerate(obj.data.vertices): #restore selection
if toShow[vid]:
v.select = True
forcedEdges = []
for e in obj.data.edges:
if e.bevel_weight >= 0.001:
N = obj['bevelToResMap'][str(round(e.bevel_weight*100))]
forcedEdges.append([[e.vertices[0],e.vertices[1]], N])
gradedEdges = []
for e in obj.data.edges:
if e.crease == 0:
grad = 1
else:
grad = obj['creaseToGradMap'][str(round(e.crease*100))]
gradedEdges.append([[e.vertices[0],e.vertices[1]], grad, e.use_seam])
bpy.ops.object.mode_set(mode='OBJECT')
obj.select = False
if scn.setEdges:
polyLines, polyLinesPoints, lengths = getPolyLines(verts, edges, obj)
else:
polyLinesPoints = []
lengths = [[], []]
dx0 = scn.resFloat
effective_lengths = [[], []]
for e in edges:
if e in lengths[0]:
ind = lengths[0].index(e)