]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/material.py
Clear reflect data before adding shader stages
[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 def check_group(node_tree, group, func):
12         from .util import get_linked_node_and_socket
13
14         output = group.node_tree.nodes["Group Output"]
15         from_node, _ = get_linked_node_and_socket(group.node_tree, output.inputs[0])
16         if from_node:
17                 from_node, _ = func(group.node_tree, from_node)
18                 if from_node and from_node.type=='GROUP_INPUT':
19                         return get_linked_node_and_socket(node_tree, group.inputs[0])
20         return (None, None)
21
22 def check_invert_green(node_tree, node):
23         if node.type=='GROUP':
24                 return check_group(node_tree, node, check_invert_green)
25         elif node.type!='COMBRGB':
26                 return (None, None)
27
28         from .util import get_linked_node_and_socket
29
30         green, g_sock = get_linked_node_and_socket(node_tree, node.inputs["G"])
31         if not green or green.type!='MATH' or green.operation!='SUBTRACT':
32                 return (None, None)
33         green, g_sock = get_linked_node_and_socket(node_tree, green.inputs[1])
34
35         red, r_sock = get_linked_node_and_socket(node_tree, node.inputs["R"])
36         blue, b_sock = get_linked_node_and_socket(node_tree, node.inputs["B"])
37         if not red or red.type!='SEPRGB' or blue!=red or green!=red:
38                 return (None, None)
39
40         return get_linked_node_and_socket(node_tree, red.inputs["Image"])
41
42 class MaterialProperty:
43         def __init__(self, keyword, tex_keyword, value):
44                 self.keyword = keyword
45                 self.tex_keyword = tex_keyword
46                 self.value = value
47                 self.texture = None
48                 self.tex_usage = None
49                 self.invert_green = False
50
51         def set_from_input(self, node_tree, input_socket, alpha_socket=None):
52                 if self.keyword:
53                         if type(self.value)==tuple:
54                                 if alpha_socket:
55                                         self.value = input_socket.default_value[:len(self.value)-1]+(alpha_socket.default_value,)
56                                 else:
57                                         self.value = input_socket.default_value[:len(self.value)]
58                         else:
59                                 self.value = input_socket.default_value
60
61                 if self.tex_keyword:
62                         from .util import get_linked_node_and_socket
63
64                         from_node, _ = get_linked_node_and_socket(node_tree, input_socket)
65                         alpha_from = None
66                         if from_node:
67                                 usage = None
68                                 if from_node.type=='NORMAL_MAP':
69                                         from_node, _ = get_linked_node_and_socket(node_tree, from_node.inputs["Color"])
70                                         invert, _ = check_invert_green(node_tree, from_node)
71                                         if invert:
72                                                 from_node = invert
73                                                 self.invert_green = True
74                                         usage = 'RGB'
75                                 elif from_node.type=='RGBTOBW':
76                                         from_node, _ = get_linked_node_and_socket(node_tree, from_node.inputs["Color"])
77
78                                 if alpha_socket:
79                                         alpha_from, _ = get_linked_node_and_socket(node_tree, alpha_socket)
80                                         if alpha_from and alpha_from!=from_node:
81                                                 raise Exception("Separate textures for color and alpha are not supported")
82
83                                 if from_node.type=='TEX_IMAGE':
84                                         self.texture = from_node
85                                         if usage:
86                                                 self.tex_usage = usage
87                                         elif alpha_from:
88                                                 self.tex_usage = 'RGBA'
89                                         elif type(self.value)==tuple:
90                                                 self.tex_usage = 'RGB'
91                                         else:
92                                                 self.tex_usage = 'GRAY'
93                                 else:
94                                         raise Exception("Unsupported property input node type "+from_node.type)
95
96 class Material:
97         def __init__(self, material):
98                 self.name = material.name
99                 self.type = None
100                 self.properties = []
101
102                 self.render_mode = material.render_mode
103                 self.technique = material.technique
104                 self.render_methods = material.render_methods[:]
105                 self.receive_shadows = material.receive_shadows
106                 self.cast_shadows = (material.shadow_method!='NONE')
107                 self.image_based_lighting = material.image_based_lighting
108
109                 if self.render_mode=='EXTERNAL' and not self.technique:
110                         raise Exception("Invalid configuration on material {}: No technique for external rendering".format(self.name))
111                 elif self.render_mode=='CUSTOM' and not self.render_methods:
112                         raise Exception("Invalid configuration on material {}: No render methods for custom rendering".format(self.name))
113
114                 out_node = next((n for n in material.node_tree.nodes if n.type=='OUTPUT_MATERIAL'), None)
115                 if not out_node:
116                         raise Exception("No output node found on material {}".format(self.name))
117
118                 from .util import get_linked_node_and_socket
119
120                 surface_node, _ = get_linked_node_and_socket(material.node_tree, out_node.inputs["Surface"])
121                 if not surface_node:
122                         if self.render_mode=='BUILTIN':
123                                 raise Exception("Invalid configuration on material {}: Empty material with builtin rendering".format(self.name))
124                         return
125                 elif surface_node.type=='BSDF_PRINCIPLED':
126                         self.type = "pbr"
127
128                         base_color = self.create_property("base_color", (0.8, 0.8, 0.8, 1.0))
129                         metalness = self.create_property("metalness", 0.0)
130                         roughness = self.create_property("roughness", 0.5)
131                         normal = self.create_property("normal_map")
132                         emission = self.create_property("emission", (0.0, 0.0, 0.0))
133
134                         base_color.set_from_input(material.node_tree, surface_node.inputs["Base Color"], surface_node.inputs["Alpha"])
135                         metalness.set_from_input(material.node_tree, surface_node.inputs["Metallic"])
136                         roughness.set_from_input(material.node_tree, surface_node.inputs["Roughness"])
137                         normal.set_from_input(material.node_tree, surface_node.inputs["Normal"])
138                         emission.set_from_input(material.node_tree, surface_node.inputs["Emission"])
139                 elif surface_node.type=='EMISSION':
140                         self.type = "unlit"
141
142                         color = self.create_property("color", "texture", (1.0, 1.0, 1.0, 1.0))
143
144                         color.set_from_input(material.node_tree, surface_node.inputs["Color"])
145                 else:
146                         raise Exception("Unsupported surface node type {} on material {}".format(surface_node.type, self.name))
147
148                 sampler_settings = None
149                 for p in self.properties:
150                         if p.texture:
151                                 settings = (p.texture.interpolation, p.texture.use_mipmap, p.texture.max_anisotropy)
152                                 if sampler_settings is None:
153                                         sampler_settings = settings
154                                 elif settings!=sampler_settings:
155                                         raise Exception("Material {} has conflicting texture sampler settings".format(self.name))
156
157         def create_property(self, *args):
158                 prop = None
159                 if len(args)==1:
160                         prop = MaterialProperty(None, args[0], None)
161                 elif len(args)==2:
162                         prop = MaterialProperty(args[0], args[0]+"_map", args[1])
163                 else:
164                         prop = MaterialProperty(*args)
165                 self.properties.append(prop)
166                 return prop
167
168
169 class MaterialAtlas:
170         def __init__(self, materials):
171                 self.render_mode = materials[0].render_mode
172                 if self.render_mode=='EXTERNAL':
173                         raise Exception("Material atlas with external render mode does not make sense")
174
175                 if self.render_mode=='CUSTOM':
176                         self.render_methods = materials[0].render_methods
177                 else:
178                         self.render_methods = None
179                 if self.render_methods:
180                         self.name = "material_atlas_"+os.path.splitext(self.render_methods[0].shader)[0]
181                 else:
182                         self.name = "material_atlas"
183                 self.receive_shadows = materials[0].receive_shadows
184                 self.cast_shadows = (materials[0].shadow_method!='NONE')
185                 self.materials = materials
186                 self.material_names = [m.name for m in self.materials]
187                 self.uniforms = None
188                 method_hash = compute_render_method_hash(self)
189                 for m in self.materials:
190                         if m.render_mode!=self.render_mode:
191                                 raise Exception("Conflicting render modes in MaterialAtlas constructor")
192                         if self.render_mode=='CUSTOM' and compute_render_method_hash(m)!=method_hash:
193                                 raise Exception("Conflicting shaders in MaterialAtlas constructor")
194                         if m.receive_shadows!=self.receive_shadows or m.shadow_method!=materials[0].shadow_method:
195                                 raise Exception("Conflicting shadow settings in MaterialAtlas constructor")
196
197                 count = len(self.materials)
198                 size = 1
199                 while size*size*2<count:
200                         size *= 2
201                 if size*size>=count:
202                         self.size = (size, size)
203                 else:
204                         self.size = (size*2, size)
205
206                 from .util import get_colormap
207
208                 cm = get_colormap(True)
209                 self.base_color_data = ""
210                 for m in map(Material, self.materials):
211                         if any(p.texture for p in m.properties):
212                                 raise Exception("Texturing is incompatible with material atlas")
213                         base_color = [int(cm(c)*255) for c in m.base_color.value]
214                         self.base_color_data += "\\x{:02X}\\x{:02X}\\x{:02X}\\xFF".format(*base_color)
215                 self.base_color_data += "\\x00\\x00\\x00\\x00"*(self.size[0]*self.size[1]-count)
216
217         def get_material_uv(self, material):
218                 index = self.material_names.index(material.name)
219                 x = index%self.size[0]
220                 y = index//self.size[0]
221                 return ((x+0.5)/self.size[0], (y+0.5)/self.size[1])
222
223 def create_material_atlas(context, material):
224         if not material.material_atlas:
225                 raise Exception("Material is not part of a material atlas")
226
227         method_hash = compute_render_method_hash(material)
228         materials = []
229         for m in context.blend_data.materials:
230                 if m.material_atlas and compute_render_method_hash(m)==method_hash:
231                         materials.append(m)
232
233         return MaterialAtlas(materials)