4 Name: 'Metasequoia(.mqo)...'
\r
7 Tooltip: 'Import from Metasequoia file format (.mqo)'
\r
9 __author__=['ousttrue']
\r
10 __url__ = ["http://gunload.web.fc2.com/blender/"]
\r
16 This script imports a mqo into Blender for editing.
\r
18 0.2 20080123: update.
\r
19 0.3 20091125: modify for linux.
\r
20 0.4 20100310: rewrite.
\r
21 0.5 20100311: create armature from mikoto bone.
\r
22 0.6 20100505: C extension.
\r
23 0.7 20100606: integrate 2.4 and 2.5.
\r
24 0.8 20100619: fix multibyte object name.
\r
25 0.9 20100626: refactoring.
\r
26 2.0 20100724: update for Blender2.53.
\r
27 2.1 20100731: add full python module.
\r
28 2.2 20101005: update for Blender2.54.
\r
29 2.3 20101228: update for Blender2.55.
\r
33 'category': 'Import/Export',
\r
34 'name': 'Import: Metasequioa Model Format (.mqo)',
\r
35 'author': 'ousttrue',
\r
37 'blender': (2, 5, 3),
\r
38 'location': 'File > Import',
\r
39 'description': 'Import from the Metasequioa Model Format (.mqo)',
\r
40 'warning': '', # used for warning icon and text in addons panel
\r
41 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
\r
42 'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
\r
50 from meshio import mqo
\r
51 print('use meshio C module')
\r
54 from pymeshio import mqo
\r
57 return sys.version_info[0]<3
\r
62 from Blender import Mathutils
\r
68 def createMqoMaterial(m):
\r
69 material = Blender.Material.New(
\r
70 m.getName().encode(bl.INTERNAL_ENCODING))
\r
71 #material.mode |= Blender.Material.Modes.SHADELESS
\r
73 material.rgbCol = [m.color.r, m.color.g, m.color.b]
\r
74 material.alpha = m.color.a
\r
76 material.amb=m.ambient
\r
77 material.spec=m.specular
\r
78 material.hard=int(255 * m.power)
\r
79 material.emit=m.emit
\r
89 def createMqoMaterial(m):
\r
90 material = bpy.data.materials.new(m.getName())
\r
93 material.diffuse_shader='FRESNEL'
\r
95 material.diffuse_shader='LAMBERT'
\r
97 material.diffuse_color=[m.color.r, m.color.g, m.color.b]
\r
98 material.diffuse_intensity=m.diffuse
\r
99 material.alpha=m.color.a
\r
101 material.ambient = m.ambient
\r
102 #material.specular = m.specular
\r
103 material.emit=m.emit
\r
104 material.use_shadeless=True
\r
108 def has_mikoto(mqo):
\r
109 #for o in mqo.objects:
\r
110 # if o.getName().startswith('bone'):
\r
112 # if o.getName().startswith('sdef'):
\r
114 # if o.getName().startswith('anchor'):
\r
119 def __createMaterials(mqo, directory):
\r
121 create blender materials and renturn material list.
\r
126 if len(mqo.materials)>0:
\r
127 for material_index, m in enumerate(mqo.materials):
\r
129 material=createMqoMaterial(m)
\r
130 materials.append(material)
\r
132 texture_name=m.getTexture()
\r
133 if texture_name!='':
\r
134 if texture_name in textureMap:
\r
135 texture=textureMap[texture_name]
\r
137 # load texture image
\r
138 if os.path.isabs(texture_name):
\r
140 path = texture_name
\r
143 path = os.path.join(directory, texture_name)
\r
145 path=path.replace("\\", "/")
\r
146 if os.path.exists(path):
\r
147 print("create texture:", path)
\r
148 texture, image=bl.texture.create(path)
\r
149 textureMap[texture_name]=texture
\r
150 imageMap[material_index]=image
\r
152 print("%s not exits" % path)
\r
154 bl.material.addTexture(material, texture)
\r
158 return materials, imageMap
\r
161 def __createObjects(mqo, root, materials, imageMap, scale):
\r
163 create blender mesh objects.
\r
168 for o in mqo.objects:
\r
169 mesh, mesh_object=bl.mesh.create(o.getName())
\r
172 stack_depth=len(stack)-1
\r
173 #print(o.depth, stack_depth)
\r
174 if o.depth<stack_depth:
\r
175 for i in range(stack_depth-o.depth):
\r
177 bl.object.makeParent(stack[-1], mesh_object)
\r
178 stack.append(mesh_object)
\r
180 if o.getName().startswith('sdef'):
\r
181 objects.append(mesh_object)
\r
182 elif o.getName().startswith('anchor'):
\r
183 bl.object.setLayerMask(mesh_object, [0, 1])
\r
184 elif o.getName().startswith('bone'):
\r
185 bl.object.setLayerMask(mesh_object, [0, 1])
\r
188 vertices=[(v.x * scale, -v.z * scale, v.y * scale) for v in o.vertices]
\r
194 for i in reversed(range(f.index_count)):
\r
195 face_indices.append(f.getIndex(i))
\r
196 faces.append(face_indices)
\r
197 materialMap[f.material_index]=True
\r
198 bl.mesh.addGeometry(mesh, vertices, faces)
\r
200 # blender limits 16 materials per mesh
\r
201 for i, material_index in enumerate(materialMap.keys()):
\r
204 print("over 16 materials!")
\r
206 bl.mesh.addMaterial(mesh, materials[material_index])
\r
207 materialMap[material_index]=i
\r
210 assert(len(o.faces)==len(mesh.faces))
\r
211 bl.mesh.addUV(mesh)
\r
212 for i, (f, face) in enumerate(zip(o.faces, mesh.faces)):
\r
216 for j in reversed(range(f.index_count)):
\r
217 uv_array.append((f.getUV(j).x, 1.0-f.getUV(j).y))
\r
218 bl.mesh.setFaceUV(mesh, i, face, uv_array,
\r
219 imageMap.get(f.material_index, None))
\r
220 if f.material_index in materialMap:
\r
221 bl.face.setMaterial(face, materialMap[f.material_index])
\r
222 bl.face.setSmooth(face, True)
\r
226 bl.modifier.addMirror(mesh_object)
\r
229 bl.mesh.setSmooth(mesh, o.smoothing)
\r
232 bl.mesh.recalcNormals(mesh_object)
\r
237 ###############################################################################
\r
238 # for mqo mikoto bone.
\r
239 ###############################################################################
\r
240 class MikotoBone(object):
\r
243 'iHead', 'iTail', 'iUp',
\r
244 'vHead', 'vTail', 'vUp',
\r
245 'parent', 'isFloating',
\r
248 def __init__(self, face=None, vertices=None, materials=None):
\r
250 self.isFloating=False
\r
256 self.name=materials[face.material_index].name.encode('utf-8')
\r
258 i0=face.getIndex(0)
\r
259 i1=face.getIndex(1)
\r
260 i2=face.getIndex(2)
\r
267 sqNorm0=e01.getSqNorm()
\r
268 sqNorm1=e12.getSqNorm()
\r
269 sqNorm2=e20.getSqNorm()
\r
270 if sqNorm0>sqNorm1:
\r
271 if sqNorm1>sqNorm2:
\r
277 if sqNorm0>sqNorm2:
\r
289 if sqNorm1<sqNorm2:
\r
295 if sqNorm0<sqNorm2:
\r
305 self.vHead=vertices[self.iHead]
\r
306 self.vTail=vertices[self.iTail]
\r
307 self.vUp=vertices[self.iUp]
\r
309 if self.name.endswith('[]'):
\r
310 basename=self.name[0:-2]
\r
313 self.name="%s_L" % basename
\r
315 self.name="%s_R" % basename
\r
318 def setParent(self, parent, floating=False):
\r
320 self.isFloating=True
\r
322 parent.children.append(self)
\r
324 def printTree(self, indent=''):
\r
325 print("%s%s" % (indent, self.name))
\r
326 for child in self.children:
\r
327 child.printTree(indent+' ')
\r
330 def build_armature(armature, mikotoBone, parent=None):
\r
332 create a armature bone.
\r
334 bone = Armature.Editbone()
\r
335 bone.name = mikotoBone.name.encode('utf-8')
\r
336 armature.bones[bone.name] = bone
\r
338 bone.head = Mathutils.Vector(*mikotoBone.vHead.to_a())
\r
339 bone.tail = Mathutils.Vector(*mikotoBone.vTail.to_a())
\r
342 if mikotoBone.isFloating:
\r
345 bone.options=[Armature.CONNECTED]
\r
347 for child in mikotoBone.children:
\r
348 build_armature(armature, child, bone)
\r
351 def create_armature(mqo):
\r
356 for o in mqo.objects:
\r
357 if o.name.startswith('bone'):
\r
364 for f in boneObject.faces:
\r
365 if f.index_count!=3:
\r
366 print("invalid index_count: %d" % f.index_count)
\r
368 b=MikotoBone(f, boneObject.vertices, mqo.materials)
\r
371 ####################
\r
372 # build mikoto bone tree
\r
373 ####################
\r
374 mikotoRoot=MikotoBone()
\r
376 for b in tailMap.values():
\r
377 # each bone has unique parent or is root bone.
\r
378 if b.iHead in tailMap:
\r
379 b.setParent(tailMap[b.iHead])
\r
382 for e in boneObject.edges:
\r
383 if b.iHead==e.indices[0]:
\r
385 if e.indices[1] in tailMap:
\r
386 b.setParent(tailMap[e.indices[1]], True)
\r
389 elif b.iHead==e.indices[1]:
\r
391 if e.indices[0] in tailMap:
\r
392 b.setParent(tailMap[e.indices[0]], True)
\r
399 b.setParent(mikotoRoot, True)
\r
401 if len(mikotoRoot.children)==0:
\r
402 print("no root bone")
\r
405 if len(mikotoRoot.children)==1:
\r
407 mikotoRoot=mikotoRoot.children[0]
\r
408 mikotoRoot.parent=None
\r
410 mikotoRoot.vHead=Vector3(0, 10, 0)
\r
411 mikotoRoot.vTail=Vector3(0, 0, 0)
\r
413 ####################
\r
415 ####################
\r
416 armature = Armature.New()
\r
418 armature_object = scene.objects.new(armature)
\r
420 act = Armature.NLA.NewAction()
\r
421 act.setActive(armature_object)
\r
423 armature_object.drawMode |= Object.DrawModes.XRAY
\r
424 # armature settings
\r
425 armature.drawType = Armature.OCTAHEDRON
\r
426 armature.envelopes = False
\r
427 armature.vertexGroups = True
\r
428 armature.mirrorEdit = True
\r
429 armature.drawNames=True
\r
432 armature.makeEditable()
\r
433 build_armature(armature, mikotoRoot)
\r
436 return armature_object
\r
439 class TrianglePlane(object):
\r
441 mikoto
\e$BJ}<0%\!<%s$N%"%s%+!<%&%'%$%H7W;;MQ!#
\e(B
\r
444 __slots__=['normal',
\r
447 def __init__(self, v0, v1, v2):
\r
452 def isInsideXY(self, p):
\r
453 v0=Vector2(self.v0.x, self.v0.y)
\r
454 v1=Vector2(self.v1.x, self.v1.y)
\r
455 v2=Vector2(self.v2.x, self.v2.y)
\r
459 c0=Vector2.cross(e01, p-v0)
\r
460 c1=Vector2.cross(e12, p-v1)
\r
461 c2=Vector2.cross(e20, p-v2)
\r
462 if c0>=0 and c1>=0 and c2>=0:
\r
464 if c0<=0 and c1<=0 and c2<=0:
\r
467 def isInsideYZ(self, p):
\r
468 v0=Vector2(self.v0.y, self.v0.z)
\r
469 v1=Vector2(self.v1.y, self.v1.z)
\r
470 v2=Vector2(self.v2.y, self.v2.z)
\r
474 c0=Vector2.cross(e01, p-v0)
\r
475 c1=Vector2.cross(e12, p-v1)
\r
476 c2=Vector2.cross(e20, p-v2)
\r
477 if c0>=0 and c1>=0 and c2>=0:
\r
479 if c0<=0 and c1<=0 and c2<=0:
\r
482 def isInsideZX(self, p):
\r
483 v0=Vector2(self.v0.z, self.v0.x)
\r
484 v1=Vector2(self.v1.z, self.v1.x)
\r
485 v2=Vector2(self.v2.z, self.v2.x)
\r
489 c0=Vector2.cross(e01, p-v0)
\r
490 c1=Vector2.cross(e12, p-v1)
\r
491 c2=Vector2.cross(e20, p-v2)
\r
492 if c0>=0 and c1>=0 and c2>=0:
\r
494 if c0<=0 and c1<=0 and c2<=0:
\r
498 class MikotoAnchor(object):
\r
500 mikoto
\e$BJ}<0%9%1%k%H%s$N%"%s%+!<!#
\e(B
\r
503 "triangles", "bbox",
\r
505 def __init__(self):
\r
509 def push(self, face, vertices):
\r
510 if face.index_count==3:
\r
511 self.triangles.append(TrianglePlane(
\r
512 vertices[face.indices[0]],
\r
513 vertices[face.indices[1]],
\r
514 vertices[face.indices[2]]
\r
516 elif face.index_count==4:
\r
517 self.triangles.append(TrianglePlane(
\r
518 vertices[face.indices[0]],
\r
519 vertices[face.indices[1]],
\r
520 vertices[face.indices[2]]
\r
522 self.triangles.append(TrianglePlane(
\r
523 vertices[face.indices[2]],
\r
524 vertices[face.indices[3]],
\r
525 vertices[face.indices[0]]
\r
529 self.bbox=BoundingBox(vertices[face.indices[0]])
\r
530 for i in face.indices:
\r
531 self.bbox.expand(vertices[i])
\r
534 def calcWeight(self, v):
\r
535 if not self.bbox.isInside(v):
\r
538 if self.anyXY(v.x, v.y) and self.anyYZ(v.y, v.z) and self.anyZX(v.z, v.x):
\r
543 def anyXY(self, x, y):
\r
544 for t in self.triangles:
\r
545 if t.isInsideXY(Vector2(x, y)):
\r
549 def anyYZ(self, y, z):
\r
550 for t in self.triangles:
\r
551 if t.isInsideYZ(Vector2(y, z)):
\r
555 def anyZX(self, z, x):
\r
556 for t in self.triangles:
\r
557 if t.isInsideZX(Vector2(z, x)):
\r
562 def create_bone_weight(scene, mqo, armature_object, objects):
\r
564 create mikoto bone weight.
\r
567 # setup mikoto anchors
\r
568 for o in mqo.objects:
\r
569 if o.name.startswith("anchor"):
\r
571 name=mqo.materials[f.material_index].name
\r
572 if name.endswith('[]'):
\r
573 basename=name[0:-2]
\r
574 v=o.vertices[f.indices[0]]
\r
577 name_L=basename+'_L'
\r
578 if not name_L in anchorMap:
\r
579 anchorMap[name_L]=MikotoAnchor()
\r
580 anchorMap[name_L].push(f, o.vertices)
\r
583 name_R=basename+'_R'
\r
584 if not name_R in anchorMap:
\r
585 anchorMap[name_R]=MikotoAnchor()
\r
586 anchorMap[name_R].push(f, o.vertices)
\r
588 print("no side", v)
\r
590 if not name in anchorMap:
\r
591 anchorMap[name]=MikotoAnchor()
\r
592 anchorMap[name].push(f, o.vertices)
\r
595 # add armature modifier
\r
596 mod=o.modifiers.append(Modifier.Types.ARMATURE)
\r
597 mod[Modifier.Settings.OBJECT] = armature_object
\r
598 mod[Modifier.Settings.ENVELOPES] = False
\r
599 o.makeDisplayList()
\r
600 # create vertex group
\r
601 mesh=o.getData(mesh=True)
\r
602 for name in anchorMap.keys():
\r
603 mesh.addVertGroup(name)
\r
606 # assing vertices to vertex group
\r
608 mesh=o.getData(mesh=True)
\r
609 for i, mvert in enumerate(mesh.verts):
\r
611 for name, anchor in anchorMap.items():
\r
612 weight=anchor.calcWeight(mvert.co)
\r
614 mesh.assignVertsToGroup(
\r
615 name, [i], weight, Mesh.AssignModes.ADD)
\r
618 # debug orphan vertex
\r
619 print('orphan', mvert)
\r
623 def __execute(filename, scene, scale=0.1):
\r
626 if not io.read(filename):
\r
627 bl.message("fail to load %s" % filename)
\r
631 materials, imageMap=__createMaterials(io, os.path.dirname(filename))
\r
632 if len(materials)==0:
\r
633 materials.append(bl.material.create('default'))
\r
636 root=bl.object.createEmpty(os.path.basename(filename))
\r
637 objects=__createObjects(io, root, materials, imageMap, scale)
\r
640 # create mikoto bone
\r
641 armature_object=create_armature(io)
\r
642 if armature_object:
\r
643 root.makeParent([armature_object])
\r
645 # create bone weight
\r
646 create_bone_weight(io, armature_object, objects)
\r
649 ###############################################################################
\r
651 ###############################################################################
\r
654 def execute_24(filename):
\r
655 scene=Blender.Scene.GetCurrent()
\r
656 bl.initialize('mqo_import', scene)
\r
658 filename.decode(bl.INTERNAL_ENCODING),
\r
663 Blender.Window.FileSelector(execute_24, 'Import MQO', '*.mqo')
\r
667 def execute_25(filename, scene, scale):
\r
668 bl.initialize('mqo_import', scene)
\r
669 __execute(filename, scene, scale)
\r
673 class IMPORT_OT_mqo(bpy.types.Operator):
\r
674 '''Import from Metasequoia file format (.mqo)'''
\r
675 bl_idname = "import_scene.mqo"
\r
676 bl_label = 'Import MQO'
\r
678 # List of operator properties, the attributes will be assigned
\r
679 # to the class instance from the operator settings before calling.
\r
680 filepath = bpy.props.StringProperty()
\r
681 filename = bpy.props.StringProperty()
\r
682 directory = bpy.props.StringProperty()
\r
684 scale = bpy.props.FloatProperty(
\r
686 description="Scale the MQO by this value",
\r
687 min=0.0001, max=1000000.0,
\r
688 soft_min=0.001, soft_max=100.0, default=0.1)
\r
690 def execute(self, context):
\r
692 self.properties.filepath,
\r
694 self.properties.scale)
\r
697 def invoke(self, context, event):
\r
698 wm=context.window_manager
\r
700 wm.fileselect_add(self)
\r
702 wm.add_fileselect(self)
\r
703 return 'RUNNING_MODAL'
\r
707 def menu_func(self, context):
\r
708 self.layout.operator(
\r
709 IMPORT_OT_mqo.bl_idname,
\r
710 text="Metasequoia (.mqo)",
\r
715 bpy.types.INFO_MT_file_import.append(menu_func)
\r
718 bpy.types.INFO_MT_file_import.remove(menu_func)
\r
720 if __name__=="__main__":
\r