-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjb-materialsharing.py
More file actions
347 lines (265 loc) · 11.1 KB
/
Copy pathjb-materialsharing.py
File metadata and controls
347 lines (265 loc) · 11.1 KB
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
# THE MATERIAL SHARING ADD-ON
#
# Initial release was developed and shared November 2023 by Johan Basberg.
#
# I hope you this will finally allow us all to easily share materials without
# having to resort to screenshots.
#
# Future feature: allow me to copy some nodes, not the entire material.
#
# Give me a shout-out on Twitter if you find it useful: @johanhwb
#
# Enjoy!
# Johan
bl_info = {
"author": "Johan Basberg",
"version": (0, 8, 0),
"name": "Material Sharing using JSON",
"blender": (2, 80, 0),
"category": "Material",
"location": "TopBar > Edit",
"description": "Copy & Paste materials as JSON. Visit https://matdb.org.",
}
import bpy
import json
import os
from mathutils import Vector, Euler
class BlenderEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bpy.types.bpy_prop_array):
return list(obj)
elif isinstance(obj, Vector):
return list(obj)
elif isinstance(obj, Euler):
return list(obj)
elif isinstance(obj, bpy.types.NodeFrame):
# Extract relevant data for NodeFrame
return obj.name
return super().default(obj)
class JB_MATERIALSHARING_OT_save_material_json_to_file(bpy.types.Operator):
bl_idname = "jb_materialsharing.save_material"
bl_label = "Save Material"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if context.active_object:
active_material = context.active_object.active_material
if active_material:
material_json = JB_MATERIALSHARING_OT_copy_material.material_to_json(self, active_material)
save_folder = context.scene.render.filepath
if material_json and os.path.isdir(save_folder):
# Specify an absolute path for the JSON file
json_file_path = save_folder + active_material.name + '.json'
# Dump the JSON data to the specified file path using the custom encoder
with open(json_file_path, "w") as json_file:
json.dump(material_json, json_file, indent=4, cls=BlenderEncoder)
self.report({'INFO'}, f"Material successfully saved to '{json_file_path}'")
else:
self.report({'WARNING'}, 'Invalid file path. Please update Scene Output folder.')
return {'CANCELLED'}
else:
self.report({'WARNING'}, 'No active material to copy: Please select an object and try again')
return {'FINISHED'}
class JB_MATERIALSHARING_OT_copy_material(bpy.types.Operator):
bl_idname = "jb_materialsharing.copy_material"
bl_label = "Copy Material"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
# Example: Convert the active material to JSON
if context.active_object:
active_material = context.active_object.active_material
if active_material:
material_json = self.material_to_json(active_material)
json_formatted = json.dumps(material_json, indent=4, cls=BlenderEncoder)
context.window_manager.clipboard = json_formatted
self.report({'INFO'}, 'Material successfully copied to clipboard.')
else:
self.report({'WARNING'}, 'No active material to copy: Please select an object and try again')
return {'FINISHED'}
def material_to_json(self, material):
# Check if the material uses nodes
if material.use_nodes:
node_tree = material.node_tree
nodes_data = []
is_selection = False
# Check if any nodes are selected
selected_nodes = [node for node in material.node_tree.nodes if node.select]
if selected_nodes:
nodes_to_copy = selected_nodes
is_selection = True
else:
nodes_to_copy = material.node_tree.nodes
# Iterate through the nodes in the node tree
for node in nodes_to_copy:
node_data = {
"name": node.name,
"label": node.label,
"type": node.bl_idname,
"parent": node.parent,
"hide": node.hide,
"location": (node.location.x, node.location.y),
"width": node.width,
}
if (node.bl_idname == "NodeFrame"):
# Frames have an initialised height
node_data["height"] = node.height # Only frames has a useful height
else:
# Material node has inputs and outputs, but height seem to always be 100.0
node_data["inputs"] = {}
node_data["outputs"] = {}
# Store information about inputs
for input_socket in node.inputs:
input_data = {
"links": [{"from_node": link.from_node.name, "from_socket": link.from_socket.name} for link in input_socket.links]
}
# Check if the socket is connected
if hasattr(input_socket, "default_value"):
input_data["default_value"] = input_socket.default_value
node_data["inputs"][input_socket.name] = input_data
# Store information about outputs
for output_socket in node.outputs:
output_data = {
"links": [{"to_node": link.to_node.name, "to_socket": link.to_socket.name} for link in output_socket.links]
}
# Check if the socket is connected
if hasattr(output_socket, "default_value"):
output_data["default_value"] = output_socket.default_value
node_data["outputs"][output_socket.name] = output_data
nodes_data.append(node_data)
material_data = {
"name": material.name,
"selection": is_selection,
"nodes": nodes_data
}
return material_data
else:
return None
class JB_MATERIALSHARING_OT_paste_material_from_clipboard(bpy.types.Operator):
bl_idname = "jb_materialsharing.paste_material_from_clipboard"
bl_label = "Paste Material"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
active_object = context.active_object
if active_object is not None and active_object.active_material is not None:
# Get the JSON string from the clipboard in Blender
json_string_from_clipboard = context.window_manager.clipboard
try:
# Attempt to parse JSON string representing material data
material_data_from_clipboard = json.loads(json_string_from_clipboard)
# Call the function to create material from the retrieved data
self.json_to_material(context, material_data_from_clipboard)
self.report({'INFO'}, 'Material was successfully pasted!')
return {'FINISHED'}
except json.JSONDecodeError:
# Handle the case where JSON parsing fails
self.report({'WARNING'}, 'Invalid material format on Clipboard')
return {'CANCELLED'}
except ValueError as ve:
self.report({'WARNING'}, f"Error creating material: {ve}")
return {'CANCELLED'}
except Exception as e:
self.report({'WARNING'}, f"Unexpected error: {e}")
return {'CANCELLED'}
else:
self.report({'WARNING'}, 'No active object or active material. Select an object with a material')
return {'CANCELLED'}
def json_to_material(self, context, material_data):
print("\nVisit https://matdb.org to copy paste more materials!\n")
if not isinstance(material_data, dict):
raise ValueError("Invalid material data. Expected a dictionary.")
# Check for the presence of required keys
required_keys = ["name", "nodes", "selection"]
for key in required_keys:
if key not in material_data:
raise ValueError(f"Invalid material format. Missing key '{key}' in material data.")
# Check if there's an active object with a material slot
if context.active_object and context.active_object.type == 'MESH' and context.active_object.material_slots:
data_type = "node selection"
if not material_data.get("selection", False):
# Since a complete material is being pasted,
# we clear nodes and rename the active material:
data_type = "full material"
context.active_object.active_material.node_tree.nodes.clear()
context.active_object.active_material.name = material_data.get("name", "Pasted Material")
material = context.active_object.active_material
nodes_data = material_data.get("nodes", [])
node_dict = {}
# Create nodes
print("\nRestoring", data_type, "from JSON:\nClipboard ontains", len(nodes_data) ,"nodes.\n")
for node_data in nodes_data:
node_type = node_data.get("type", "")
node_location = node_data.get("location", (0, 0))
# Use shader.new_node_tree instead of ops.node.add for shader nodes
new_node = material.node_tree.nodes.new(type=node_type)
new_node.location.x = node_location[0]
new_node.location.y = node_location[1]
new_node.name = node_data.get("name", "")
new_node.label = node_data.get("label", "")
new_node.width = node_data.get("width", "")
new_node.hide = node_data.get("hide", False)
print("Created new node:", new_node.label or new_node.name , "of type", node_type)
if (node_type == "NodeFrame"):
new_node.height = node_data.get("height", 100)
node_dict[new_node.name] = new_node
# Parent the nodes
print("Setting parents..")
for node_data in nodes_data:
node_name = node_data.get("name", "")
parent_node_name = node_data.get("parent")
if (parent_node_name):
parent_node = node_dict[parent_node_name]
if (parent_node != None):
node_dict[node_name].parent = parent_node
# Connect nodes
print("Connecting nodes..")
for node_data in nodes_data:
from_node_name = node_data.get("name", "")
from_node = node_dict[from_node_name]
for input_name, input_data in node_data.get("inputs", {}).items():
input_socket = from_node.inputs.get(input_name)
if input_socket:
for link_data in input_data.get("links", []):
to_node_name = link_data.get("from_node", "")
to_socket_name = link_data.get("from_socket", "")
to_node = node_dict.get(to_node_name)
if to_node:
to_socket = to_node.outputs.get(to_socket_name)
if to_socket:
bpy.context.active_object.active_material.node_tree.links.new(input_socket, to_socket)
# Set default values
for node_data in nodes_data:
node_name = node_data.get("name", "")
node = node_dict.get(node_name)
# Set default values for input sockets
for input_name, input_data in node_data.get("inputs", {}).items():
input_socket = node.inputs.get(input_name)
if input_socket:
default_value = input_data.get("default_value")
if default_value is not None:
input_socket.default_value = default_value
# Switch back to the 3D View context
# context.area.type = 'VIEW_3D'
else:
raise ValueError('No active object with material slots found')
classes = (
JB_MATERIALSHARING_OT_save_material_json_to_file,
JB_MATERIALSHARING_OT_copy_material,
JB_MATERIALSHARING_OT_paste_material_from_clipboard
)
def menu_func(self, context):
self.layout.separator()
self.layout.operator(JB_MATERIALSHARING_OT_save_material_json_to_file.bl_idname)
self.layout.separator()
self.layout.operator(JB_MATERIALSHARING_OT_copy_material.bl_idname)
self.layout.operator(JB_MATERIALSHARING_OT_paste_material_from_clipboard.bl_idname)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.TOPBAR_MT_edit.append(menu_func)
bpy.types.Scene.JB_MATERIALSHARING_copy_paste = bpy.props.StringProperty(default="")
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.TOPBAR_MT_edit.remove(menu_func)
del bpy.types.Scene.JB_MATERIALSHARING_copy_paste
if __name__ == "__main__":
register()