]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mesh_mspgl/export_mspgl.py
Support exporting textures with objects
[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.textures = "REF"
79                 self.smoothing = "MSPGL"
80
81         def stripify(self, mesh, progress = None):
82                 for f in mesh.faces:
83                         f.flag = False
84
85                 faces_done = 0
86                 strips = []
87                 loose = []
88
89                 cache = None
90                 if self.optimize_cache:
91                         cache = VertexCache(self.cache_size)
92
93                 island = []
94                 island_strips = []
95                 while 1:
96                         if not island:
97                                 queue = []
98                                 for f in mesh.faces:
99                                         if not f.flag:
100                                                 f.flag = True
101                                                 queue.append(f)
102                                                 break
103
104                                 if not queue:
105                                         break
106
107                                 while queue:
108                                         f = queue[0]
109                                         del queue[0]
110                                         island.append(f)
111
112                                         for e in f.edges:
113                                                 other = e.other_face(f)
114                                                 if other and not other.flag:
115                                                         other.flag = True
116                                                         queue.append(other)
117
118                                 for f in island:
119                                         f.flag = False
120
121                         best = 5
122                         face = None
123                         for f in island:
124                                 if f.flag:
125                                         continue
126                                 score = 0
127                                 for e in f.edges:
128                                         other = e.other_face(f)
129                                         if other and not other.flag:
130                                                 score += 1
131                                 if score>0 and score<best:
132                                         face = f
133                                         best = score
134
135                         if not face:
136                                 while island_strips:
137                                         best = 0
138                                         if cache:
139                                                 best_hits = 0
140                                                 for i in range(len(island_strips)):
141                                                         hits = cache.test_strip(island_strips[i])
142                                                         if hits>best_hits:
143                                                                 best = i
144                                                                 best_hits = hits
145
146                                         s = island_strips[best]
147                                         del island_strips[best]
148                                         strips.append(s)
149
150                                         if cache:
151                                                 cache.fetch_strip(s)
152
153                                 faces_done += len(island)
154                                 if progress:
155                                         progress.set_progress(float(faces_done)/len(mesh.faces))
156
157                                 loose += [f for f in island if not f.flag]
158                                 for f in island:
159                                         f.flag = True
160
161                                 island = []
162                                 island_strips = []
163                                 continue
164
165                         strip = mesh.create_strip(face, self.max_strip_len)
166                         if strip:
167                                 island_strips.append(strip)
168
169                 if cache:
170                         cache = VertexCache(self.cache_size)
171                         total_hits = 0
172
173                 if self.use_degen_tris and strips:
174                         big_strip = []
175
176                         for s in strips:
177                                 if big_strip:
178                                         glue = [big_strip[-1], s[0]]
179                                         if len(big_strip)%2:
180                                                 glue += [s[0]]
181
182                                         big_strip += glue
183                                         if cache:
184                                                 total_hits += cache.fetch_strip(glue)
185
186                                 big_strip += s
187                                 if cache:
188                                         total_hits += cache.fetch_strip(s)
189
190                         for f in loose:
191                                 if len(big_strip)%2:
192                                         order = (-1, -2, 0, 1)
193                                 else:
194                                         order = (0, 1, -1, -2)
195                                 vertices = [f.vertices[i] for i in order[:len(f.vertices)]]
196
197                                 if big_strip:
198                                         glue = [big_strip[-1], vertices[0]]
199                                         big_strip += glue
200                                         if cache:
201                                                 total_hits += cache.fetch_strip(glue)
202
203                                 big_strip += vertices
204                                 if cache:
205                                         total_hits += cache.fetch_strip(vertices)
206
207                         strips = [big_strip]
208                         loose = []
209
210                 return strips, loose
211
212         def export(self, context, fn):
213                 if self.compound:
214                         objs = context.selected_objects
215                 else:
216                         objs = [context.active_object]
217
218                 if not objs:
219                         raise Exception("Nothing to export")
220                 for o in objs:
221                         if o.type!="MESH":
222                                 raise Exception("Can only export Mesh data")
223
224                 from .mesh import Mesh
225                 from .util import Progress
226
227                 progress = Progress()
228                 progress.set_task("Preparing", 0.0, 0.0)
229
230                 mesh = None
231                 bmeshes = []
232                 for o in objs:
233                         bmesh = o.to_mesh(context.scene, True, "PREVIEW")
234                         bmeshes.append(bmesh)
235                         if not mesh:
236                                 mesh = Mesh(bmesh)
237                         else:
238                                 mesh.splice(Mesh(bmesh))
239
240                 progress.set_task("Smoothing", 0.05, 0.35)
241                 if self.smoothing=="NONE":
242                         mesh.flatten_faces()
243                 mesh.split_smooth(progress)
244
245                 if self.smoothing!="BLENDER":
246                         mesh.compute_normals()
247
248                 if self.material_tex and mesh.materials:
249                         mesh.generate_material_uv()
250
251                 texunits = []
252                 if mesh.uv_layers and self.export_uv!="NONE":
253                         # Figure out which UV layers to export
254                         if self.export_uv=="UNIT0":
255                                 if mesh.uv_layers[0].unit==0:
256                                         texunits = [0]
257                         else:
258                                 texunits = range(len(mesh.uv_layers))
259                         texunits = [(i, mesh.uv_layers[i]) for i in texunits]
260                         texunits = [u for u in texunits if not u[1].hidden]
261
262                         if self.tbn_vecs:
263                                 # TBN coordinates must be generated before vertices are split by any other layer
264                                 uv_names = [u.name for i, u in texunits]
265                                 if self.tbn_uvtex in uv_names:
266                                         tbn_index = uv_names.index(self.tbn_uvtex)
267                                         unit = texunits[tbn_index]
268                                         del texunits[tbn_index]
269                                         texunits.insert(0, unit)
270
271                         for i, u in texunits:
272                                 progress.set_task("Splitting UVs", 0.35+0.3*i/len(texunits), 0.35+0.3*(i+1)/len(texunits))
273                                 mesh.split_uv(i, progress)
274                                 if self.tbn_vecs and u.name==self.tbn_uvtex:
275                                         mesh.compute_uv()
276                                         mesh.compute_tbn(i)
277
278                         mesh.compute_uv()
279
280                 strips = []
281                 loose = mesh.faces
282                 if self.use_strips:
283                         progress.set_task("Creating strips", 0.65, 0.95)
284                         strips, loose = self.stripify(mesh, progress)
285
286                 progress.set_task("Writing file", 0.95, 1.0)
287
288                 out_file = OutFile(fn)
289                 if self.object:
290                         out_file.begin("mesh")
291
292                 fmt = "NORMAL3"
293                 if texunits:
294                         for i, u in texunits:
295                                 if u.unit==0:
296                                         fmt += "_TEXCOORD2"
297                                 else:
298                                         fmt += "_TEXCOORD2%d"%u.unit
299                         if self.tbn_vecs:
300                                 fmt += "_ATTRIB33_ATTRIB34"
301                 fmt += "_VERTEX3"
302                 out_file.begin("vertices", fmt)
303                 normal = None
304                 uvs = [None]*len(texunits)
305                 tan = None
306                 bino = None
307                 for v in mesh.vertices:
308                         if v.normal!=normal:
309                                 out_file.write("normal3", *v.normal)
310                                 normal = v.normal
311                         for i, u in texunits:
312                                 if v.uvs[i]!=uvs[i]:
313                                         if u.unit==0:
314                                                 out_file.write("texcoord2", *v.uvs[i])
315                                         else:
316                                                 out_file.write("multitexcoord2", u.unit, *v.uvs[i])
317                                         uvs[i] = v.uvs[i]
318                         if v.tan!=tan:
319                                 out_file.write("attrib3", 3, *v.tan)
320                                 tan = v.tan
321                         if v.bino!=bino:
322                                 out_file.write("attrib3", 4, *v.bino)
323                                 bino = v.bino
324                         out_file.write("vertex3", *v.co)
325                 out_file.end()
326                 for s in strips:
327                         out_file.begin("batch", "TRIANGLE_STRIP")
328                         indices = []
329                         n = 0
330                         for v in s:
331                                 indices.append(v.index)
332                                 if len(indices)>=32:
333                                         out_file.write("indices", *indices)
334                                         indices = []
335                         if indices:
336                                 out_file.write("indices", *indices)
337                         out_file.end()
338
339                 if loose:
340                         out_file.begin("batch", "TRIANGLES")
341                         for f in loose:
342                                 for i in range(2, len(f.vertices)):
343                                         out_file.write("indices", f.vertices[0].index, f.vertices[i-1].index, f.vertices[i].index)
344                         out_file.end()
345
346                 if self.export_lines and mesh.lines:
347                         out_file.write("batch", "LINES")
348                         for l in mesh.lines:
349                                 out_file.write("indices", l.vertices[0].index, l.vertices[1].index)
350                         out_file.end()
351
352                 if self.object:
353                         out_file.end()
354                         out_file.begin("technique")
355                         out_file.begin("pass", '""')
356                         if mesh.materials:
357                                 if self.material_tex:
358                                         out_file.begin("material")
359                                         out_file.write("diffuse", 1.0, 1.0, 1.0, 1.0)
360                                         out_file.end()
361                                         index = 0
362                                         for u in mesh.uv_layers:
363                                                 if u.name=="material_tex":
364                                                         index = u.unit
365                                         out_file.begin("texunit", index)
366                                         out_file.begin("texture2d")
367                                         out_file.write("min_filter", "NEAREST")
368                                         out_file.write("mag_filter", "NEAREST")
369                                         out_file.write("storage", "RGB", len(mesh.materials), 1)
370                                         texdata = '"'
371                                         for m in mesh.materials:
372                                                 color = [int(c*255) for c in m.diffuse_color]
373                                                 texdata += "\\x%02X\\x%02X\\x%02X"%tuple(color)
374                                         texdata += '"'
375                                         out_file.write("raw_data", texdata)
376                                         out_file.end()
377                                         out_file.end()
378                                 else:
379                                         mat = mesh.materials[0]
380                                         out_file.begin("material")
381                                         diff = mat.diffuse_color
382                                         out_file.write("diffuse", diff.r, diff.g, diff.b, 1.0)
383                                         amb = diff*mat.ambient
384                                         out_file.write("ambient", amb.r, amb.g, amb.b, 1.0)
385                                         spec = mat.specular_color*mat.specular_intensity
386                                         out_file.write("specular", spec.r, spec.g, spec.b, 1.0)
387                                         out_file.write("shininess", mat.specular_hardness);
388                                         out_file.end()
389
390                                 if self.textures!="NONE":
391                                         for slot in mesh.materials[0].texture_slots:
392                                                 if not slot:
393                                                         continue
394
395                                                 tex = slot.texture
396                                                 if tex.type!="IMAGE":
397                                                         continue
398
399                                                 if slot.uv_layer:
400                                                         for u in mesh.uv_layers:
401                                                                 if u.name==slot.uv_layer:
402                                                                         index = u.unit
403                                                 else:
404                                                         index = mesh.uv_layers[0].unit
405
406                                                 out_file.begin("texunit", index)
407                                                 if self.textures=="INLINE":
408                                                         out_file.begin("texture2d")
409                                                         out_file.write("min_filter", "LINEAR")
410                                                         out_file.write("storage", "RGBA", tex.image.size[0], tex.image.size[1])
411                                                         texdata = '"'
412                                                         for p in tex.image.pixels:
413                                                                 texdata += "\\x%02X"%int(p*255)
414                                                         texdata += '"'
415                                                         out_file.write("raw_data", texdata)
416                                                         out_file.end()
417                                                 else:
418                                                         out_file.write("texture", '"%s"'%tex.image.name)
419                                                 out_file.end()
420
421                         out_file.end()
422                         out_file.end()
423
424                 progress.set_task("Done", 1.0, 1.0)
425
426                 for m in bmeshes:
427                         bpy.data.meshes.remove(m)