OSDN Git Service

separate vertex with uv or normal.
authorousttrue <ousttrue@gmail.com>
Sun, 11 Jul 2010 01:54:56 +0000 (10:54 +0900)
committerousttrue <ousttrue@gmail.com>
Sun, 11 Jul 2010 01:54:56 +0000 (10:54 +0900)
swig/blender/bl24.py
swig/blender/bl25.py
swig/blender/mqo_export.py
swig/blender/pmd_export.py
swig/blender/pmd_import.py

index f57b1c7..9c28140 100755 (executable)
@@ -388,6 +388,15 @@ class material:
                     continue
                 yield image.getFilename()
 
+    @staticmethod
+    def eachEnalbeTexturePath(m, dirname):
+        for i, texture in enumerate(m.getTextures()):
+            if (i in m.enabledTextures) and texture and texture.tex and texture.tex.getImage():
+                image=texture.tex.getImage()
+                if not image:
+                    continue
+                yield image.getFilename()
+
 
 class mesh:
     @staticmethod
@@ -462,12 +471,16 @@ class mesh:
 
 class vertex:
     @staticmethod
-    def setNormal(mvert, normal):
-        mvert.no=Mathutils.Vector(*normal)
+    def getNormal(v):
+        return v.no
+
+    @staticmethod
+    def setNormal(v, normal):
+        v.no=Mathutils.Vector(*normal)
 
     @staticmethod
-    def setUv(mvert, uv):
-        mvert.uvco=uv
+    def setUv(v, uv):
+        v.uvco=uv
 
 
 class face:
index a1ed64b..d0138b3 100755 (executable)
@@ -337,16 +337,16 @@ class material:
         return index
 
     @staticmethod
-    def getTexture(material, index):
-        return material.texture_slots[index].texture
+    def getTexture(m, index):
+        return m.texture_slots[index].texture
 
     @staticmethod
-    def hasTexture(material):
-        return material.texture_slots[0]
+    def hasTexture(m):
+        return m.texture_slots[0]
 
     @staticmethod
-    def setUseTexture(material, index, enable):
-        material.use_textures[index]=enable
+    def setUseTexture(m, index, enable):
+        m.use_textures[index]=enable
 
     @staticmethod
     def eachTexturePath(m):
@@ -359,6 +359,17 @@ class material:
                         continue
                     yield image.filename
 
+    @staticmethod
+    def eachEnalbeTexturePath(m):
+        for i, slot in enumerate(m.texture_slots):
+            if m.use_textures[i] and slot and slot.texture:
+                texture=slot.texture
+                if  texture.type=="IMAGE":
+                    image=texture.image
+                    if not image:
+                        continue
+                    yield image.filename
+
 
 class mesh:
     @staticmethod
@@ -477,11 +488,16 @@ class mesh:
 
 class vertex:
     @staticmethod
-    def setNormal(mvert, normal):
-        mvert.normal=mathutils.Vector(normal)
+    def setNormal(v, normal):
+        v.normal=mathutils.Vector(normal)
+
+    @staticmethod
+    def getNormal(v):
+        return v.normal
 
     @staticmethod
-    def setUv(mvert, uv):
+    def setUv(v, uv):
+        # sticky ?
         pass
 
 
index 9b87a10..aeb971c 100644 (file)
@@ -21,6 +21,7 @@ Run this script from "File->Export" menu.
 0.2 20100518: refactoring.\r
 0.3 20100606: integrate 2.4 and 2.5.\r
 0.4 20100626: refactoring.\r
+0.5 20100710: add [apply_modifier] option(2.5 only).\r
 """\r
 \r
 import os\r
@@ -45,7 +46,6 @@ if isBlender24():
 else:\r
     # for 2.5\r
     import bpy\r
-    from bpy.props import *\r
 \r
     # wrapper\r
     import bl25 as bl\r
@@ -89,11 +89,12 @@ class ObjectInfo(object):
 \r
 \r
 class MqoExporter(object):\r
-    __slots__=["materials", "objects", 'scale',]\r
-    def __init__(self, scale):\r
+    __slots__=["materials", "objects", 'scale', 'apply_modifier',]\r
+    def __init__(self, scale, apply_modifier):\r
         self.objects=[]\r
         self.materials=[]\r
         self.scale=scale\r
+        self.apply_modifier=apply_modifier\r
 \r
     def setup(self, scene):\r
         # 木構造を構築する\r
@@ -189,9 +190,10 @@ class MqoExporter(object):
         io.write("\tdepth %d\r\n" % info.depth)\r
 \r
         # mirror\r
-        if bl.modifier.hasType(obj, 'MIRROR'):\r
-                io.write("\tmirror 1\r\n")\r
-                io.write("\tmirror_axis 1\r\n")\r
+        if not self.apply_modifier:\r
+            if bl.modifier.hasType(obj, 'MIRROR'):\r
+                    io.write("\tmirror 1\r\n")\r
+                    io.write("\tmirror_axis 1\r\n")\r
 \r
         if obj.type.upper()=='MESH':\r
             # duplicate and applyMatrix\r
@@ -203,6 +205,17 @@ class MqoExporter(object):
             bpy.ops.object.rotation_apply()\r
             copyObj.location=obj.location\r
             bpy.ops.object.location_apply()\r
+            # apply modifier\r
+            if self.apply_modifier:\r
+                for m in [m for m in copyObj.modifiers]:\r
+                    if m.type=='SOLIDFY':\r
+                        continue\r
+                    elif m.type=='ARMATURE':\r
+                        bpy.ops.object.modifier_apply(modifier=m.name)\r
+                    elif m.type=='MIRROR':\r
+                        bpy.ops.object.modifier_apply(modifier=m.name)\r
+                    else:\r
+                        print(m.type)\r
             # write mesh\r
             self.__write_mesh(io, copyMesh, info.material_map)\r
             bl.object.delete(copyObj)\r
@@ -242,12 +255,12 @@ class MqoExporter(object):
         io.write("\t}\r\n") # end of faces\r
 \r
 \r
-def __execute(filename, scene, scale=10):\r
+def __execute(filename, scene, scale=10, apply_modifier=False):\r
     if not scene.objects.active:\r
         bl.message('no active object !')\r
         return\r
 \r
-    exporter=MqoExporter(scale)\r
+    exporter=MqoExporter(scale, apply_modifier)\r
     exporter.setup(scene)\r
     exporter.write(filename)\r
 \r
@@ -259,7 +272,7 @@ if isBlender24():
         bl.initialize('mqo_export', scene)\r
         __execute(\r
                 filename.decode(bl.INTERNAL_ENCODING), \r
-                scene)\r
+                scene, False)\r
         bl.finalize()\r
 \r
     # execute\r
@@ -270,9 +283,9 @@ if isBlender24():
 \r
 else:\r
     # for 2.5\r
-    def execute_25(path, scene, scale):\r
+    def execute_25(path, scene, scale, apply_modifier):\r
         bl.initialize('mqo_export', scene)\r
-        __execute(path, scene, scale)\r
+        __execute(path, scene, scale, apply_modifier)\r
         bl.finalize()\r
 \r
     # operator\r
@@ -284,26 +297,31 @@ else:
         # List of operator properties, the attributes will be assigned\r
         # to the class instance from the operator settings before calling.\r
 \r
-        path = StringProperty(\r
+        path = bpy.props.StringProperty(\r
                 name="File Path",\r
                 description="File path used for exporting the MQO file",\r
                 maxlen= 1024,\r
                 default= ""\r
                 )\r
-        filename = StringProperty(\r
+        filename = bpy.props.StringProperty(\r
                 name="File Name", \r
                 description="Name of the file.")\r
-        directory = StringProperty(\r
+        directory = bpy.props.StringProperty(\r
                 name="Directory", \r
                 description="Directory of the file.")\r
 \r
-        scale = FloatProperty(\r
+        scale = bpy.props.FloatProperty(\r
                 name="Scale", \r
                 description="Scale the MQO by this value", \r
                 min=0.0001, max=1000000.0, \r
                 soft_min=0.001, soft_max=100.0, default=10.0)\r
 \r
-        check_existing = BoolProperty(\r
+        apply_modifier = bpy.props.BoolProperty(\r
+                name="ApplyModifier", \r
+                description="Would apply modifiers", \r
+                default=False)\r
+\r
+        check_existing = bpy.props.BoolProperty(\r
                 name="Check Existing",\r
                 description="Check and warn on overwriting existing files",\r
                 default=True,\r
@@ -313,7 +331,8 @@ else:
             execute_25(\r
                     self.properties.path, \r
                     context.scene, \r
-                    self.properties.scale)\r
+                    self.properties.scale,\r
+                    self.properties.apply_modifier)\r
             return 'FINISHED'\r
 \r
         def invoke(self, context, event):\r
index 52ff883..9f5eec4 100644 (file)
@@ -23,6 +23,7 @@ This script exports a pmd model.
 1.4 20100626: refactoring.
 1.5 20100629: sphere map.
 1.6 20100710: toon texture & bone group.
+1.7 20100711: separate vertex with normal or uv.
 """
 
 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
@@ -143,23 +144,12 @@ def near(x, y, EPSILON=1e-5):
     return d>=-EPSILON and d<=EPSILON
 
 
-class VertexKey(object):
-    """
-    重複頂点の検索キー
-    """
+class VertexAttribute(object):
     __slots__=[
-            'obj', 'index',
-            'x', 'y', 'z', # 位置
-            'nx', 'ny', 'nz', # 法線
+            'nx', 'ny', 'nz', # normal
             'u', 'v', # uv
             ]
-
-    def __init__(self, obj, index, x, y, z, nx, ny, nz, u, v):
-        self.obj=obj
-        self.index=index
-        self.x=x
-        self.y=y
-        self.z=z
+    def __init__(self, nx, ny, nz, u, v):
         self.nx=nx
         self.ny=ny
         self.nz=nz
@@ -167,19 +157,33 @@ class VertexKey(object):
         self.v=v
 
     def __str__(self):
-        return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
-                self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
+        return "<vkey: %f, %f, %f, %f, %f>" % (
+                self.nx, self.ny, self.nz, self.u, self.v)
 
     def __hash__(self):
-        #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
-        #return int((self.x+self.y+self.z)*100)
-        return self.index*100+self.obj
+        return self.nx + self.ny + self.nz + self.u + self.v
 
     def __eq__(self, rhs):
-        #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z) and near(self.nx, rhs.nx) and near(self.ny, rhs.ny) and near(self.nz, rhs.nz) and near(self.u, rhs.u) and near(self.v, rhs.v)
-        #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
-        #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
-        return self.obj==rhs.obj and self.index==rhs.index
+        return self.nx==rhs.nx and self.ny==rhs.ny and self.nz==rhs.nz and self.u==rhs.u and self.v==rhs.v
+
+
+class VertexKey(object):
+    __slots__=[
+            'obj_index', 'index',
+            ]
+
+    def __init__(self, obj_index, index):
+        self.obj_index=obj_index
+        self.index=index
+
+    def __str__(self):
+        return "<vkey: %d, %d>" % (self.obj_index, self.index)
+
+    def __hash__(self):
+        return self.index*100+self.obj_index
+
+    def __eq__(self, rhs):
+        return self.obj_index==rhs.obj_index and self.index==rhs.index
 
 
 class VertexArray(object):
@@ -188,36 +192,32 @@ class VertexArray(object):
     """
     __slots__=[
             'indexArrays',
-            'vertices',
-            'normals',
-            'uvs',
+            'positions',
+            'attributes', # normal and uv
             'b0', 'b1', 'weight',
             'vertexMap',
             'objectMap',
             ]
     def __init__(self):
-        # マテリアル毎に分割したインデックス配列
+        # indexArrays split with each material
         self.indexArrays={}
-        # 頂点属性
-        self.vertices=[]
-        self.normals=[]
-        self.uvs=[]
-        # skinning属性
+
+        self.positions=[]
+        self.attributes=[]
         self.b0=[]
         self.b1=[]
         self.weight=[]
 
         self.vertexMap={}
-        #self.indexMap={}
         self.objectMap={}
 
     def __str__(self):
-        return "<VertexArray %d vertices, %d indexArrays>" % (
-                len(self.vertices), len(self.indexArrays))
+        return "<VertexArray %d positions, %d indexArrays>" % (
+                len(self.positions), len(self.indexArrays))
 
     def zip(self):
         return zip(
-                self.vertices, self.normals, self.uvs,
+                self.positions, self.attributes,
                 self.b0, self.b1, self.weight)
 
     def each(self):
@@ -226,48 +226,39 @@ class VertexArray(object):
         for key in keys:
             yield(key, self.indexArrays[key])
 
-    def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
-        """
-        頂点属性からその頂点のインデックスを得る
-        """
-        key=VertexKey(
-                obj, base_index,
-                pos[0], pos[1], pos[2],
+    def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
+        key=VertexKey(obj_index, base_index)
+        attribute=VertexAttribute( 
                 normal[0], normal[1], normal[2],
                 uv[0], uv[1])
         if key in self.vertexMap:
-            # 同じ頂点を登録済み
-            index=self.vertexMap[key]
+            if attribute in self.vertexMap[key]:
+                return self.vertexMap[key][attribute]
+            else:
+                return self.__addVertex(self.vertexMap[key],
+                        pos, attribute, b0, b1, weight0)
         else:
-            index=len(self.vertices)
-            # 新規頂点
-            self.vertexMap[key]=index
-            # append...
-            self.vertices.append((pos.x, pos.y, pos.z))
-            self.normals.append((normal.x, normal.y, normal.z))
-            self.uvs.append((uv[0], uv[1]))
-            self.b0.append(b0)
-            self.b1.append(b1)
-            self.weight.append(weight0)
-            
-        # indexのマッピングを保存する
-        #if not base_index in self.indexMap:
-        #    self.indexMap[base_index]=set()
-        #self.indexMap[base_index].add(index)
-
+            vertexMapKey={}
+            self.vertexMap[key]=vertexMapKey
+            return self.__addVertex(vertexMapKey,
+                    pos, attribute, b0, b1, weight0)
+
+    def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
+        index=len(self.positions)
+        vertexMapKey[attribute]=index
+        # position
+        self.positions.append((pos.x, pos.y, pos.z))
+        # unique attribute
+        self.attributes.append(attribute)
+        # shared attribute
+        self.b0.append(b0)
+        self.b1.append(b1)
+        self.weight.append(weight0)
         assert(index<=65535)
         return index
-
+            
     def getMappedIndex(self, obj_name, base_index):
-        key=VertexKey(
-                self.objectMap[obj_name], base_index,
-                None, None, None,
-                None, None, None,
-                None, None)
-        return self.vertexMap[key]
-
-    def getMappedIndices(self, obj, base_index):
-        return self.indexMap[base_index]
+        return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
 
     def addTriangle(self,
             object_name, material,
@@ -280,13 +271,13 @@ class VertexArray(object):
             weight0, weight1, weight2
             ):
         if object_name in self.objectMap:
-            obj=self.objectMap[object_name]
+            obj_index=self.objectMap[object_name]
         else:
-            obj=len(self.objectMap)
-            self.objectMap[object_name]=obj
-        index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
-        index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
-        index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
+            obj_index=len(self.objectMap)
+            self.objectMap[object_name]=obj_index
+        index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
+        index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
+        index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
 
         if not material in self.indexArrays:
             self.indexArrays[material]=[]
@@ -374,6 +365,7 @@ class OneSkinMesh(object):
                 else:
                     weightMap[i]=(name, w)
 
+        # ToDo bone weightと関係ないvertex groupを除外する
         if isBlender24():
             for name in bl.object.getVertexGroupNames(obj):
                 for i, w in mesh.getVertsFromGroup(name, 1):
@@ -420,11 +412,9 @@ class OneSkinMesh(object):
                         v[2].co, 
                         v[1].co, 
                         v[0].co,
-                        # ToDo vertex normal
-                        #v0.no, v1.no, v2.no,
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face),
+                        bl.vertex.getNormal(v[2]), 
+                        bl.vertex.getNormal(v[1]), 
+                        bl.vertex.getNormal(v[0]),
                         uv[2], 
                         uv[1], 
                         uv[0],
@@ -448,10 +438,9 @@ class OneSkinMesh(object):
                         v[2].co, 
                         v[1].co, 
                         v[0].co,
-                        #v0.no, v1.no, v2.no,
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face), 
+                        bl.vertex.getNormal(v[2]), 
+                        bl.vertex.getNormal(v[1]), 
+                        bl.vertex.getNormal(v[0]), 
                         uv[2], 
                         uv[1], 
                         uv[0],
@@ -473,10 +462,9 @@ class OneSkinMesh(object):
                         v[0].co, 
                         v[3].co, 
                         v[2].co,
-                        #v2.no, v3.no, v0.no,
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face), 
-                        bl.face.getNormal(face), 
+                        bl.vertex.getNormal(v[0]), 
+                        bl.vertex.getNormal(v[3]), 
+                        bl.vertex.getNormal(v[2]), 
                         uv[0], 
                         uv[3], 
                         uv[2],
@@ -525,7 +513,7 @@ class OneSkinMesh(object):
             elif m.type=='MIRROR':
                 bpy.ops.object.modifier_apply(modifier=m.name)
             else:
-                print(m.tpye)
+                print(m.type)
 
         weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
         self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
@@ -557,19 +545,16 @@ class OneSkinMesh(object):
                 for index in vg:
                     v=bl.shapekey.getByIndex(b, index)
                     pos=[v[0], v[1], v[2]]
-                    i=self.vertexArray.getMappedIndex(obj.name, index)
-                    baseMorph.add(i, pos)
-                    indexRelativeMap[i]=relativeIndex
-                    relativeIndex+=1
-                    #indices=self.vertexArray.getMappedIndices(index)
-                    #for i in indices:
-                    #    if i in used:
-                    #        continue
-                    #    used.add(i)
-
-                    #    baseMorph.add(i, pos)
-                    #    indexRelativeMap[i]=relativeIndex
-                    #    relativeIndex+=1
+
+                    indices=self.vertexArray.getMappedIndex(obj.name, index)
+                    for attribute, i in indices.items():
+                        if i in used:
+                            continue
+                        used.add(i)
+
+                        baseMorph.add(i, pos)
+                        indexRelativeMap[i]=relativeIndex
+                        relativeIndex+=1
 
                 break
         assert(basis)
@@ -594,17 +579,12 @@ class OneSkinMesh(object):
                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
                     continue
                 if index in vg:
-                    i=self.vertexArray.getMappedIndex(obj.name, index)
-                    if i in used:
-                        continue
-                    used.add(i) 
-                    morph.add(indexRelativeMap[i], offset)
-                    #indices=self.vertexArray.getMappedIndices(index)
-                    #for i in indices:
-                    #    if i in used:
-                    #        continue
-                    #    used.add(i) 
-                    #    morph.add(indexRelativeMap[i], offset)
+                    indices=self.vertexArray.getMappedIndex(obj.name, index)
+                    for attribute, i in indices.items():
+                        if i in used:
+                            continue
+                        used.add(i) 
+                        morph.add(indexRelativeMap[i], offset)
             assert(len(morph.offsets)<len(baseMorph.offsets))
 
         # sort skinmap
@@ -643,7 +623,7 @@ class OneSkinMesh(object):
         return m
 
     def getVertexCount(self):
-        return len(self.vertexArray.vertices)
+        return len(self.vertexArray.positions)
 
 
 class Bone(object):
@@ -936,17 +916,17 @@ class PmdExporter(object):
         io.version=1.0
 
         # 頂点
-        for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
+        for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
             # convert right-handed z-up to left-handed y-up
             v=io.addVertex()
             v.pos.x=pos[0]
             v.pos.y=pos[2]
             v.pos.z=pos[1]
-            v.normal.x=normal[0]
-            v.normal.y=normal[2]
-            v.normal.z=normal[1]
-            v.uv.x=uv[0]
-            v.uv.y=1.0-uv[1] # reverse vertical
+            v.normal.x=attribute.nx
+            v.normal.y=attribute.ny
+            v.normal.z=attribute.nz
+            v.uv.x=attribute.u
+            v.uv.y=1.0-attribute.v # reverse vertical
             v.bone0=self.skeleton.indexByName(b0)
             v.bone1=self.skeleton.indexByName(b1)
             v.weight0=int(100*weight)
@@ -964,7 +944,7 @@ class PmdExporter(object):
             material.vertex_count=len(indices)
             material.toon_index=0
             textures=[os.path.basename(path) 
-                for path in bl.material.eachTexturePath(m)]
+                for path in bl.material.eachEnalbeTexturePath(m)]
             if len(textures)>0:
                 material.setTexture(toCP932('*'.join(textures)))
             else:
index 206a614..f8062e0 100755 (executable)
@@ -446,15 +446,7 @@ def __import16MaerialAndMesh(meshObject, l,
         except KeyError:
             break
 
-        material=createPmdMaterial(m, material_index)
-        toon_index=bl.material.addTexture(
-                material, 
-                bl.material.getTexture(
-                    toon_material, 
-                    0 if m.toon_index==0xFF else m.toon_index
-                    ),
-                False)
-
+        # main texture
         texture_name=m.getTexture()
         if texture_name!='':
             for i, t in enumerate(texture_name.split('*')):
@@ -473,7 +465,18 @@ def __import16MaerialAndMesh(meshObject, l,
                     # sphere map
                     setSphereMap(material, texture_index, 'ADD')
 
+        # toon texture
+        material=createPmdMaterial(m, material_index)
+        toon_index=bl.material.addTexture(
+                material, 
+                bl.material.getTexture(
+                    toon_material, 
+                    0 if m.toon_index==0xFF else m.toon_index
+                    ),
+                False)
+
         bl.mesh.addMaterial(mesh, material)
+
         index+=1
 
     ############################################################