]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mesh_mspgl/export_mspgl.py
Improve texture unit handling
[libs/gl.git] / blender / io_mesh_mspgl / export_mspgl.py
1 import bpy
2
3 class VertexCache:
4         def __init__(self, size):
5                 self.size = size
6                 self.slots = [-1]*self.size
7
8         def fetch(self, v):
9                 hit = v.index in self.slots
10                 if hit:
11                         self.slots.remove(v.index)
12                 self.slots.append(v.index)
13                 if not hit:
14                         del self.slots[0]
15                 return hit
16
17         def fetch_strip(self, strip):
18                 hits = 0
19                 for v in strip:
20                         if self.fetch(v):
21                                 hits += 1
22                 return hits
23
24         def test_strip(self, strip):
25                 hits = 0
26                 for i in range(len(strip)):
27                         if i>=self.size:
28                                 break
29                         if strip[i].index in self.slots[i:]:
30                                 hits += 1
31                 return hits
32
33
34 class OutFile:
35         def __init__(self, fn):
36                 if fn==None:
37                         self.file = sys.stdout
38                 else:
39                         self.file = open(fn, "w")
40                 self.indent = 0
41
42         def make(self, kwd, *params):
43                 pstr = ""
44                 for p in params:
45                         if type(p)==float:
46                                 pstr += " %.6g"%p
47                         else:
48                                 pstr += " %s"%p
49                 return "%s%s"%(kwd, pstr)
50
51         def write(self, kwd, *params):
52                 self.file.write("%s%s;\n"%('\t'*self.indent, self.make(kwd, *params)))
53
54         def begin(self, kwd, *params):
55                 i = '\t'*self.indent
56                 self.file.write("%s%s\n%s{\n"%(i, self.make(kwd, *params), i))
57                 self.indent += 1
58
59         def end(self):
60                 self.indent -= 1
61                 self.file.write("%s};\n"%('\t'*self.indent))
62
63
64 class Exporter:
65         def __init__(self):
66                 self.use_strips = True
67                 self.use_degen_tris = True
68                 self.max_strip_len = 1024
69                 self.optimize_cache = False
70                 self.cache_size = 64
71                 self.export_lines = True
72                 self.export_uv = "UNIT0"
73                 self.tbn_vecs = False
74                 self.tbn_uvtex = ""
75                 self.compound = False
76                 self.object = False
77                 self.material_tex = False
78                 self.smoothing = "MSPGL"
79
80         def stripify(self, mesh, progress = None):
81                 for f in mesh.faces:
82                         f.flag = False
83
84                 faces_done = 0
85                 strips = []
86                 loose = []
87
88                 cache = None
89                 if self.optimize_cache:
90                         cache = VertexCache(self.cache_size)
91
92                 island = []
93                 island_strips = []
94                 while 1:
95                         if not island:
96                                 queue = []
97                                 for f in mesh.faces:
98                                         if not f.flag:
99                                                 f.flag = True
100                                                 queue.append(f)
101                                                 break
102
103                                 if not queue:
104                                         break
105
106                                 while queue:
107                                         f = queue[0]
108                                         del queue[0]
109                                         island.append(f)
110
111                                         for e in f.edges:
112                                                 other = e.other_face(f)
113                                                 if other and not other.flag:
114                                                         other.flag = True
115                                                         queue.append(other)
116
117                                 for f in island:
118                                         f.flag = False
119
120                         best = 5
121                         face = None
122                         for f in island:
123                                 if f.flag:
124                                         continue
125                                 score = 0
126                                 for e in f.edges:
127                                         other = e.other_face(f)
128                                         if other and not other.flag:
129                                                 score += 1
130                                 if score>0 and score<best:
131                                         face = f
132                                         best = score
133
134                         if not face:
135                                 while island_strips:
136                                         best = 0
137                                         if cache:
138                                                 best_hits = 0
139                                                 for i in range(len(island_strips)):
140                                                         hits = cache.test_strip(island_strips[i])
141                                                         if hits>best_hits:
142                                                                 best = i
143                                                                 best_hits = hits
144
145                                         s = island_strips[best]
146                                         del island_strips[best]
147                                         strips.append(s)
148
149                                         if cache:
150                                                 cache.fetch_strip(s)
151
152                                 faces_done += len(island)
153                                 if progress:
154                                         progress.set_progress(float(faces_done)/len(mesh.faces))
155
156                                 loose += [f for f in island if not f.flag]
157                                 for f in island:
158                                         f.flag = True
159
160                                 island = []
161                                 island_strips = []
162                                 continue
163
164                         strip = mesh.create_strip(face, self.max_strip_len)
165                         if strip:
166                                 island_strips.append(strip)
167
168                 if cache:
169                         cache = VertexCache(self.cache_size)
170                         total_hits = 0
171
172                 if self.use_degen_tris and strips:
173                         big_strip = []
174
175                         for s in strips:
176                                 if big_strip:
177                                         glue = [big_strip[-1], s[0]]
178                                         if len(big_strip)%2:
179                                                 glue += [s[0]]
180
181                                         big_strip += glue
182                                         if cache:
183                                                 total_hits += cache.fetch_strip(glue)
184
185                                 big_strip += s
186                                 if cache:
187                                         total_hits += cache.fetch_strip(s)
188
189                         for f in loose:
190                                 if len(big_strip)%2:
191                                         order = (-1, -2, 0, 1)
192                                 else:
193                                         order = (0, 1, -1, -2)
194                                 vertices = [f.vertices[i] for i in order[:len(f.vertices)]]
195
196                                 if big_strip:
197                                         glue = [big_strip[-1], vertices[0]]
198                                         big_strip += glue
199                                         if cache:
200                                                 total_hits += cache.fetch_strip(glue)
201
202                                 big_strip += vertices
203                                 if cache:
204                                         total_hits += cache.fetch_strip(vertices)
205
206                         strips = [big_strip]
207                         loose = []
208
209                 return strips, loose
210
211         def export(self, context, fn):
212                 if self.compound:
213                         objs = context.selected_objects
214                 else:
215                         objs = [context.active_object]
216
217                 if not objs:
218                         raise Exception("Nothing to export")
219                 for o in objs:
220                         if o.type!="MESH":
221                                 raise Exception("Can only export Mesh data")
222
223                 from .mesh import Mesh
224                 from .util import Progress
225
226                 progress = Progress()
227                 progress.set_task("Preparing", 0.0, 0.0)
228
229                 mesh = None
230                 bmeshes = []
231                 for o in objs:
232                         bmesh = o.to_mesh(context.scene, True, "PREVIEW")
233                         bmeshes.append(bmesh)
234                         if not mesh:
235                                 mesh = Mesh(bmesh)
236                         else:
237                                 mesh.splice(Mesh(bmesh))
238
239                 progress.set_task("Smoothing", 0.05, 0.35)
240                 if self.smoothing=="NONE":
241                         mesh.flatten_faces()
242                 mesh.split_smooth(progress)
243
244                 if self.smoothing!="BLENDER":
245                         mesh.compute_normals()
246
247                 if self.material_tex and mesh.materials:
248                         mesh.generate_material_uv()
249
250                 texunits = []
251                 if mesh.uv_layers and self.export_uv!="NONE":
252                         # Figure out which UV layers to export
253                         if self.export_uv=="UNIT0":
254                                 if mesh.uv_layers[0].unit==0:
255                                         texunits = [0]
256                         else:
257                                 texunits = range(len(mesh.uv_layers))
258                         texunits = [(i, mesh.uv_layers[i]) for i in texunits]
259                         texunits = [u for u in texunits if not u[1].hidden]
260
261                         if self.tbn_vecs:
262                                 # TBN coordinates must be generated before vertices are split by any other layer
263                                 uv_names = [u.name for i, u in texunits]
264                                 if self.tbn_uvtex in uv_names:
265                                         tbn_index = uv_names.index(self.tbn_uvtex)
266                                         unit = texunits[tbn_index]
267                                         del texunits[tbn_index]
268                                         texunits.insert(0, unit)
269
270                         for i, u in texunits:
271                                 progress.set_task("Splitting UVs", 0.35+0.3*i/len(texunits), 0.35+0.3*(i+1)/len(texunits))
272                                 mesh.split_uv(i, progress)
273                                 if self.tbn_vecs and u.name==self.tbn_uvtex:
274                                         mesh.compute_uv()
275                                         mesh.compute_tbn(i)
276
277                         mesh.compute_uv()
278
279                 strips = []
280                 loose = mesh.faces
281                 if self.use_strips:
282                         progress.set_task("Creating strips", 0.65, 0.95)
283                         strips, loose = self.stripify(mesh, progress)
284
285                 progress.set_task("Writing file", 0.95, 1.0)
286
287                 out_file = OutFile(fn)
288                 if self.object:
289                         out_file.begin("mesh")
290
291                 fmt = "NORMAL3"
292                 if texunits:
293                         for i, u in texunits:
294                                 if u.unit==0:
295                                         fmt += "_TEXCOORD2"
296                                 else:
297                                         fmt += "_TEXCOORD2%d"%u.unit
298                         if self.tbn_vecs:
299                                 fmt += "_ATTRIB33_ATTRIB34"
300                 fmt += "_VERTEX3"
301                 out_file.begin("vertices", fmt)
302                 normal = None
303                 uvs = [None]*len(texunits)
304                 tan = None
305                 bino = None
306                 for v in mesh.vertices:
307                         if v.normal!=normal:
308                                 out_file.write("normal3", *v.normal)
309                                 normal = v.normal
310                         for i, u in texunits:
311                                 if v.uvs[i]!=uvs[i]:
312                                         if u.unit==0:
313                                                 out_file.write("texcoord2", *v.uvs[i])
314                                         else:
315                                                 out_file.write("multitexcoord2", u.unit, *v.uvs[i])
316                                         uvs[i] = v.uvs[i]
317                         if v.tan!=tan:
318                                 out_file.write("attrib3", 3, *v.tan)
319                                 tan = v.tan
320                         if v.bino!=bino:
321                                 out_file.write("attrib3", 4, *v.bino)
322                                 bino = v.bino
323                         out_file.write("vertex3", *v.co)
324                 out_file.end()
325                 for s in strips:
326                         out_file.begin("batch", "TRIANGLE_STRIP")
327                         indices = []
328                         n = 0
329                         for v in s:
330                                 indices.append(v.index)
331                                 if len(indices)>=32:
332                                         out_file.write("indices", *indices)
333                                         indices = []
334                         if indices:
335                                 out_file.write("indices", *indices)
336                         out_file.end()
337
338                 if loose:
339                         out_file.begin("batch", "TRIANGLES")
340                         for f in loose:
341                                 for i in range(2, len(f.vertices)):
342                                         out_file.write("indices", f.vertices[0].index, f.vertices[i-1].index, f.vertices[i].index)
343                         out_file.end()
344
345                 if self.export_lines and mesh.lines:
346                         out_file.write("batch", "LINES")
347                         for l in mesh.lines:
348                                 out_file.write("indices", l.vertices[0].index, l.vertices[1].index)
349                         out_file.end()
350
351                 if self.object:
352                         out_file.end()
353                         out_file.begin("technique")
354                         out_file.begin("pass", '""')
355                         if mesh.materials:
356                                 if self.material_tex:
357                                         out_file.begin("material")
358                                         out_file.write("diffuse", 1.0, 1.0, 1.0, 1.0)
359                                         out_file.end()
360                                         index = 0
361                                         for u in mesh.uv_layers:
362                                                 if u.name=="material_tex":
363                                                         index = u.unit
364                                         out_file.begin("texunit", index)
365                                         out_file.begin("texture2d")
366                                         out_file.write("min_filter", "NEAREST")
367                                         out_file.write("mag_filter", "NEAREST")
368                                         out_file.write("storage", "RGB", len(mesh.materials), 1)
369                                         texdata = '"'
370                                         for m in mesh.materials:
371                                                 color = [int(c*255) for c in m.diffuse_color]
372                                                 texdata += "\\x%02X\\x%02X\\x%02X"%tuple(color)
373                                         texdata += '"'
374                                         out_file.write("raw_data", texdata)
375                                         out_file.end()
376                                         out_file.end()
377                                 else:
378                                         mat = mesh.materials[0]
379                                         out_file.begin("material")
380                                         diff = mat.diffuse_color
381                                         out_file.write("diffuse", diff.r, diff.g, diff.b, 1.0)
382                                         amb = diff*mat.ambient
383                                         out_file.write("ambient", amb.r, amb.g, amb.b, 1.0)
384                                         spec = mat.specular_color*mat.specular_intensity
385                                         out_file.write("specular", spec.r, spec.g, spec.b, 1.0)
386                                         out_file.write("shininess", mat.specular_hardness);
387                                         out_file.end()
388                         out_file.end()
389                         out_file.end()
390
391                 progress.set_task("Done", 1.0, 1.0)
392
393                 for m in bmeshes:
394                         bpy.data.meshes.remove(m)