-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoperators.py
3569 lines (2830 loc) · 135 KB
/
operators.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 os
import bpy
import colorsys
import bmesh
import bgl, blf, bpy, mathutils, time, copy, math, re
from .utils import next_power_of_2, previous_power_of_2
from bpy.props import *
import bpy
from bpy.types import Operator
from .utils import (find_brush, create_image_plane_from_image, create_matching_camera,\
switch_to_camera_view, get_image_from_selected_object, \
move_object_to_collection, export_uv_layout, \
set_camera_background_image, get_active_image_from_image_editor, \
save_incremental_copy,paint_view_color_management_settings, \
multi_texture_paint_view,single_texture_paint_view, get_active_image_size, \
get_active_texture_node_image_size,create_new_texture_node_with_size, \
rgb_to_hex, complementary_color, split_complementary_colors,\
triadic_colors, tetradic_colors, analogous_colors, create_palette, \
new_convert_curve_object,convert_gpencil_to_curve,move_trace_objects_to_collection, \
convert_image_plane_to_curve, is_canvas_mesh, create_compositor_node_tree,\
render_and_extract_image,calculate_texel_density, create_scene_based_on_active_image,\
select_object_by_suffix, update_texture_settings, copy_photostack_nodes_to_compositor, \
find_selected_texture_nodes, get_image_from_photostack_group)
from bpy.types import Operator, Menu, Panel, UIList
from bpy_extras.io_utils import ImportHelper
#new Trace2Curve makes the leap from image plane to gpencil to curve
class D2P_OT_Trace2Curve(bpy.types.Operator):
"""Convert B&W Image Plane to Curve"""
bl_idname = "d2p.trace2curve"
bl_label = "Convert Image Plane to Curve"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
selected_objects = context.selected_objects
if selected_objects:
convert_image_plane_to_curve(selected_objects[0])
return {'FINISHED'}
else:
self.report({'WARNING'}, "No object selected.")
return {'CANCELLED'}
# new image texture node sized to same as active
class D2P_OT_NewTextureNode(bpy.types.Operator):
bl_idname = "node.new_texture_node"
bl_label = "New Texture Node from Active Texture"
def execute(self, context):
width, height = get_active_texture_node_image_size()
if width and height:
create_new_texture_node_with_size(width, height)
return {'FINISHED'}
else:
self.report({'WARNING'}, "No active texture node with an image found")
return {'CANCELLED'}
# new image dialog autofilled with size from active image in image editor
class D2P_OT_GetImageSizeOperator(bpy.types.Operator):
bl_idname = "image.get_image_size"
bl_label = "New Image from Active Image Size"
width: bpy.props.IntProperty()
height: bpy.props.IntProperty()
def invoke(self, context, event):
width, height = get_active_image_size()
if width and height:
self.width = width
self.height = height
context.window_manager.invoke_props_dialog(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "No active image found")
return {'CANCELLED'}
def draw(self, context):
layout = self.layout
layout.prop(self, "width")
layout.prop(self, "height")
def execute(self, context):
bpy.ops.image.new(name="New Image", width=self.width, height=self.height)
return {'FINISHED'}
# Operator to set single texture paint view
class D2P_OT_SetSingleTexturePaintView(bpy.types.Operator):
bl_idname = "view3d.set_single_texture_paint_view"
bl_label = "Set Single Texture Paint View"
def execute(self, context):
single_texture_paint_view()
context.scene.view_mode = 'SINGLE'
return {'FINISHED'}
# Operator to set multi texture paint view
class D2P_OT_SetMultiTexturePaintView(bpy.types.Operator):
bl_idname = "view3d.set_multi_texture_paint_view"
bl_label = "Set Multi Texture Paint View"
def execute(self, context):
multi_texture_paint_view()
context.scene.view_mode = 'MULTI'
return {'FINISHED'}
class D2P_OT_UV2Mask(bpy.types.Operator):
"""New Mask Object from UV Map of Subject"""
bl_description = "New Mask Object from UV Map of Subject"
bl_idname = "object.uv_mask_from_selected_object"
bl_label = "Generate UV Mask Object from Selected Object"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
selected_objects = context.selected_objects
if not selected_objects:
return False
selected_object = selected_objects[0]
# Check if 'subject_view' collection exists
if 'subject_view' not in bpy.data.collections:
return False
# Check if the object with the same name and suffix '_UVObj' already exists in 'mask_objects' collection
object_name_with_suffix = selected_object.name + '_UVObj'
if 'mask_objects' in bpy.data.collections:
mask_objects_collection = bpy.data.collections['mask_objects']
if object_name_with_suffix in mask_objects_collection.objects:
return False
return True
def execute(self, context):
selected_objects = context.selected_objects
if not selected_objects:
self.report({'WARNING'}, "No selected objects found.")
return {'CANCELLED'}
selected_object = selected_objects[0]
if not selected_object.data.uv_layers:
self.report({'WARNING'}, "Please Create UV Layer")
return {'CANCELLED'}
C = bpy.context
ob = selected_object # Use the selected object
size = 4.095675
def create_mesh_from_data(name, verts, faces):
# Create mesh and object
me = bpy.data.meshes.new(name + 'Mesh')
new_ob = bpy.data.objects.new(name, me)
new_ob.show_name = True
# Link object to scene and make active
C.view_layer.active_layer_collection.collection.objects.link(new_ob)
C.view_layer.objects.active = new_ob
new_ob.select_set(True)
# Create mesh from given verts, faces
me.from_pydata(verts, [], faces)
# Update mesh with new data
me.update()
return new_ob
out_verts = []
out_faces = []
for face in ob.data.polygons:
oface = []
for vert, loop in zip(face.vertices, face.loop_indices):
uv = ob.data.uv_layers.active.data[loop].uv
out_verts.append((uv.x * size, uv.y * size, 0))
oface.append(loop)
out_faces.append(oface)
new_obj = create_mesh_from_data(ob.name + '_UVObj', out_verts, out_faces)
# Show wire on the new object
new_obj.show_wire = True
# Enter Edit Mode to remove duplicate vertices
with bpy.context.temp_override(active_object=new_obj, selected_objects=[new_obj]):
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.remove_doubles()
bpy.ops.object.mode_set(mode='OBJECT')
# Deselect all objects
bpy.ops.object.select_all(action='DESELECT')
# Find the canvas object by suffix
canvas_obj = None
for obj in bpy.data.objects:
if obj.name.endswith('_canvas'):
canvas_obj = obj
break
if canvas_obj:
# Select the canvas object
canvas_obj.select_set(True)
context.view_layer.objects.active = canvas_obj
# Update the context to ensure the active object is set
bpy.context.view_layer.update()
# Use temp_override for mode switching
with bpy.context.temp_override(active_object=canvas_obj, selected_objects=[canvas_obj]):
# Enter Edit Mode for the canvas object
bpy.ops.object.mode_set(mode='EDIT')
# Get the active mesh
bm = bmesh.from_edit_mesh(canvas_obj.data)
# Ensure the lookup table is up to date
bm.verts.ensure_lookup_table()
# Identify the lower left vertex (default is Vertex 0)
lower_left_vertex = bm.verts[0]
# Switch to Object Mode temporarily
bpy.ops.object.mode_set(mode='OBJECT')
# Access the mesh vertices in Object Mode
verts = canvas_obj.data.vertices
# Get the coordinates of the lower left vertex (Vertex 0)
lower_left_vertex_co = verts[0].co
# Snap the cursor to this vertex
bpy.context.scene.cursor.location = lower_left_vertex_co
print(f"Cursor snapped to lower left vertex: {lower_left_vertex_co}")
# Select the new UV mask object
new_obj.select_set(True)
context.view_layer.objects.active = new_obj
# Move the new object to the cursor's location
new_obj.location = bpy.context.scene.cursor.location
new_obj.location.z += 0.25 # Move up Z by 0.25
new_obj.parent = canvas_obj # Make it a child of canvas object
# Adopt the material of the selected object
if selected_object.data.materials:
new_obj.data.materials.append(selected_object.data.materials[0]) # Copy material from selected object
# Ensure 'canvas_view' collection exists
if 'canvas_view' not in bpy.data.collections:
canvas_view_collection = bpy.data.collections.new('canvas_view')
bpy.context.scene.collection.children.link(canvas_view_collection)
else:
canvas_view_collection = bpy.data.collections['canvas_view']
# Ensure 'mask_objects' collection exists within 'canvas_view'
if 'mask_objects' not in bpy.data.collections:
mask_objects_collection = bpy.data.collections.new('mask_objects')
canvas_view_collection.children.link(mask_objects_collection)
else:
mask_objects_collection = bpy.data.collections['mask_objects']
# Add new object to 'mask_objects' collection
if new_obj.name not in mask_objects_collection.objects:
mask_objects_collection.objects.link(new_obj)
bpy.context.view_layer.active_layer_collection.collection.objects.unlink(new_obj)
else:
self.report({'WARNING'}, "Canvas object with suffix '_canvas' not found.")
return {'CANCELLED'}
return {'FINISHED'}
class D2P_OT_Subject2Canvas(bpy.types.Operator):
"""New Canvas and Camera from Selected Subject"""
bl_description = "New Canvas and Camera from Selected Subject"
bl_idname = "object.canvas_and_camera_from_selected_object"
bl_label = "Generate Image Plane and Camera from Selected Object"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return 'subject_view' not in bpy.data.collections or 'canvas_view' not in bpy.data.collections
def execute(self, context):
selected_objects = context.selected_objects
if not selected_objects:
self.report({'WARNING'}, "No selected objects found.")
return {'CANCELLED'}
selected_object = selected_objects[0]
if not selected_object.data.uv_layers:
self.report({'WARNING'}, "Please Create UV Layer")
return {'CANCELLED'}
# Rename object with suffix _subject
selected_object.name += '_subject'
# Create new scene and link the object, using the active image if possible
create_scene_based_on_active_image(selected_object)
# Ensure the object is active and selected in the new scene context
new_scene = bpy.context.window.scene # The newly created scene from create_scene_based_on_active_image
selected_object = new_scene.objects.get(selected_object.name)
if selected_object is None:
self.report({'ERROR'}, "Selected object could not be found in the new scene.")
return {'CANCELLED'}
# Make the object active and selected in the new scene
new_scene.view_layers[0].objects.active = selected_object
selected_object.select_set(True)
# Move object to 'subject_view' collection
move_object_to_collection(selected_object, 'subject_view')
# Export UV layout
uv_filepath = os.path.join("C:/tmp", selected_object.name + ".png")
export_uv_layout(selected_object, uv_filepath)
# Retrieve the active image or fallback to the "_photostack" group node if none
active_image = get_image_from_selected_object(selected_object)
if not active_image:
active_image = get_image_from_photostack_group(selected_object)
if not active_image:
self.report({'WARNING'}, "No active image or group image found in '_photostack' node.")
return {'CANCELLED'}
# Create the image plane and camera based on the retrieved image
image_plane_obj, width, height = create_image_plane_from_image(active_image)
if not image_plane_obj:
self.report({'WARNING'}, "Failed to create image plane.")
return {'CANCELLED'}
camera_obj = create_matching_camera(image_plane_obj, width, height)
# Move camera and image plane to 'canvas_view' collection
move_object_to_collection(image_plane_obj, 'canvas_view')
move_object_to_collection(camera_obj, 'canvas_view')
try:
set_camera_background_image(camera_obj, uv_filepath)
except Exception as e:
self.report({'ERROR'}, str(e))
return {'CANCELLED'}
# Switch to camera view
switch_to_camera_view(camera_obj)
# Toggle canvas_view collection visibility
bpy.ops.object.toggle_collection_visibility()
return {'FINISHED'}
class D2P_OT_Image2CanvasPlus(bpy.types.Operator):
"""Create Canvas and Camera from Active Image In Image Editor"""
bl_description = "Create Canvas and Camera from Active Image In Image Editor"
bl_idname = "image.canvas_and_camera"
bl_label = "Generate Image Plane and Matching Camera from Image Editor"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
active_image = None
for area in bpy.context.screen.areas:
if area.type == 'IMAGE_EDITOR':
active_image = area.spaces.active.image
break
if not active_image:
self.report({'WARNING'}, "No active image found.")
return {'CANCELLED'}
# Create new scene based on the image editor's active image (no object needed)
create_scene_based_on_active_image() # No selected object is passed here
# Switch to 3D view
bpy.context.area.ui_type = 'VIEW_3D'
# Create image plane and matching camera
image_plane_obj, width, height = create_image_plane_from_image(active_image)
if not image_plane_obj:
self.report({'WARNING'}, "Failed to create image plane.")
return {'CANCELLED'}
camera_obj = create_matching_camera(image_plane_obj, width, height)
bpy.context.view_layer.objects.active = camera_obj
camera_obj.data.show_name = True
# Move camera and image plane to 'canvas_view' collection
move_object_to_collection(image_plane_obj, active_image.name + '_canvas_view')
move_object_to_collection(camera_obj, active_image.name + '_canvas_view')
# Switch to camera view (inside the 3D View context)
switch_to_camera_view(camera_obj)
# Switch back to Image Editor
bpy.context.area.ui_type = 'IMAGE_EDITOR'
return {'FINISHED'}
class D2P_OT_ToggleUV2Camera(bpy.types.Operator):
"""Toggle UV Image Visibility in Camera"""
bl_description = "Toggle UV Image Visibility in Camera"
bl_idname = "object.toggle_uv_image_visibility"
bl_label = "Toggle UV Image Visibility in Camera"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll (clas, context):
return is_canvas_mesh(context.object)
def execute(self, context):
cam = context.scene.camera
if cam and cam.data.background_images:
# Assume the first background image is the one we want to toggle
bg = cam.data.background_images[0]
bg.show_background_image = not bg.show_background_image
return {'FINISHED'}
else:
self.report({'WARNING'}, "No background image found on the active camera.")
return {'CANCELLED'}
class D2P_OT_ToggleCollectionView(bpy.types.Operator):
"""Toggle 3D or 2D Collection"""
bl_description = "Toggle 3D or 2D Collection"
bl_idname = "object.toggle_collection_visibility"
bl_label = "Toggle Collection Visibility"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
subject_view = bpy.data.collections.get("subject_view")
canvas_view = bpy.data.collections.get("canvas_view")
if subject_view and canvas_view:
if subject_view.hide_viewport:
subject_view.hide_viewport = False
subject_view.hide_render = False
canvas_view.hide_viewport = True
canvas_view.hide_render = True
# Switch to front view
bpy.ops.view3d.view_axis(type='FRONT', align_active=True)
#bpy.context.space_data.shading.type = 'MATERIAL'
select_object_by_suffix('_subject')
else:
subject_view.hide_viewport = True
subject_view.hide_render = True
canvas_view.hide_viewport = False
canvas_view.hide_render = False
# Switch to camera view
switch_to_camera_view(context.scene.camera)
#bpy.context.space_data.shading.type = 'SOLID'
#bpy.context.space_data.shading.light = 'FLAT'
select_object_by_suffix('_canvas')
# Update the view layer to reflect visibility changes
bpy.context.view_layer.update()
return {'FINISHED'}
else:
self.report({'WARNING'}, "One or both collections not found.")
return {'CANCELLED'}
class D2P_OT_holdout_shader(bpy.types.Operator):
bl_label = "Mask Holdout Shader"
bl_idname = "d2p.add_holdout"
@classmethod
def poll(self, context):
obj = context.active_object
A = obj is not None
if A:
B = obj.type == 'CURVE' or 'MESH'
return B
def execute(self, context):
mask = bpy.data.materials.new(name="Holdout Mask")
mask.use_nodes = True
bpy.context.object.active_material = mask
mask = bpy.data.materials.new(name="Holdout Mask")
mask.use_nodes = True
bpy.context.object.active_material = mask
###output node new
material_output = bpy.context.active_object.active_material.node_tree.\
nodes.get('Material Output')
# Principled Main Shader in Tree
principled_node = mask.node_tree.nodes.get('Principled BSDF')
mask.node_tree.nodes.remove(principled_node)
###Tex Coordinate Node
hold = mask.node_tree.nodes.new('ShaderNodeHoldout')
hold.location = (-100, 0)
hold.label = ("Holdout Mask")
#####LINKING
link = mask.node_tree.links.new
link(hold.outputs[0], material_output.inputs[0])
return {'FINISHED'}
class D2P_OT_CanvasMaterial(bpy.types.Operator):
"""Adopt Canvas Material"""
bl_idname = "d2p.canvas_material"
bl_label = "Set the Material to the same as Main Canvas"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
obj = context.active_object
return obj is not None and obj.type in {'MESH', 'CURVE'} and context.mode in {'OBJECT', 'PAINT_TEXTURE'}
def execute(self, context):
scene = context.scene
suffix = '_canvas'
match_object_name = None
# Find the object with the specified suffix
for obj in scene.objects:
if obj.name.endswith(suffix):
match_object_name = obj.name
break
if match_object_name:
print(f"Object with suffix '{suffix}' found: {match_object_name}")
# Get the material from the matching object
canvas_object = bpy.data.objects.get(match_object_name)
if canvas_object and canvas_object.material_slots:
canvas_material = canvas_object.material_slots[0].material
# Assign the material to the active object if not already present
active_obj = context.active_object
material_names = [mat.name for mat in active_obj.data.materials]
if canvas_material.name not in material_names:
active_obj.data.materials.append(canvas_material)
print(f"Material '{canvas_material.name}' added to the active object.")
else:
print(f"Material '{canvas_material.name}' already assigned to the object.")
else:
self.report({'WARNING'}, f"Object '{match_object_name}' has no materials.")
else:
self.report({'WARNING'}, f"No object with suffix '{suffix}' found in the scene.")
return {'FINISHED'}
class D2P_OT_Copy2Eraser(bpy.types.Operator):
"""Duplicate Selected Image Plane, Single User for Eraser Paint"""
bl_idname = "d2p.sculpt_duplicate"
bl_label = "Sculpt Liquid Duplicate"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_canvas_mesh(context.object)
def execute(self, context):
scene = context.scene
bpy.ops.paint.texture_paint_toggle()
bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked": False, "mode": 'TRANSLATION'},
TRANSFORM_OT_translate={"value": (0, 0, 0),
"orient_type": 'GLOBAL',
"orient_matrix": ((1, 0, 0), (0, 1, 0), (0, 0, 1)),
"orient_matrix_type": 'GLOBAL',
"constraint_axis": (False, False, False),
"mirror": False,
"use_proportional_edit": False,
"proportional_edit_falloff": 'SMOOTH',
"proportional_size": 1,
"use_proportional_connected": False,
"use_proportional_projected": False,
"snap": False,
"snap_target": 'CLOSEST',
"snap_point": (0, 0, 0),
"snap_align": False,
"snap_normal": (0, 0, 0),
"gpencil_strokes": False,
"cursor_transform": False,
"texture_space": False,
"remove_on_cancel": False,
"view2d_edge_pan": False,
"release_confirm": False,
"use_accurate": False,
"use_automerge_and_split": False})
bpy.ops.transform.translate(value=(0, 0, 0.1))
bpy.ops.view3d.localview()
bpy.ops.paint.texture_paint_toggle()
# make ERASER brush or use existing
# might need fixing for 4.3 version
try:
context.tool_settings.image_paint.brush = bpy.data.brushes["Eraser"]
except KeyError:
context.tool_settings.image_paint.brush = bpy.data.brushes["TexDraw"]
bpy.ops.brush.add()
bpy.data.brushes["TexDraw.001"].name = "Eraser"
bpy.data.brushes["Eraser"].use_pressure_strength = False
bpy.data.brushes["Eraser"].blend = 'ERASE_ALPHA'
# make individual of material AND of image reference inside
sel = bpy.context.active_object
mat = sel.material_slots[0].material
sel.material_slots[0].material = mat.copy()
material = sel.material_slots[0].material
node = material.node_tree.nodes['Image Texture']
new_image = node.image.copy()
node.image = new_image
return {'FINISHED'}
class D2P_OT_LiquidSculpt(bpy.types.Operator):
"""Convert to Subdivided Plane & Sculpt Liquid"""
bl_idname = "d2p.sculpt_liquid"
bl_label = "Sculpt like Liquid"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_canvas_mesh(context.object)
def execute(self, context):
scene = context.scene
bpy.ops.paint.texture_paint_toggle()
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.subdivide(number_cuts=100, smoothness=0)
bpy.ops.mesh.subdivide(number_cuts=2, smoothness=0)
bpy.ops.sculpt.sculptmode_toggle()
bpy.ops.paint.brush_select(sculpt_tool='GRAB', create_missing=False)
scene.tool_settings.sculpt.use_symmetry_x = False
bpy.ops.view3d.localview()
return {'FINISHED'}
class D2P_OT_CanvasX(bpy.types.Operator):
"""Flip the Canvas Left/Right"""
bl_idname = "d2p.canvas_horizontal"
bl_label = "Canvas Horizontal"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_canvas_mesh(context.object)
def execute(self, context):
scene = context.scene
layer = bpy.context.view_layer
layer.update()
# toggle texture mode / object mode
bpy.ops.paint.texture_paint_toggle()
scene = bpy.context.scene
original_area = bpy.context.area.type
# toggle edit mode
bpy.ops.object.editmode_toggle()
#####select all mesh
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='SELECT')
####change editor to UV Editor
bpy.context.area.ui_type = 'UV'
# + select the uvs
bpy.ops.uv.select_all(action='SELECT')
bpy.ops.uv.select_all(action='SELECT')
######scale -1 on axis
bpy.ops.transform.resize(value=(-1, 1, 1),
orient_type='GLOBAL',
orient_matrix=((1, 0, 0), (0, 1, 0),
(0, 0, 1)),
orient_matrix_type='GLOBAL',
constraint_axis=(True, False, False),
mirror=True, use_proportional_edit=False,
proportional_edit_falloff='SMOOTH',
proportional_size=1,
use_proportional_connected=False,
use_proportional_projected=False)
# back to Object mode
bpy.ops.object.editmode_toggle()
#####return to original window editor
bpy.context.area.type = original_area
bpy.ops.paint.texture_paint_toggle()
return {'FINISHED'}
class D2P_OT_CanvasY(bpy.types.Operator):
"""Flip the Canvas Top/Bottom"""
bl_idname = "d2p.canvas_vertical"
bl_label = "Canvas Vertical"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return is_canvas_mesh(context.object)
def execute(self, context):
scene = context.scene
layer = bpy.context.view_layer
layer.update()
# toggle texture mode / object mode
bpy.ops.paint.texture_paint_toggle()
scene = bpy.context.scene
original_area = bpy.context.area.type
# toggle edit mode
bpy.ops.object.editmode_toggle()
#####select all mesh
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='SELECT')
####change editor to UV Editor
bpy.context.area.ui_type = 'UV'
# + select the uvs
bpy.ops.uv.select_all(action='SELECT')
bpy.ops.uv.select_all(action='SELECT')
######scale -1 on axis
bpy.ops.transform.resize(value=(1, -1, 1),
orient_type='GLOBAL',
orient_matrix=((1, 0, 0), (0, 1, 0),
(0, 0, 1)),
orient_matrix_type='GLOBAL',
constraint_axis=(True, False, False),
mirror=True, use_proportional_edit=False,
proportional_edit_falloff='SMOOTH',
proportional_size=1,
use_proportional_connected=False,
use_proportional_projected=False)
# back to Object mode
bpy.ops.object.editmode_toggle()
#####return to original window editor
bpy.context.area.type = original_area
bpy.ops.paint.texture_paint_toggle()
return {'FINISHED'}
class D2P_OT_CanvasReset(bpy.types.Operator):
"""Reset Canvas Rotation"""
bl_idname = "d2p.canvas_resetrot"
bl_label = "Canvas Reset Rotation"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(self, context):
obj = context.active_object
if obj is not None:
A = obj.type == 'MESH'
B = context.mode == 'PAINT_TEXTURE'
return A and B
def execute(self, context):
scene = context.scene
layer = bpy.context.view_layer
layer.update()
# reset canvas rotation
bpy.ops.object.rotation_clear()
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS',
center='MEDIAN')
return {'FINISHED'}
class D2P_OT_PixelsToBorder(bpy.types.Operator):
""" Convert the pixel value into the proportion needed
by the Blender native property """
bl_idname = "d2p.pixelstoborder"
bl_label = "Convert Pixels to Border proportion"
@classmethod
def poll(cls, context):
return True
def execute(self, context):
C = bpy.context
X = C.scene.render.resolution_x
Y = C.scene.render.resolution_y
C.scene.render.border_min_x = C.scene.x_min_pixels / X
C.scene.render.border_max_x = C.scene.x_max_pixels / X
C.scene.render.border_min_y = C.scene.y_min_pixels / Y
C.scene.render.border_max_y = C.scene.y_max_pixels / Y
if C.scene.x_min_pixels > X:
C.scene.x_min_pixels = X
if C.scene.x_max_pixels > X:
C.scene.x_max_pixels = X
if C.scene.y_min_pixels > Y:
C.scene.y_min_pixels = Y
if C.scene.y_max_pixels > Y:
C.scene.y_max_pixels = Y
return {'FINISHED'}
class D2P_OT_BorderToPixels(bpy.types.Operator):
""" Convert the Blender native property value to pixels"""
bl_idname = "d2p.bordertopixels"
bl_label = "Convert border values to pixels"
@classmethod
def poll(cls, context):
return True
def execute(self, context):
C = bpy.context
X = C.scene.render.resolution_x
Y = C.scene.render.resolution_y
C.scene.x_min_pixels = int(C.scene.render.border_min_x * X)
C.scene.x_max_pixels = int(C.scene.render.border_max_x * X)
C.scene.y_min_pixels = int(C.scene.render.border_min_y * Y)
C.scene.y_max_pixels = int(C.scene.render.border_max_y * Y)
return {'FINISHED'}
class D2P_OT_BorderCrop(bpy.types.Operator):
"""Turn on Border Crop in Render Settings"""
bl_description = "Border Crop ON"
bl_idname = "d2p.border_crop"
bl_label = ""
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
rs = context.scene.render
rs.use_border = True
rs.use_crop_to_border = True
return {'FINISHED'}
class D2P_OT_BorderUnCrop(bpy.types.Operator):
"""Turn off Border Crop in Render Settings"""
bl_description = "Border Crop OFF"
bl_idname = "d2p.border_uncrop"
bl_label = ""
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
rs = context.scene.render
rs.use_border = False
rs.use_crop_to_border = False
return {'FINISHED'}
class D2P_OT_BorderCropToggle(bpy.types.Operator):
"""Set Border Crop in Render Settings"""
bl_description = "Border Crop On/Off TOGGLE"
bl_idname = "d2p.border_toggle"
bl_label = ""
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(self, context):
return poll_apt(self, context)
def execute(self, context):
scene = context.scene
rs = context.scene.render
if not (scene.prefs_are_locked):
if rs.use_border and rs.use_crop_to_border:
bpy.ops.d2p.border_uncrop()
scene.bordercrop_is_activated = False
else:
bpy.ops.d2p.border_crop()
scene.bordercrop_is_activated = True
return {'FINISHED'}
class D2P_OT_Image2Scene(bpy.types.Operator):
"""IMAGE EDITOR FOR CREATING NEW BLANK CANVAS IMAGE"""
bl_idname = "d2p.new_image"
bl_label = "New Image"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
scene = context.scene
layer = bpy.context.view_layer
layer.update()
# Call user prefs window
bpy.ops.screen.userpref_show('INVOKE_DEFAULT')
#bpy.ops.wm.window_new()
# Change area type
area = context.window_manager.windows[-1].screen.areas[0]
area.type = 'IMAGE_EDITOR'
return {'FINISHED'}
class D2P_OT_SaveImage(bpy.types.Operator): # works IF image is already in Slot2Display prior
"""Save Image"""
bl_idname = "d2p.save_current"
bl_label = "Save Image Current"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(self, context):
obj = context.active_object
if obj is not None:
A = obj.type == 'MESH'
B = context.mode == 'PAINT_TEXTURE'
return A and B
def execute(self, context):
scene = context.scene
layer = bpy.context.view_layer
layer.update()
original_type = bpy.context.area.type
bpy.context.area.type = 'IMAGE_EDITOR'
# SAVE CHANGES MADE TO IMAGE
bpy.ops.image.save()
bpy.context.area.type = original_type
return {'FINISHED'}
class D2P_OT_SaveIncrem(bpy.types.Operator): #works already with Material and Image IF image is opened in Editor prior
"""Save Incremential Images - MUST SAVE SESSION FILE FIRST"""
bl_description = ""
bl_idname = "d2p.save_increm"
bl_label = "Save incremential Image Current"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(self, context):
obj = context.active_object
if obj is not None:
A = obj.type == 'MESH'
B = context.mode == 'PAINT_TEXTURE'
return A and B
####new code
def execute(self, context):
try:
image = get_active_image_from_image_editor()
save_incremental_copy(image)
self.report({'INFO'}, "Incremental copy saved.")
except ValueError as e:
self.report({'ERROR'}, str(e))
return {'FINISHED'}
class D2P_OT_SaveDirty(bpy.types.Operator): #Already Good for Image and Material
"""Save All Modified Images or Pack if Unsaved"""
bl_description = "Save all modified images or pack them if unsaved"
bl_idname = "d2p.save_dirty"
bl_label = "Save All Modified Images or Pack if Unsaved"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
obj = context.active_object
if obj is not None:
A = obj.type == 'MESH'
B = context.mode == 'PAINT_TEXTURE'
return A and B
return False
def execute(self, context):
# Save or pack all modified images
for image in bpy.data.images: #already packs all in Image and Material modes
if image.is_dirty:
if image.filepath:
try:
image.save()
self.report({'INFO'}, f"Saved image: {image.name}")
except Exception as e: