]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/material.py
Check the flat qualifier from the correct member
[libs/gl.git] / blender / io_mspgl / material.py
1 import os
2
3 def compute_render_method_hash(material):
4         descr = ""
5         for m in material.render_methods:
6                 if descr:
7                         descr += ","
8                 descr += "{}={}".format(m.tag, m.shader)
9         return hash(descr)
10
11 class PropertyNode:
12         def __init__(self, node_tree, node, socket):
13                 self.node_tree = node_tree
14                 self.node = node
15                 self.socket = socket
16                 self.type = None
17                 self.data = None
18                 self.input = None
19
20                 checks = [self.check_group,
21                         self.check_scale,
22                         self.check_tint,
23                         self.check_gray,
24                         self.check_extract,
25                         self.check_normal,
26                         self.check_invert_channels,
27                         self.check_additive_blend,
28                         self.check_texture]
29                 for c in checks:
30                         if c():
31                                 break
32
33         def set_input_from_linked(self, input_sock):
34                 from .util import get_linked_node_and_socket
35
36                 from_node, from_sock = get_linked_node_and_socket(self.node_tree, input_sock)
37                 self.input = PropertyNode(self.node_tree, from_node, from_sock)
38                 return self.input
39
40         def check_group(self):
41                 if self.node.type!='GROUP':
42                         return
43
44                 from .util import get_linked_node_and_socket
45
46                 output = self.node.node_tree.nodes["Group Output"]
47                 from_node, from_sock = get_linked_node_and_socket(self.node.node_tree, output.inputs[0])
48                 inner = PropertyNode(self.node.node_tree, from_node, from_sock)
49                 if inner.input:
50                         # TODO This currently only supports a single operation inside the group
51                         if inner.input.node.type=='GROUP_INPUT':
52                                 self.type = inner.type
53                                 self.data = inner.data
54                                 return self.set_input_from_linked(self.node.inputs[0])
55
56         def check_scale(self):
57                 if self.node.type!='MATH':
58                         return
59
60                 if self.node.operation=='MULTIPLY':
61                         for i in range(2):
62                                 if not self.node.inputs[i].is_linked:
63                                         self.type = 'SCALE'
64                                         self.data = self.node.inputs[i].default_value
65                                         return self.set_input_from_linked(self.node.inputs[1-i])
66
67         def check_tint(self):
68                 if self.node.type!='MIX_RGB':
69                         return
70
71                 if self.node.blend_type=='MULTIPLY':
72                         for i in range(2):
73                                 if not self.node.inputs[1+i].is_linked:
74                                         self.type = 'TINT'
75                                         self.data = self.node.inputs[1+i].default_value[:]
76                                         return self.set_input_from_linked(self.node.inputs[2-i])
77
78         def check_gray(self):
79                 if self.node.type=='RGBTOBW':
80                         self.type = 'GRAY'
81                         self.set_input_from_linked(self.node.inputs["Color"])
82
83         def check_extract(self):
84                 if self.node.type=='SEPRGB':
85                         self.type = 'EXTRACT'
86                         self.data = self.socket.name[0]
87                         return self.set_input_from_linked(self.node.inputs["Image"])
88
89         def check_normal(self):
90                 if self.node.type=='NORMAL_MAP':
91                         self.type = 'NORMAL'
92                         return self.set_input_from_linked(self.node.inputs["Color"])
93
94         def check_invert_channels(self):
95                 if self.node.type!='COMBRGB':
96                         return
97
98                 from .util import get_linked_node_and_socket
99
100                 separate = None
101                 invert_channels = ""
102                 for c in ("R", "G", "B"):
103                         from_node, _ = get_linked_node_and_socket(self.node_tree, self.node.inputs[c])
104                         if from_node.type=='MATH' and from_node.operation=='SUBTRACT' and not from_node.inputs[0].is_linked and from_node.inputs[0].default_value==1.0:
105                                 invert_channels += c
106                                 from_node, _ = get_linked_node_and_socket(self.node_tree, from_node.inputs[1])
107
108                         if from_node.type=='SEPRGB' and (separate is None or from_node==separate):
109                                 separate = from_node
110                         else:
111                                 return
112
113                 self.type = 'INVERT'
114                 self.data = invert_channels
115
116                 return self.set_input_from_linked(separate.inputs["Image"])
117
118         def check_additive_blend(self):
119                 if self.node.type=='ADD_SHADER':
120                         from .util import get_linked_node_and_socket
121
122                         for i in range(2):
123                                 shader, _ = get_linked_node_and_socket(self.node_tree, self.node.inputs[i])
124                                 if shader.type=='BSDF_TRANSPARENT':
125                                         self.type = 'ADDITIVE'
126                                         return self.set_input_from_linked(self.node.inputs[1-i])
127
128         def check_texture(self):
129                 if self.node.type=='TEX_IMAGE':
130                         self.type = 'TEXTURE'
131
132 def get_unlit_inputs(node_tree, node, additive):
133         from .util import get_linked_node_and_socket
134
135         if node.type=='MIX_SHADER' and not additive:
136                 shader1, _ = get_linked_node_and_socket(node_tree, node.inputs[1])
137                 shader2, _ = get_linked_node_and_socket(node_tree, node.inputs[2])
138                 if shader1.type=='BSDF_TRANSPARENT' and shader2.type=='EMISSION':
139                         factor_input = node.inputs["Fac"]
140                         factor_from, _ = get_linked_node_and_socket(node_tree, factor_input)
141                         color_input = shader2.inputs["Color"]
142                         color_from, _ = get_linked_node_and_socket(node_tree, color_input)
143                         if factor_from==color_from:
144                                 return (color_input, factor_input)
145         elif node.type=='EMISSION':
146                 color_input = node.inputs["Color"]
147                 if additive:
148                         color_from, _ = get_linked_node_and_socket(node_tree, color_input)
149                         if color_from.type=='MIX_RGB' and color_from.blend_type=='MIX':
150                                 mix_factor_input = color_from.inputs["Fac"]
151                                 mix_factor_from, _ = get_linked_node_and_socket(node_tree, mix_factor_input)
152                                 mix_color_input = color_from.inputs["Color2"]
153                                 mix_color_from, _ = get_linked_node_and_socket(node_tree, mix_color_input)
154                                 if mix_factor_from==mix_color_from:
155                                         return (mix_color_input, mix_factor_input)
156                 return (color_input, None)
157         return (None, None)
158
159 def get_splat_layers(node_tree, node):
160         from .util import get_linked_node_and_socket
161
162         if node.type!='MIX_SHADER':
163                 return
164
165         layers = []
166         while True:
167                 factor_from, factor_sock = get_linked_node_and_socket(node_tree, node.inputs["Fac"])
168                 if factor_from.type!='SEPRGB':
169                         return
170
171                 factor_from, _ = get_linked_node_and_socket(node_tree, factor_from.inputs["Image"])
172                 if factor_from.type!='VERTEX_COLOR':
173                         return
174
175                 shader1, _ = get_linked_node_and_socket(node_tree, node.inputs[1])
176                 shader2, _ = get_linked_node_and_socket(node_tree, node.inputs[2])
177                 layers.append((shader2, factor_from.layer_name, factor_sock.name[0]))
178                 if shader1.type=='MIX_SHADER':
179                         node = shader1
180                 else:
181                         layers.append((shader1, None, None))
182                         break
183
184         return layers
185
186 class MaterialProperty:
187         def __init__(self, keyword, tex_keyword, value):
188                 self.keyword = keyword
189                 self.tex_keyword = tex_keyword
190                 self.value = value
191                 self.texture = None
192                 self.tex_channels = None
193                 self.scale = 1.0
194                 self.tint = None
195
196         def set_from_input(self, node_tree, input_socket, alpha_socket=None):
197                 if self.keyword:
198                         if type(self.value)==tuple:
199                                 if alpha_socket:
200                                         self.value = input_socket.default_value[:len(self.value)-1]+(alpha_socket.default_value,)
201                                 else:
202                                         self.value = input_socket.default_value[:len(self.value)]
203                         else:
204                                 self.value = input_socket.default_value
205
206                 if self.tex_keyword:
207                         from .util import get_linked_node_and_socket
208
209                         from_node, from_sock = get_linked_node_and_socket(node_tree, input_socket)
210                         alpha_from = None
211                         if from_node:
212                                 channels = None
213                                 top_node = PropertyNode(node_tree, from_node, from_sock)
214                                 n = top_node
215                                 while n:
216                                         if n.type=='NORMAL':
217                                                 channels = ['R', 'G', 'B']
218                                         elif n.type=='GRAY':
219                                                 channels = ['Y']
220                                         elif n.type=='EXTRACT':
221                                                 channels = [n.data]
222                                         elif n.type=='INVERT':
223                                                 channels = ['~'+c if c in n.data else c for c in channels]
224                                         elif n.type=='SCALE':
225                                                 self.scale = n.data
226                                         elif n.type=='TINT':
227                                                 self.tint = n.data
228                                         elif n.type=='TEXTURE':
229                                                 self.texture = n.node
230                                         n = n.input
231
232                                 if alpha_socket:
233                                         alpha_from, _ = get_linked_node_and_socket(node_tree, alpha_socket)
234                                         if alpha_from and alpha_from!=self.texture:
235                                                 raise Exception("Separate textures for color and alpha are not supported")
236
237                                 if self.scale==0.0 and self.keyword and type(self.value)!=tuple:
238                                         self.texture = None
239                                         self.value = self.scale
240                                 elif self.scale!=1.0:
241                                         raise Exception("Unsupported material property scale {}".format(self.scale))
242                                 elif self.texture:
243                                         if channels:
244                                                 self.tex_channels = channels
245                                         elif alpha_from:
246                                                 self.tex_channels = ['R', 'G', 'B', 'A']
247                                         elif type(self.value)==tuple:
248                                                 self.tex_channels = ['R', 'G', 'B']
249                                         else:
250                                                 self.tex_channels = ['Y']
251                                 else:
252                                         raise Exception("Unsupported property input node type "+from_node.type)
253
254 class SubMaterial:
255         def __init__(self):
256                 self.properties = []
257                 self.weight_source = (None, None)
258
259 class Material:
260         def __init__(self, material):
261                 self.name = material.name
262                 self.type = None
263                 self.properties = []
264                 self.sub_materials = []
265                 self.array_storage = {}
266
267                 self.render_mode = material.render_mode
268                 self.technique = material.technique
269                 self.render_methods = material.render_methods[:]
270                 self.uniforms = material.uniforms[:]
271                 self.face_cull = 'BACK' if material.use_backface_culling else 'NONE'
272                 self.receive_shadows = material.receive_shadows
273                 self.cast_shadows = (material.shadow_method!='NONE')
274                 self.blend_type = 'ALPHA' if material.blend_method=='BLEND' else 'NONE'
275                 self.alpha_cutoff = material.alpha_threshold if material.blend_method=='CLIP' else 0.0
276                 self.image_based_lighting = material.image_based_lighting
277                 self.instancing = material.instancing
278
279                 if self.render_mode=='EXTERNAL' and not self.technique:
280                         raise Exception("Invalid configuration on material {}: No technique for external rendering".format(self.name))
281                 elif self.render_mode=='CUSTOM' and not self.render_methods:
282                         raise Exception("Invalid configuration on material {}: No render methods for custom rendering".format(self.name))
283
284                 out_node = next((n for n in material.node_tree.nodes if n.type=='OUTPUT_MATERIAL'), None)
285                 if not out_node:
286                         raise Exception("No output node found on material {}".format(self.name))
287
288                 from .util import get_linked_node_and_socket
289
290                 from_node, from_sock = get_linked_node_and_socket(material.node_tree, out_node.inputs["Surface"])
291                 if not from_node:
292                         if self.render_mode=='BUILTIN':
293                                 raise Exception("Invalid configuration on material {}: Empty material with builtin rendering".format(self.name))
294                         return
295
296                 surface_node = PropertyNode(material.node_tree, from_node, from_sock)
297                 if surface_node.type=='ADDITIVE':
298                         self.blend_type = 'ADDITIVE'
299                         from_node = surface_node.input.node
300
301                 if from_node.type=='BSDF_PRINCIPLED':
302                         self.type = "pbr"
303                         self.init_pbr_properties(material.node_tree, from_node)
304                 elif from_node.type=='EMISSION' or from_node.type=='MIX_SHADER':
305                         splat_layers = get_splat_layers(material.node_tree, from_node)
306                         if splat_layers:
307                                 for s in splat_layers:
308                                         if s[0].type!='BSDF_PRINCIPLED':
309                                                 raise Exception("Unsupported splat layer type {} on splat material {}".format(s[0].type, self.name))
310
311                                 from .texture import Texture
312
313                                 self.type = "splat"
314                                 self.sub_materials = []
315                                 for l in splat_layers:
316                                         self.init_pbr_properties(material.node_tree, l[0])
317                                         sub = SubMaterial()
318                                         sub.properties = self.properties
319                                         sub.weight_source = l[1:]
320                                         self.sub_materials.append(sub)
321                                         self.properties = []
322
323                                         for p in sub.properties:
324                                                 if p.texture:
325                                                         texture = Texture(p.texture, p.tex_channels)
326                                                         storage = (texture.pixelformat, texture.width, texture.height)
327                                                         existing = self.array_storage.setdefault(p.tex_keyword, storage)
328                                                         if storage!=existing:
329                                                                 raise Exception("Inconsistent storage for {} on splat material {}".format(p.tex_keyword, self.name))
330                         else:
331                                 color_input, alpha_input = get_unlit_inputs(material.node_tree, from_node, self.blend_type=='ADDITIVE')
332                                 if not color_input:
333                                         raise Exception("Unsupported configuration for unlit material {}".format(self.name))
334
335                                 self.type = "unlit"
336
337                                 color = self.create_property("color", "texture", (1.0, 1.0, 1.0, 1.0))
338
339                                 color.set_from_input(material.node_tree, color_input, alpha_input)
340                                 if self.blend_type=='ADDITIVE' and alpha_input:
341                                         self.blend_type = 'ADDITIVE_ALPHA'
342                 else:
343                         raise Exception("Unsupported surface node type {} on material {}".format(from_node.type, self.name))
344
345                 sampler_settings = None
346                 for p in self.properties:
347                         if p.texture:
348                                 settings = (p.texture.interpolation, p.texture.use_mipmap, p.texture.max_anisotropy)
349                                 if sampler_settings is None:
350                                         sampler_settings = settings
351                                 elif settings!=sampler_settings:
352                                         raise Exception("Material {} has conflicting texture sampler settings".format(self.name))
353
354         def create_property(self, *args):
355                 prop = None
356                 if len(args)==1:
357                         prop = MaterialProperty(None, args[0], None)
358                 elif len(args)==2:
359                         prop = MaterialProperty(args[0], args[0]+"_map", args[1])
360                 else:
361                         prop = MaterialProperty(*args)
362                 self.properties.append(prop)
363                 return prop
364
365         def init_pbr_properties(self, node_tree, from_node):
366                 base_color = self.create_property("base_color", (0.8, 0.8, 0.8, 1.0))
367                 tint = self.create_property("tint", (1.0, 1.0, 1.0, 1.0))
368                 metalness = self.create_property("metalness", 0.0)
369                 roughness = self.create_property("roughness", 0.5)
370                 normal = self.create_property("normal_map")
371                 emission = self.create_property("emission", (0.0, 0.0, 0.0))
372
373                 base_color.set_from_input(node_tree, from_node.inputs["Base Color"], from_node.inputs["Alpha"])
374                 if base_color.tint:
375                         tint.value = base_color.tint
376                 metalness.set_from_input(node_tree, from_node.inputs["Metallic"])
377                 roughness.set_from_input(node_tree, from_node.inputs["Roughness"])
378                 normal.set_from_input(node_tree, from_node.inputs["Normal"])
379                 emission.set_from_input(node_tree, from_node.inputs["Emission"])