-
Notifications
You must be signed in to change notification settings - Fork 39
/
__init__.py
1457 lines (1235 loc) · 54.3 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
import bpy, bmesh, math, re, json, string, os, platform, subprocess
from bpy.props import IntProperty, FloatProperty, StringProperty, BoolProperty, EnumProperty, FloatVectorProperty, BoolVectorProperty, PointerProperty
from mathutils import Vector, Euler, Quaternion, Matrix, Color
from random import random
from functools import reduce
# @Globals
app = {
"items": [],
"first_run": True,
"vertex_colors": [
(247, 241, 176),
(246, 212, 180),
(252, 202, 206),
(241, 192, 232),
(207, 186, 240),
(163, 196, 243),
(144, 219, 244),
(152, 245, 225),
(185, 251, 192),
(163, 240, 173),
],
}
if __name__ == '__main__':
# For development purposes when running the script directly in Blender:
addon_directory = '/Users/passivestar/Files/blender/addons/quickmenu/'
else:
addon_directory = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
nodes_path = os.path.join(addon_directory, 'nodetools.blend')
config_path = os.path.join(addon_directory, 'config.json')
# @Util
def select(obj):
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
def get_selected_non_active():
objects = [o for o in bpy.context.selected_objects if o != bpy.context.object]
return objects[0] if len(objects) == 1 else None
def get_selection_and_active_indices():
selected_indeces = []
active_indeces = []
mesh = bpy.context.active_object.data
bm = bmesh.from_edit_mesh(mesh)
if not mesh.vertex_colors: mesh.vertex_colors.new()
for face in [face for face in bm.faces if face.select]:
for loop in face.loops:
selected_indeces.append(loop.index)
if face == bm.faces.active: active_indeces.append(loop.index)
return (selected_indeces, active_indeces)
def grid_snap(grid, value):
return round(value / grid) * grid
def view_vector(left_to_right = False, use_object_transform = True):
view_matrix = bpy.context.space_data.region_3d.view_matrix
object_matrix = bpy.context.object.matrix_world if bpy.context.object else Matrix()
if use_object_transform:
if bpy.context.mode == 'POSE':
matrix = view_matrix @ object_matrix @ bpy.context.active_pose_bone.matrix
else: matrix = view_matrix @ object_matrix
else:
matrix = view_matrix
return (Vector((-1, 0, 0) if left_to_right else (0, 0, 1)) @ matrix).normalized()
def view_snapped_vector(left_to_right = False, use_object_transform = True):
vec = view_vector(left_to_right, use_object_transform)
biggest = max(abs(n) for n in vec)
for i in range(len(vec)): vec[i] = grid_snap(1, vec[i]) if abs(vec[i]) == biggest else 0
return vec
def axis_by_vector(vector):
axes = ['X', 'Y', 'Z']
for i in range(3):
if vector[i] == 1:
return axes[i], False
elif vector[i] == -1:
return axes[i], True
def cursor_to_selected(to_active = False):
ts = bpy.context.scene.tool_settings
previous_context = bpy.context.area.type
bpy.context.area.type = 'VIEW_3D'
previous_pivot = ts.transform_pivot_point
ts.transform_pivot_point = 'BOUNDING_BOX_CENTER'
if to_active:
bpy.ops.view3d.snap_cursor_to_active()
else:
bpy.ops.view3d.snap_cursor_to_selected()
ts.transform_pivot_point = previous_pivot
bpy.context.area.type = previous_context
def execute_in_mode(mode, callback, *args):
previous_mode = 'EDIT' if is_in_editmode() else bpy.context.mode
bpy.ops.object.mode_set(mode=mode)
result = callback(*args)
try: bpy.ops.object.mode_set(mode=previous_mode)
except: pass
return result
def make_vertex_group(name, assign=True):
bpy.context.object.vertex_groups.new(name=name)
bpy.ops.object.vertex_group_set_active(group=name)
if assign: bpy.ops.object.vertex_group_assign()
def modifier_exists(modifier_type, name = None):
if name is None:
return len([m for m in bpy.context.object.modifiers if m.type == modifier_type]) > 0
else:
return len([m for m in bpy.context.object.modifiers if m.type == modifier_type and m.name == name]) > 0
def get_modifier(modifier_type, name):
if name is None:
return [m for m in bpy.context.object.modifiers if m.type == modifier_type][0]
else:
return [m for m in bpy.context.object.modifiers if m.type == modifier_type and m.name == name][0]
def move_modifier_on_top(modifier_name):
bpy.ops.object.modifier_move_to_index(modifier=modifier_name, index=0)
def add_modifier(modifier_type):
bpy.ops.object.modifier_add(type=modifier_type)
return bpy.context.object.modifiers[-1]
def add_or_get_modifier(modifier_type, move_on_top=False):
if modifier_exists(modifier_type):
for modifier in bpy.context.object.modifiers:
if modifier.type == modifier_type:
return modifier
bpy.ops.object.modifier_add(type=modifier_type)
modifier = bpy.context.object.modifiers[-1]
if move_on_top: move_modifier_on_top(modifier.name)
return modifier
def geonode_modifier_exists(node_group_name):
return len([m for m in bpy.context.object.modifiers if m.type == 'NODES' and m.node_group is not None and m.node_group.name == node_group_name]) > 0
def add_geonode_modifier(node_group_name):
bpy.ops.object.modifier_add(type='NODES')
modifier = bpy.context.object.modifiers[-1]
modifier.node_group = bpy.data.node_groups[node_group_name]
return modifier
def add_or_get_geonode_modifier(node_group_name):
if geonode_modifier_exists(node_group_name):
for modifier in bpy.context.object.modifiers:
if modifier.type == 'NODES' and modifier.node_group.name == node_group_name:
return modifier
bpy.ops.object.modifier_add(type='NODES')
modifier = bpy.context.object.modifiers[-1]
modifier.node_group = bpy.data.node_groups[node_group_name]
return modifier
def remove_geonode_modifier(node_group_name):
if geonode_modifier_exists(node_group_name):
for modifier in bpy.context.object.modifiers:
if modifier.type == 'NODES' and modifier.node_group.name == node_group_name:
bpy.context.object.modifiers.remove(modifier)
break
def is_in_editmode():
return bpy.context.mode == 'EDIT_MESH' or bpy.context.mode == 'EDIT_CURVE' or bpy.context.mode == 'EDIT_SURFACE' or bpy.context.mode == 'EDIT_METABALL' or bpy.context.mode == 'EDIT_TEXT' or bpy.context.mode == 'EDIT_ARMATURE'
def anything_is_selected_in_editmode():
for o in bpy.context.objects_in_mode:
if o.type == 'MESH':
if True in [v.select for v in bmesh.from_edit_mesh(o.data).verts]:
return True
elif o.type == 'CURVE':
for spline in o.data.splines:
for p in spline.bezier_points:
if p.select_control_point:
return True
return False
def anything_is_hidden_in_editmode():
for o in bpy.context.objects_in_mode:
if True in [v.hide for v in bmesh.from_edit_mesh(o.data).verts]:
return True
return False
def snake_to_title_case(string):
return ''.join([s.title() for s in string.split('_')])
def nodes_were_loaded():
# If any node starting with 'QM ' exists, assume nodes were loaded
for n in bpy.data.node_groups:
if n.name.startswith('QM '):
return True
return False
# @MenuOperators
class QuickMenuOperator(bpy.types.Operator):
"""Quick Menu"""
bl_idname, bl_label, bl_options = 'qm.quick_menu', 'Quick Menu Operator', {'REGISTER', 'UNDO'}
def execute(self, context):
# Inject cursor
bpy.ops.qm.set_cursor_rotation_to_view()
# Unload geometry nodes on first run to make sure nodes are updated
# when you update the addon
if app['first_run']:
unload_geometry_nodes()
# Load geometry nodes if not yet loaded
if not nodes_were_loaded():
load_geometry_nodes()
app['first_run'] = False
bpy.ops.wm.call_menu(name=QuickMenu.bl_idname)
return {'FINISHED'}
class EditMenuItemsOperator(bpy.types.Operator):
"""Edit Menu Items"""
bl_idname, bl_label = 'qm.edit_items', 'Edit Menu Items Operator'
def execute(self, context):
if platform.system() == 'Darwin': # macOS
subprocess.call(('open', config_path))
elif platform.system() == 'Windows': # Windows
os.startfile(config_path)
else: # linux variants
subprocess.call(('xdg-open', config_path))
return {'FINISHED'}
class ReloadMenuItemsOperator(bpy.types.Operator):
"""Reload Menu Items"""
bl_idname, bl_label = 'qm.load_items', 'Reload Menu Items Operator'
def execute(self, context):
load_items(config_path)
return {'FINISHED'}
# @Operators
class JoinSeparateOperator(bpy.types.Operator):
"""Join or Separate"""
bl_idname, bl_label, bl_options = 'qm.join_separate', 'Separate / Join', {'REGISTER', 'UNDO'}
reset_origin: BoolProperty(name='Reset Origin on Separate', default=True)
reset_drivers: BoolProperty(name='Reset Drivers on Separate', default=True)
@classmethod
def poll(cls, context):
if is_in_editmode() and not anything_is_selected_in_editmode():
return False
return True
def execute(self, context):
if is_in_editmode():
if anything_is_selected_in_editmode():
if context.object.type == 'CURVE':
bpy.ops.curve.separate()
elif context.object.type == 'MESH':
bpy.ops.mesh.separate(type='SELECTED')
bpy.ops.object.editmode_toggle()
select(context.selected_objects[-1])
if self.reset_origin: bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
if self.reset_drivers:
bpy.ops.qm.clear_drivers()
elif len(context.selected_objects) > 0:
bpy.ops.object.join()
return {'FINISHED'}
class SetSmoothOperator(bpy.types.Operator):
"""Set Smooth Shading. Hold shift to use modifier"""
bl_idname, bl_label, bl_options = 'qm.smooth', 'Set Smooth', {'REGISTER', 'UNDO'}
smooth: BoolProperty(name='Smooth', default=True)
by_angle: BoolProperty(name='By Angle', default=True)
angle: FloatProperty(name='Angle', subtype='ANGLE', default=0.872665, step=2, min=0, max=1.5708)
use_modifier: BoolProperty(name='Use Modifier', default=True)
def invoke(self, context, event):
if event.shift: self.use_modifier = True
return self.execute(context)
def execute(self, context):
if self.use_modifier:
if self.smooth:
m = add_or_get_geonode_modifier('Smooth by Angle')
m['Input_1'] = self.angle
m['Socket_1'] = True
else:
remove_geonode_modifier('Smooth by Angle')
else:
remove_geonode_modifier('Smooth by Angle')
def fn():
if self.smooth:
if self.by_angle:
try:
bpy.ops.object.shade_smooth_by_angle(angle=self.angle)
bpy.ops.mesh.customdata_custom_splitnormals_add()
except : bpy.ops.object.shade_smooth(use_auto_smooth=True, auto_smooth_angle=self.angle)
else: bpy.ops.object.shade_smooth()
else:
bpy.ops.object.shade_flat()
execute_in_mode('OBJECT', fn)
return {'FINISHED'}
class LocalViewOperator(bpy.types.Operator):
"""Local View"""
bl_idname, bl_label, bl_options = 'qm.local_view', 'Local View', {'REGISTER', 'UNDO'}
def execute(self, context):
if is_in_editmode():
if anything_is_hidden_in_editmode(): bpy.ops.mesh.reveal(select=False)
elif anything_is_selected_in_editmode(): bpy.ops.mesh.hide(unselected=True)
else: bpy.ops.view3d.localview()
return {'FINISHED'}
class SetOriginOperator(bpy.types.Operator):
"""Set origin to geometry center or selection. Hold shift to set origin to bottom"""
bl_idname, bl_label, bl_options = 'qm.set_origin', 'Set Origin', {'REGISTER', 'UNDO'}
type: EnumProperty(name='Type', items=(
('GEOMETRY', 'Geometry', 'Origin To Geometry'),
('BOTTOM', 'Bottom', 'Origin To Bottom')
))
def invoke(self, context, event):
if event.shift: self.type = 'BOTTOM'
return self.execute(context)
def execute(self, context):
if self.type == 'GEOMETRY':
if is_in_editmode() and anything_is_selected_in_editmode():
cursor_to_selected()
fn = lambda: bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='BOUNDS')
else:
fn = lambda: bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
elif self.type == 'BOTTOM':
def fn():
objects = context.selected_objects
for obj in objects:
select(obj)
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
new_origin = Vector((0, 0, -obj.dimensions.z / 2))
obj.data.transform(Matrix.Translation(-new_origin))
obj.location += new_origin
for obj in objects: obj.select_set(True)
execute_in_mode('OBJECT', fn)
return {'FINISHED'}
class ProportionalEditingOperator(bpy.types.Operator):
"""Toggle Proportional Editing"""
bl_idname, bl_label, bl_options = 'qm.proportional_editing', 'Proportional Editing', {'REGISTER', 'UNDO'}
falloff: EnumProperty(name='Type', default='SMOOTH', items=(
('SMOOTH', 'Smooth', 'Smooth falloff'),
('SPHERE', 'Sphere', 'Sphere falloff'),
('ROOT', 'Root', 'Root falloff'),
('INVERSE_SQUARE', 'Inverse Square', 'Inverse Square falloff'),
('SHARP', 'Sharp', 'Sharp falloff'),
('LINEAR', 'Linear', 'Linear falloff'),
('CONSTANT', 'Constant', 'Constant falloff'),
('RANDOM', 'Random', 'Random falloff'),
))
connected: BoolProperty(name='Connected', default = True)
def execute(self, context):
ts = context.scene.tool_settings
if context.mode != 'OBJECT':
ts.use_proportional_connected = self.connected
if ts.proportional_edit_falloff == self.falloff and not self.options.is_repeat:
ts.use_proportional_edit = not ts.use_proportional_edit
self.report({'INFO'}, 'Proportional Editing: ' + ('On' if ts.use_proportional_edit else 'Off'))
else:
ts.use_proportional_edit = True
ts.proportional_edit_falloff = self.falloff
else:
ts.use_proportional_connected = self.connected
if ts.proportional_edit_falloff == self.falloff and not self.options.is_repeat:
ts.use_proportional_edit_objects = not ts.use_proportional_edit_objects
self.report({'INFO'}, 'Proportional Editing: ' + ('On' if ts.use_proportional_edit_objects else 'Off'))
else:
ts.use_proportional_edit_objects = True
ts.proportional_edit_falloff = self.falloff
return {'FINISHED'}
class WireframeOperator(bpy.types.Operator):
"""Toggle Wireframe"""
bl_idname, bl_label, bl_options = 'qm.wireframe', 'Wireframe', {'REGISTER', 'UNDO'}
opacity: FloatProperty(name='Opacity', default=0.75, min=0, max=1)
def execute(self, context):
ol = context.space_data.overlay
if not self.options.is_repeat:
ol.show_wireframes = not ol.show_wireframes
self.report({'INFO'}, 'Wireframe: ' + ('On' if ol.show_wireframes else 'Off'))
context.space_data.overlay.wireframe_opacity = self.opacity
return {'FINISHED'}
class RotateOperator(bpy.types.Operator):
"""Rotate. Hold shift to invert angle"""
bl_idname, bl_label, bl_options = 'qm.rotate', 'Rotate', {'REGISTER', 'UNDO'}
angle: FloatProperty(name='Angle', subtype='ANGLE', default=1.5708)
def invoke(self, context, event):
if event.shift: self.angle = -abs(self.angle)
return self.execute(context)
def execute(self, context):
axis, negative = axis_by_vector(view_snapped_vector(False, False))
value = -self.angle if negative else self.angle
bpy.ops.transform.rotate(value=value, orient_axis=axis, orient_type='GLOBAL')
return {'FINISHED'}
class CorrectAttributesOperator(bpy.types.Operator):
"""Toggle Correct Face Attributes"""
bl_idname, bl_label, bl_options = 'qm.correct_attributes', 'Toggle Correct Face Attributes', {'REGISTER', 'UNDO'}
def execute(self, context):
ts = bpy.context.scene.tool_settings
ts.use_transform_correct_face_attributes = not ts.use_transform_correct_face_attributes
self.report({'INFO'}, 'Correct Face Attributes: ' + ('On' if ts.use_transform_correct_face_attributes else 'Off'))
return {'FINISHED'}
class ClearModifiersOperator(bpy.types.Operator):
"""Clear Modifiers"""
bl_idname, bl_label, bl_options = 'qm.clear_modifiers', 'Clear Modifiers', {'REGISTER', 'UNDO'}
def execute(self, context):
for obj in context.selected_objects:
obj.modifiers.clear()
return {'FINISHED'}
class SelectRingOperator(bpy.types.Operator):
"""Select ring. Hold shift to select loop"""
bl_idname, bl_label, bl_options = 'qm.select_ring', 'Select Ring Or Loop', {'REGISTER', 'UNDO'}
select_loop: BoolProperty(name='Select Loop', default=False)
@classmethod
def poll(cls, context):
return is_in_editmode()
def invoke(self, context, event):
self.select_loop = event.shift
return self.execute(context)
def execute(self, context):
bpy.ops.mesh.loop_multi_select(ring=not self.select_loop)
return {'FINISHED'}
class SelectMoreOperator(bpy.types.Operator):
"""Select more. Hold shift to select less"""
bl_idname, bl_label, bl_options = 'qm.select_more', 'Select More Or Less', {'REGISTER', 'UNDO'}
select_less: BoolProperty(name='Select Less', default=False)
@classmethod
def poll(cls, context):
return is_in_editmode()
def invoke(self, context, event):
self.select_less = event.shift
return self.execute(context)
def execute(self, context):
if self.select_less: bpy.ops.mesh.select_less()
else: bpy.ops.mesh.select_more()
return {'FINISHED'}
class RegionToLoopOperator(bpy.types.Operator):
"""Convert Region To Loop Or Loop To Region"""
bl_idname, bl_label, bl_options = 'qm.region_to_loop', 'Region To Loop', {'REGISTER', 'UNDO'}
select_bigger: BoolProperty(name='Loop To Region Bigger', default = False)
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
mode = tuple(context.scene.tool_settings.mesh_select_mode).index(True)
if mode == 1:
bpy.ops.mesh.loop_to_region(select_bigger=self.select_bigger)
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
elif mode == 2:
bpy.ops.mesh.region_to_loop()
return {'FINISHED'}
class MirrorOperator(bpy.types.Operator):
"""Mirror"""
bl_idname, bl_label, bl_options = 'qm.mirror', 'Mirror', {'REGISTER', 'UNDO'}
axis: BoolVectorProperty(name='Axis', subtype='XYZ')
bisect_flip: BoolVectorProperty(name='Bisect Flip', subtype='XYZ')
@classmethod
def poll(cls, context):
return len(context.selected_objects) > 0
def draw(self, context):
l = self.layout
l.row().prop(self.properties, 'axis', toggle=1)
l.row().prop(self.properties, 'bisect_flip', toggle=1)
def execute(self, context):
if modifier_exists('MIRROR'):
m = add_or_get_modifier('MIRROR')
fn = lambda: bpy.ops.object.modifier_apply(modifier=m.name)
execute_in_mode('OBJECT', fn)
return {'FINISHED'}
m = add_or_get_modifier('MIRROR', move_on_top=True)
m.use_axis[0], m.show_on_cage = False, True
vsv = view_snapped_vector(True)
vsv_notransform = view_snapped_vector(True, False)
axis, negative = axis_by_vector(vsv)
if not self.options.is_repeat:
index = ['x', 'y', 'z'].index(axis.lower())
self.axis[index] = self.bisect_flip[index] = True
self.bisect_flip[index] = negative
for i in range(3):
m.use_axis[i] = m.use_bisect_axis[i] = self.axis[i]
m.use_bisect_flip_axis[i] = self.bisect_flip[i]
return {'FINISHED'}
class ArrayOperator(bpy.types.Operator):
"""Array"""
bl_idname, bl_label, bl_options = 'qm.array', 'Array', {'REGISTER', 'UNDO'}
count: IntProperty(name='Count', default=3, step=1, min=0)
offset: FloatProperty(name='Offset', default=1.1)
@classmethod
def poll(cls, context):
return len(context.selected_objects) > 0
def execute(self, context):
v = view_snapped_vector() * self.offset
v.negate()
a = add_or_get_modifier('ARRAY')
a.count = self.count
a.relative_offset_displace = v
return {'FINISHED'}
class ConvertToMeshOperator(bpy.types.Operator):
"""Convert To Mesh"""
bl_idname, bl_label, bl_options = 'qm.convert_to_mesh', 'Convert To Mesh', {'REGISTER', 'UNDO'}
close_strokes: BoolProperty(name='GPencil Close Strokes', default=True)
dissolve_angle: FloatProperty(name='GPencil Dissolve Angle', subtype='ANGLE', step=5, default=0.261799, min=0, max=1.5708)
doubles_threshold: FloatProperty(name='GPencil Doubles Threshold', default=0.02, min=0)
@classmethod
def poll(cls, context):
return context.object != None
def execute(self, context):
if len(context.selected_objects) == 0:
return {'FINISHED'}
def fn():
if context.active_object.type == 'GPENCIL':
original = context.active_object
if self.close_strokes:
bpy.ops.object.mode_set(mode='EDIT_GPENCIL')
previous_context = context.area.type
context.area.type = 'VIEW_3D'
bpy.ops.gpencil.select_all(action='SELECT')
bpy.ops.gpencil.stroke_cyclical_set(type='CLOSE', geometry=True)
bpy.ops.gpencil.stroke_flip()
context.area.type = previous_context
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.gpencil.convert(type='POLY', use_timing_data=False)
new = get_selected_non_active()
select(original)
bpy.ops.object.delete()
select(new)
bpy.ops.object.convert(target='MESH')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.remove_doubles(threshold=0.005)
bpy.ops.mesh.dissolve_limited(angle_limit=self.dissolve_angle)
bpy.ops.mesh.remove_doubles(threshold=self.doubles_threshold)
else:
bpy.ops.object.convert(target='MESH')
execute_in_mode('OBJECT', fn)
return {'FINISHED'}
class SubsurfOperator(bpy.types.Operator):
"""Subsurf"""
bl_idname, bl_label, bl_options = 'qm.subsurf', 'Subsurf', {'REGISTER', 'UNDO'}
level: IntProperty(name='Level', default=2, min=0, soft_max=5)
def execute(self, context):
if context.mode != 'SCULPT':
m = add_or_get_modifier('SUBSURF')
m.levels, m.boundary_smooth = self.level, 'PRESERVE_CORNERS'
else:
m = add_or_get_modifier('MULTIRES')
bpy.ops.object.multires_subdivide(modifier=m.name, mode='CATMULL_CLARK')
m.levels = min(m.sculpt_levels, self.level)
return {'FINISHED'}
class BevelOperator(bpy.types.Operator):
"""Bevel"""
bl_idname, bl_label, bl_options = 'qm.bevel', 'Bevel', {'REGISTER', 'UNDO'}
amount: FloatProperty(name='Amount', default=0.1, step=0.1, min=0)
segments: IntProperty(name='Segments', default=4, min=0, soft_max=12)
angle: FloatProperty(name='Angle', subtype='ANGLE', default=0.785398, min=0, max=3.141593)
use_weight: BoolProperty(name='Use Weight', default=False)
harden_normals: BoolProperty(name='Harden Normals', default=True)
loop_slide: BoolProperty(name='Loop Slide', default=False)
use_clamp_overlap: BoolProperty(name='Clamp Overlap', default=True)
def execute(self, context):
existed = modifier_exists('BEVEL')
b = add_or_get_modifier('BEVEL')
if not existed: b.miter_outer = 'MITER_ARC'
b.limit_method = 'WEIGHT' if self.use_weight else 'ANGLE'
b.width, b.segments, b.angle_limit, b.harden_normals, b.loop_slide, b.use_clamp_overlap = self.amount, self.segments, self.angle, self.harden_normals, self.loop_slide, self.use_clamp_overlap
return {'FINISHED'}
class TriangulateOperator(bpy.types.Operator):
"""Triangulate"""
bl_idname, bl_label, bl_options = 'qm.triangulate', 'Triangulate', {'REGISTER', 'UNDO'}
keep_normals: BoolProperty(name='Keep Normals', default=True)
def execute(self, context):
existed = modifier_exists('TRIANGULATE')
t = add_or_get_modifier('TRIANGULATE')
if not existed:
t.keep_custom_normals = self.keep_normals
t.min_vertices = 5
return {'FINISHED'}
class StraightenUVsOperator(bpy.types.Operator):
"""Straighten UVs"""
bl_idname, bl_label, bl_options = 'qm.straighten_uvs', 'Straighten UVs', {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
mesh = context.object.data
selection_indeces, active_indeces = execute_in_mode('EDIT', get_selection_and_active_indices)
# Show an error if nothing is selected
if len(selection_indeces) == 0:
self.report({'ERROR'}, 'Nothing is selected')
return {'FINISHED'}
# Show an error if nothing is active
if len(active_indeces) == 0:
self.report({'ERROR'}, 'Nothing is active. Please make sure you have an active face')
return {'FINISHED'}
def process_uvs():
# Reorder active indices to ensure clockwise order
active_uv = mesh.uv_layers.active.data
center_x = sum(active_uv[i].uv.x for i in active_indeces) / len(active_indeces)
center_y = sum(active_uv[i].uv.y for i in active_indeces) / len(active_indeces)
active_indeces.sort(key=lambda i: math.atan2(active_uv[i].uv.y - center_y, active_uv[i].uv.x - center_x) % (2 * math.pi))
# Align UV vertices for the active quad
prev_uv_coords = first_axis = None
for iteration_index, index in enumerate([*active_indeces, active_indeces[0]]):
uv_coords = mesh.uv_layers.active.data[index].uv
if prev_uv_coords:
if first_axis == None:
diff = uv_coords - prev_uv_coords
diff_abs = [abs(diff.x), abs(diff.y)]
min_axis = diff_abs.index(min(diff_abs))
first_axis = min_axis
else:
min_axis = (first_axis + iteration_index + 1) % 2
uv_coords[min_axis] = prev_uv_coords[min_axis]
prev_uv_coords = uv_coords
execute_in_mode('OBJECT', process_uvs)
bpy.ops.uv.follow_active_quads()
return {'FINISHED'}
class MarkSeamOperator(bpy.types.Operator):
"""Mark Or Clear Seam. Hold shift to clear seam"""
bl_idname, bl_label, bl_options = 'qm.mark_seam', 'Mark Seam', {'REGISTER', 'UNDO'}
clear_inner_region: BoolProperty(name='Clear Inner Region', default=False)
clear: BoolProperty(name='Clear', default=False)
unwrap: BoolProperty(name='Unwrap', default=True)
@classmethod
def poll(cls, context):
return is_in_editmode()
def invoke(self, context, event):
if event.shift: self.clear = True
return self.execute(context)
def execute(self, context):
if self.unwrap:
unwrap_previous_value = bpy.context.scene.tool_settings.use_edge_path_live_unwrap
bpy.context.scene.tool_settings.use_edge_path_live_unwrap = True
if self.clear:
bpy.ops.mesh.mark_seam(clear=True)
if self.unwrap:
bpy.context.scene.tool_settings.use_edge_path_live_unwrap = unwrap_previous_value
return {'FINISHED'}
mode = tuple(context.scene.tool_settings.mesh_select_mode).index(True)
if self.clear_inner_region: bpy.ops.mesh.mark_seam(clear=True)
if mode == 1: bpy.ops.mesh.mark_seam()
elif mode == 2:
bpy.ops.mesh.region_to_loop()
bpy.ops.mesh.mark_seam()
bpy.ops.mesh.loop_to_region()
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
if self.unwrap:
bpy.context.scene.tool_settings.use_edge_path_live_unwrap = unwrap_previous_value
return {'FINISHED'}
class SmartUVProject(bpy.types.Operator):
"""Smart UV Project"""
bl_idname, bl_label, bl_options = 'qm.smart_uv_project', 'Smart UV Project', {'REGISTER', 'UNDO'}
angle: FloatProperty(name='Angle', subtype='ANGLE', default=1.0472, min=0.0001, max=3.14159)
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
bpy.ops.uv.smart_project(angle_limit=self.angle)
bpy.ops.uv.seams_from_islands()
return {'FINISHED'}
class TransformUVsOperator(bpy.types.Operator):
"""Transform UV"""
bl_idname, bl_label, bl_options = 'qm.transform_uvs', 'Transform UVs', {'REGISTER', 'UNDO'}
offset_x: FloatProperty(name='Offset X', default=0, step=0.1)
offset_y: FloatProperty(name='Offset Y', default=0, step=0.1)
rotation: FloatProperty(name='Rotation', subtype='ANGLE', default=0, soft_min=-3.14159, soft_max=3.14159)
scale_x: FloatProperty(name='Scale X', default=1, step=0.1, soft_min=0)
scale_y: FloatProperty(name='Scale Y', default=1, step=0.1, soft_min=0)
@classmethod
def poll(cls, context):
return is_in_editmode() and anything_is_selected_in_editmode()
def execute(self, context):
me = bpy.context.edit_object.data
bm = bmesh.from_edit_mesh(me)
uv_layer = bm.loops.layers.uv.verify()
uvs = []
for face in bm.faces:
if face.select:
center = face.calc_center_median()
for loop in face.loops:
uvs.append(loop[uv_layer])
center = reduce(lambda a, b: a + b, [uv.uv for uv in uvs]) / len(uvs)
for uv in uvs:
if self.offset_x or self.offset_y:
uv.uv += Vector( (self.offset_x, self.offset_y) )
if self.rotation:
rotation_matrix = Matrix.Rotation(self.rotation, 2)
offset_uv = uv.uv - center
offset_uv.rotate(rotation_matrix)
uv.uv = center + offset_uv
if self.scale_x != 1 or self.scale_y != 1:
uv.uv = center + Vector(uv.uv - center) * Vector((self.scale_x, self.scale_y))
bmesh.update_edit_mesh(me)
return {'FINISHED'}
class SetVertexColorOperator(bpy.types.Operator):
"""Set Vertex Color"""
bl_idname, bl_label, bl_options = 'qm.set_vertex_color', 'Set Vertex Color', {'REGISTER', 'UNDO'}
color: FloatVectorProperty(name='Color', subtype='COLOR', min=0, max=1)
set_to_active: BoolProperty(name='Set To Active', default = False)
reset_index: BoolProperty(name='Reset Index', default = False)
@classmethod
def poll(cls, context):
return is_in_editmode()
def invoke(self, context, event):
if event.shift: self.reset_index = True
return self.execute(context)
def execute(self, context):
context.space_data.shading.color_type = 'VERTEX'
# Reset index
if self.reset_index:
context.scene.quick_menu.vertex_color_index = 0
# Generate next unique RGB
if not self.set_to_active and not self.options.is_repeat:
i = context.scene.quick_menu.vertex_color_index
# If index is in colors range, use it
vertex_colors = app['vertex_colors']
if i < len(vertex_colors):
values = tuple([c / 255 for c in vertex_colors[i]])
# Else pick next unique one
else:
values = (
1 - (i * 3 % 10) / 10,
1 - ((i * 3 // 10) % 10) / 10,
1 - ((i * 3 // 10) % 10) / 10
)
next_color = Color()
next_color.r = values[0]
next_color.g = values[1]
next_color.b = values[2]
self.report({'INFO'}, 'Vertex Color Index: ' + str(i))
context.scene.quick_menu.vertex_color_index += 1
# Track if we already set color from active so that we can copy between meshes:
initial_active = context.active_object
for obj in context.objects_in_mode:
mesh = obj.data
context.view_layer.objects.active = obj
selection_indeces, active_indeces = execute_in_mode('EDIT', get_selection_and_active_indices)
def assign_colors():
# Set color to the next random color:
if self.set_to_active:
if obj == initial_active:
if len(active_indeces) > 0 and mesh.vertex_colors.active:
self.color = list(mesh.vertex_colors.active.data[active_indeces[0]].color)[:3]
else: self.color = (1, 1, 1)
elif not self.options.is_repeat:
self.color = next_color
# Set the color of selection
for index in selection_indeces:
mesh.vertex_colors.active.data[index].color = (self.color[0], self.color[1], self.color[2], 1)
execute_in_mode('OBJECT', assign_colors)
return {'FINISHED'}
class SelectByVertexColorOperator(bpy.types.Operator):
"""Select By Vertex Color"""
bl_idname, bl_label, bl_options = 'qm.select_by_vertex_color', 'Select By Vertex Color', {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
context.space_data.shading.color_type = 'VERTEX'
selected_colors = []
# Gather all of the selected colors across all of the objects first
for obj in context.objects_in_mode:
context.view_layer.objects.active = obj
selection_indeces, active_indeces = execute_in_mode('EDIT', get_selection_and_active_indices)
def fn():
for index in selection_indeces:
selected_colors.append(obj.data.vertex_colors.active.data[index].color)
execute_in_mode('OBJECT', fn)
# Set selection
for obj in context.objects_in_mode:
mesh = obj.data
context.view_layer.objects.active = obj
selection_indeces, active_indeces = execute_in_mode('EDIT', get_selection_and_active_indices)
def fn():
for poly in mesh.polygons:
poly.select = False
for index in poly.loop_indices:
c = mesh.vertex_colors.active.data[index].color
for sc in selected_colors:
if c[0] == sc[0] and c[1] == sc[1] and c[2] == sc[2]:
poly.select = True
continue
execute_in_mode('OBJECT', fn)
return {'FINISHED'}
class BooleanOperator(bpy.types.Operator):
"""Boolean"""
bl_idname, bl_label, bl_options = 'qm.boolean', 'Boolean', {'REGISTER', 'UNDO'}
operation: EnumProperty(name='Operation', items=(
('DIFFERENCE', 'Difference', 'Difference'),
('UNION', 'Union', 'Union'),
('INTERSECT', 'Intersect', 'Intersect')
))
solver: EnumProperty(name='Solver', default='EXACT', items=(
('FAST', 'Fast', 'Fast'),
('EXACT', 'Exact', 'Exact'),
))
boundary_extend: FloatProperty(name='Boundary Extend', default=0.0001, min=0)
use_self: BoolProperty(name='Self', default=False)
recalculate_normals: BoolProperty(name='Recalculate Normals', default=True)
move_on_top: BoolProperty(name='Move Modifier On Top', default=True)
def execute(self, context):
if self.recalculate_normals and is_in_editmode(): bpy.ops.mesh.normals_make_consistent(inside=False)
if not self.use_self and self.boundary_extend > 0:
transform_pivot = context.scene.tool_settings.transform_pivot_point
context.scene.tool_settings.transform_pivot_point = 'INDIVIDUAL_ORIGINS'
val = 1 + self.boundary_extend
bpy.ops.transform.resize(value=(val, val, val))
context.scene.tool_settings.transform_pivot_point = transform_pivot
if is_in_editmode():
bpy.ops.mesh.intersect_boolean(operation=self.operation, solver=self.solver, use_self=self.use_self)
else:
active = context.object
objects = [o for o in context.selected_objects if o != active]
for obj in objects:
select(active)
bpy.ops.object.modifier_add(type='BOOLEAN')
boolean = context.object.modifiers[-1]
boolean.object = obj
boolean.object, boolean.operation, boolean.solver = obj, self.operation, self.solver
if self.move_on_top:
move_modifier_on_top(boolean.name)
select(obj)
context.object.display_type = 'BOUNDS'
context.object.hide_render = True
bpy.ops.object.select_all(action='DESELECT')
for obj in objects: obj.select_set(True)
return {'FINISHED'}
class PlaneIntersectOperator(bpy.types.Operator):
"""Plane Intersect"""
bl_idname, bl_label, bl_options = 'qm.plane_intersect', 'Plane Intersect', {'REGISTER', 'UNDO'}
mode: EnumProperty(name='Mode', default='ISLAND', items=(
('SELECTION', 'Selection', 'Selection'),
('ISLAND', 'Island', 'Island'),
('MESH', 'Whole Mesh', 'Whole Mesh')
))
snap_view_axis: BoolProperty(name='Snap View Axis', default = True)
active: BoolProperty(name='Active', default = True)
clear_outer: BoolProperty(name='Clear Outer', default = False)
clear_inner: BoolProperty(name='Clear Inner', default = False)
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
vector = view_snapped_vector(False, False) if self.snap_view_axis else view_vector(False, False)
cursor_to_selected(self.active)
if self.mode == 'ISLAND': bpy.ops.mesh.select_linked(delimit=set())
elif self.mode == 'MESH': bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.bisect(plane_co=context.scene.cursor.location, plane_no=vector, clear_outer=self.clear_outer, clear_inner=self.clear_inner)
return {'FINISHED'}
class ParentToNewEmptyOperator(bpy.types.Operator):
"""Parent To New Empty"""
bl_idname, bl_label, bl_options = 'qm.parent_to_new_empty', 'Parent To New Empty', {'REGISTER', 'UNDO'}
reset_transforms: BoolProperty(name='Reset Transforms', default=True)
def execute(self, context):
parent = context.object.parent
selection = context.selected_objects
bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.empty_add()
empty = context.object
for obj in selection:
obj.select_set(True)
if self.reset_transforms:
bpy.ops.object.parent_no_inverse_set()
else:
bpy.ops.object.parent_set()
if parent:
select(empty)
parent.select_set(True)
context.view_layer.objects.active = parent
bpy.ops.object.parent_set()
select(empty)
return {'FINISHED'}
class AddBoneOperator(bpy.types.Operator):
"""Add Bone"""
bl_idname, bl_label, bl_options = 'qm.add_bone', 'Add Bone', {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
cursor_to_selected()
bpy.ops.object.mode_set(mode='OBJECT')
active = context.object
active_bone_name = None
# If armature exists, add bone to it:
parent = context.object.parent
if parent and parent.type == 'ARMATURE':
select(parent)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.bone_primitive_add()
bpy.ops.armature.select_linked()
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)
active_bone_name = context.selected_bones[0].name
bpy.ops.object.mode_set(mode='OBJECT')
select(active)
bpy.ops.object.mode_set(mode='EDIT')
# Remove selected geometry from all existing vertex groups:
for group in active.vertex_groups:
bpy.ops.object.vertex_group_set_active(group=group.name)
bpy.ops.object.vertex_group_remove_from()
# Add to vertex group:
make_vertex_group(active_bone_name)
# Else if armature doesnt exist, create it: