]> git.tdb.fi Git - libs/gl.git/blobdiff - blender/io_mspgl/export_object.py
Make resource handling in the Blender exporter more flexible
[libs/gl.git] / blender / io_mspgl / export_object.py
index a8af6d1f9b6a87e2334fa4deeafe74062c66821c..34724221184e600b8c40e9a53974275e0a34ffd8 100644 (file)
@@ -1,4 +1,5 @@
 import os
+import mathutils
 
 def linear_to_srgb(l):
        if l<0.0031308:
@@ -6,134 +7,259 @@ def linear_to_srgb(l):
        else:
                return 1.055*(l**(1/2.4))-0.055
 
+def get_colormap(srgb):
+       if srgb:
+               return linear_to_srgb
+       else:
+               return lambda x: x
+
+def image_name(i):
+       fp = i.filepath
+       if fp:
+               return os.path.split(fp)[1]
+       else:
+               return i.name
+
 
 class ObjectExporter:
        def __init__(self):
-               self.material_tex = False
-               self.srgb_colors = True
+               self.show_progress = True
+               self.use_strips = True
+               self.use_degen_tris = False
                self.textures = "REF"
                self.separate_mesh = False
                self.separate_tech = False
-               self.external_tech = True
-               self.shared_tech = True
+               self.shared_resources = True
+               self.export_lods = True
 
-       def export(self, context, out_file, objs=None, progress=None):
-               if objs is None:
-                       obj = context.active_object
-               else:
-                       obj = objs[0]
+       def compute_bounding_sphere(self, obj):
+               p1 = max(((v.co, v.co.length) for v in obj.data.vertices), key=lambda x:x[1])[0]
+               p2 = max(((v.co, (v.co-p1).length) for v in obj.data.vertices), key=lambda x:x[1])[0]
+               center = (p1+p2)/2
+               radius = (p1-p2).length/2
+               for v in obj.data.vertices:
+                       d = v.co-center
+                       if d.length>radius:
+                               center += d*(1-radius/d.length)/2
+                               radius = (radius+d.length)/2
+
+               return center, radius
+
+       def collect_object_lods(self, obj):
+               lods = [obj]
+               if self.export_lods:
+                       lods += sorted([c for c in obj.children if c.lod_for_parent], key=(lambda l: l.lod_index))
+                       for i, l in enumerate(lods):
+                               if i>0 and l.lod_index!=i:
+                                       raise Exception("Inconsistent LOD indices")
 
-               from .outfile import open_output
-               out_file = open_output(out_file)
+               return lods
 
+       def create_mesh_exporter(self):
                from .export_mesh import MeshExporter
                mesh_export = MeshExporter()
-               for k, v in self.__dict__.items():
-                       setattr(mesh_export, k, v)
-
-               if self.separate_mesh:
-                       path, base = os.path.split(out_file.filename)
-                       base, ext = os.path.splitext(base)
-                       mesh_out = open_output(os.path.join(path, base+".mesh"))
-                       mesh = mesh_export.export(context, mesh_out, objs, progress)
-                       out_file.write("mesh", '"{}.mesh"'.format(base))
-               else:
-                       out_file.begin("mesh")
-                       mesh = mesh_export.export(context, out_file, objs, progress)
-                       out_file.end()
-
-               if self.external_tech and obj.technique:
-                       out_file.write("technique", '"{}"'.format(obj.technique))
-               elif self.separate_tech:
-                       path, base = os.path.split(out_file.filename)
-                       if self.shared_tech and mesh.materials:
-                               tech_name = mesh.materials[0].name+".tech"
-                       else:
-                               base, ext = os.path.splitext(base)
-                               tech_name = base+".tech"
-                       tech_out = open_output(os.path.join(path, tech_name))
-                       self.export_technique(mesh, tech_out)
-                       out_file.write("technique", '"{}"'.format(tech_name))
-               else:
-                       out_file.begin("technique")
-                       self.export_technique(mesh, out_file)
-                       out_file.end()
-
-       def export_technique(self, mesh, out_file):
-               out_file.begin("pass", '""')
-               if mesh.materials:
-                       if self.srgb_colors:
-                               cm = linear_to_srgb
-                       else:
-                               cm = lambda x: x
-
-                       if self.material_tex:
-                               out_file.begin("material")
-                               out_file.write("diffuse", 1.0, 1.0, 1.0, 1.0)
-                               out_file.end()
-                               index = 0
-                               for u in mesh.uv_layers:
-                                       if u.name=="material_tex":
-                                               index = u.unit
-                               out_file.begin("texunit", index)
-                               out_file.begin("texture2d")
-                               out_file.write("min_filter", "NEAREST")
-                               out_file.write("mag_filter", "NEAREST")
-                               out_file.write("storage", "RGB", len(mesh.materials), 1)
-                               texdata = '"'
-                               for m in mesh.materials:
-                                       color = [int(cm(c)*255) for c in m.diffuse_color]
-                                       texdata += "\\x%02X\\x%02X\\x%02X"%tuple(color)
-                               texdata += '"'
-                               out_file.write("raw_data", texdata)
-                               out_file.end()
-                               out_file.end()
-                       else:
-                               mat = mesh.materials[0]
-                               out_file.begin("material")
-                               if any((s and s.use_map_color_diffuse) for s in mat.texture_slots):
-                                       out_file.write("diffuse", 1.0, 1.0, 1.0, 1.0)
-                                       amb = cm(mat.ambient)
-                                       out_file.write("ambient", amb, amb, amb, 1.0)
+               mesh_export.use_strips = self.use_strips
+               mesh_export.use_degen_tris = self.use_degen_tris
+               return mesh_export
+
+       def export_to_file(self, context, out_fn):
+               obj = context.active_object
+
+               from .util import Progress
+               progress = Progress(self.show_progress and context)
+
+               path, base = os.path.split(out_fn)
+               base = os.path.splitext(base)[0]
+
+               resources = {}
+               self.export_object_resources(context, obj, resources, progress)
+
+               obj_res = self.export_object(context, obj, progress, resources=resources)
+               refs = obj_res.collect_references()
+               if not self.shared_resources:
+                       numbers = {}
+                       for r in refs:
+                               ext = os.path.splitext(r.name)[1]
+                               n = numbers.get(ext, 0)
+                               if n>0:
+                                       r.name = "{}_{}{}".format(base, n, ext)
                                else:
-                                       diff = mat.diffuse_color
-                                       out_file.write("diffuse", cm(diff.r), cm(diff.g), cm(diff.b), 1.0)
-                                       amb = diff*mat.ambient
-                                       out_file.write("ambient", cm(amb.r), cm(amb.g), cm(amb.b), 1.0)
-                               spec = mat.specular_color*mat.specular_intensity
-                               out_file.write("specular", spec.r, spec.g, spec.b, 1.0)
-                               out_file.write("shininess", mat.specular_hardness);
-                               out_file.end()
+                                       r.name = base+ext
+                               numbers[ext] = n+1
 
-                       if self.textures!="NONE":
-                               for slot in mesh.materials[0].texture_slots:
-                                       if not slot:
-                                               continue
-
-                                       tex = slot.texture
-                                       if tex.type!="IMAGE":
-                                               continue
-
-                                       if slot.uv_layer:
-                                               for u in mesh.uv_layers:
-                                                       if u.name==slot.uv_layer:
-                                                               index = u.unit
+               for r in refs:
+                       with open(os.path.join(path, r.name), "w") as out_file:
+                               for s in r.statements:
+                                       s.write_to_file(out_file)
+
+               with open(out_fn, "w") as out_file:
+                       for s in obj_res.statements:
+                               s.write_to_file(out_file)
+
+       def export_object_resources(self, context, obj, resources, progress):
+               lods = self.collect_object_lods(obj)
+
+               from .mesh import create_mesh_from_object
+               mesh_export = self.create_mesh_exporter()
+
+               for i, l in enumerate(lods):
+                       lod_index = l.lod_index if l.lod_for_parent else 0
+                       progress.push_task_slice("LOD {}".format(lod_index), i, len(lods))
+
+                       mesh_name = l.data.name+".mesh"
+                       if mesh_name not in resources:
+                               mesh = create_mesh_from_object(context, l, progress)
+                               mesh_res = mesh_export.export_mesh(context, mesh, progress)
+                               resources[mesh_name] = mesh_res
+
+                       material = None
+                       if l.material_slots and l.material_slots[0].material:
+                               material = l.material_slots[0].material
+                               mat_name = material.name+".mat"
+                               if mat_name not in resources:
+                                       resources[mat_name] = self.export_material(material)
+
+                       tech_name = (material.name if material else l.name)+".tech"
+                       if tech_name not in resources:
+                               resources[tech_name] = self.export_object_technique(l, resources=resources)
+
+                       progress.pop_task()
+
+       def export_object(self, context, obj, progress, *, resources=None):
+               if resources is None:
+                       resources = {}
+                       self.export_object_resources(context, obj, resources, progress)
+
+               lods = self.collect_object_lods(obj)
+
+               from .datafile import Resource, Statement
+               obj_res = Resource(obj.name+".object")
+               statements = obj_res.statements
+
+               center, radius = self.compute_bounding_sphere(obj)
+               statements.append(Statement("bounding_sphere_hint", *center, radius))
+
+               prev_mesh = None
+               prev_tech = (None, None)
+               for i, l in enumerate(lods):
+                       lod_st = []
+
+                       if l.data.name!=prev_mesh:
+                               mesh_res = resources[l.data.name+".mesh"]
+                               if self.separate_mesh:
+                                       lod_st.append(obj_res.create_reference_statement("mesh", mesh_res))
+                               else:
+                                       lod_st.append(obj_res.create_embed_statement("mesh", mesh_res))
+
+                               prev_mesh = l.data.name
+
+                       mat_name = None
+                       if l.material_slots and l.material_slots[0].material:
+                               mat_name = l.material_slots[0].material.name
+
+                       tech = (l.technique, mat_name)
+                       if tech!=prev_tech:
+                               tech_res = resources[(mat_name or l.name)+".tech"]
+                               if l.technique:
+                                       if l.inherit_tech:
+                                               lod_st.append(obj_res.create_embed_statement("technique", tech_res))
                                        else:
-                                               index = mesh.uv_layers[0].unit
+                                               lod_st.append(Statement("technique", l.technique))
+                               elif self.separate_tech:
+                                       lod_st.append(obj_res.create_reference_statement("technique", tech_res))
+                               else:
+                                       lod_st.append(obj_res.create_embed_statement("technique", tech_res))
+
+                               prev_tech = tech
+
+                       if i>0:
+                               st = Statement("level_of_detail", i)
+                               st.sub = lod_st
+                               statements.append(st)
+                       else:
+                               statements += lod_st
+
+               progress.set_progress(1.0)
+
+               return obj_res
 
-                                       out_file.begin("texunit", index)
+       def export_object_technique(self, obj, *, resources):
+               material = None
+               if obj.material_slots:
+                       material = obj.material_slots[0].material
+
+               from .datafile import Resource, Statement, Token
+               tech_res = Resource((material.name if material else obj.name)+".tech")
+
+               mat_res = None
+               if material:
+                       mat_res = resources[material.name+".mat"]
+
+               if obj.technique:
+                       if not obj.inherit_tech:
+                               return tech_res
+
+                       st = Statement("inherit", obj.technique)
+                       if material:
+                               for slot in material.texture_slots:
+                                       if slot and slot.texture.type=="IMAGE":
+                                               name = image_name(slot.texture.image)
+                                               if slot.use_map_color_diffuse:
+                                                       st.sub.append(Statement("texture", "diffuse_map", name))
+                                               elif slot.use_map_normal:
+                                                       st.sub.append(Statement("texture", "normal_map", name))
+                               if obj.override_material:
+                                       st.sub.append(tech_res.create_reference_statement("material", "surface", mat_res))
+                       tech_res.statements.append(st)
+
+                       return tech_res
+
+               pass_st = Statement("pass", "")
+               if material:
+                       pass_st.sub.append(tech_res.create_embed_statement("material", mat_res))
+
+                       if self.textures!="NONE":
+                               diffuse_tex = None
+                               for slot in material.texture_slots:
+                                       if slot and slot.texture.type=="IMAGE" and slot.use_map_color_diffuse:
+                                               diffuse_tex = slot.texture
+                                               break
+
+                               if diffuse_tex:
+                                       st = Statement("texunit", 0)
                                        if self.textures=="INLINE":
-                                               out_file.begin("texture2d")
-                                               out_file.write("min_filter", "LINEAR")
-                                               out_file.write("storage", "RGBA", tex.image.size[0], tex.image.size[1])
-                                               texdata = '"'
+                                               ss = Statement("texture2d")
+                                               ss.sub.append(Statement("min_filter", Token("LINEAR")))
+                                               ss.sub.append(Statement("storage", Token("RGBA"), tex.image.size[0], tex.image.size[1]))
+                                               texdata = ""
                                                for p in tex.image.pixels:
                                                        texdata += "\\x%02X"%int(p*255)
-                                               texdata += '"'
-                                               out_file.write("raw_data", texdata)
-                                               out_file.end()
-                                       else:
-                                               out_file.write("texture", '"%s"'%tex.image.name)
-                                       out_file.end()
+                                               ss.sub.append(Statement("raw_data", texdata))
+                                               st.sub.append(ss)
+                                       elif tex.image:
+                                               st.sub.append(Statement("texture", image_name(tex.image)))
+                                       pass_st.sub.append(st)
+               tech_res.statements.append(pass_st)
+
+               return tech_res
+
+       def export_material(self, material):
+               from .datafile import Resource, Statement
+               mat_res = Resource(material.name+".mat")
+               statements = mat_res.statements
+
+               cm = get_colormap(material.srgb_colors)
+               if any(s.use_map_color_diffuse for s in material.texture_slots if s):
+                       statements.append(Statement("diffuse", 1.0, 1.0, 1.0, 1.0))
+                       amb = cm(material.ambient)
+                       statements.append(Statement("ambient", amb, amb, amb, 1.0))
+               else:
+                       diff = material.diffuse_color*material.diffuse_intensity
+                       statements.append(Statement("diffuse", cm(diff.r), cm(diff.g), cm(diff.b), 1.0))
+                       amb = diff*material.ambient
+                       statements.append(Statement("ambient", cm(amb.r), cm(amb.g), cm(amb.b), 1.0))
+               spec = material.specular_color*material.specular_intensity
+               statements.append(Statement("specular", cm(spec.r), cm(spec.g), cm(spec.g), 1.0))
+               statements.append(Statement("shininess", material.specular_hardness))
 
-               out_file.end()
+               return mat_res