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
30 2.4 20110429: update for Blender2.57b.
\r
34 'category': 'Import/Export',
\r
35 'name': 'Import: Metasequioa Model Format (.mqo)',
\r
36 'author': 'ousttrue',
\r
38 'blender': (2, 5, 3),
\r
39 'location': 'File > Import',
\r
40 'description': 'Import from the Metasequioa Model Format (.mqo)',
\r
41 'warning': '', # used for warning icon and text in addons panel
\r
42 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
\r
43 'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
\r
51 from meshio import mqo
\r
52 print('use meshio C module')
\r
55 from pymeshio import mqo
\r
63 def createMqoMaterial(m):
\r
64 material = bpy.data.materials.new(m.getName())
\r
67 material.diffuse_shader='FRESNEL'
\r
69 material.diffuse_shader='LAMBERT'
\r
71 material.diffuse_color=[m.color.r, m.color.g, m.color.b]
\r
72 material.diffuse_intensity=m.diffuse
\r
73 material.alpha=m.color.a
\r
75 material.ambient = m.ambient
\r
76 #material.specular = m.specular
\r
77 material.emit=m.emit
\r
78 material.use_shadeless=True
\r
82 def has_mikoto(mqo):
\r
83 #for o in mqo.objects:
\r
84 # if o.getName().startswith('bone'):
\r
86 # if o.getName().startswith('sdef'):
\r
88 # if o.getName().startswith('anchor'):
\r
93 def __createMaterials(mqo, directory):
\r
95 create blender materials and renturn material list.
\r
100 if len(mqo.materials)>0:
\r
101 for material_index, m in enumerate(mqo.materials):
\r
103 material=createMqoMaterial(m)
\r
104 materials.append(material)
\r
106 texture_name=m.getTexture()
\r
107 if texture_name!='':
\r
108 if texture_name in textureMap:
\r
109 texture=textureMap[texture_name]
\r
111 # load texture image
\r
112 if os.path.isabs(texture_name):
\r
114 path = texture_name
\r
117 path = os.path.join(directory, texture_name)
\r
119 path=path.replace("\\", "/")
\r
120 if os.path.exists(path):
\r
121 print("create texture:", path)
\r
122 texture, image=bl.texture.create(path)
\r
123 textureMap[texture_name]=texture
\r
124 imageMap[material_index]=image
\r
126 print("%s not exits" % path)
\r
128 bl.material.addTexture(material, texture)
\r
132 return materials, imageMap
\r
135 def __createObjects(mqo, root, materials, imageMap, scale):
\r
137 create blender mesh objects.
\r
142 for o in mqo.objects:
\r
143 mesh, mesh_object=bl.mesh.create(o.getName())
\r
146 stack_depth=len(stack)-1
\r
147 #print(o.depth, stack_depth)
\r
148 if o.depth<stack_depth:
\r
149 for i in range(stack_depth-o.depth):
\r
151 bl.object.makeParent(stack[-1], mesh_object)
\r
152 stack.append(mesh_object)
\r
154 if o.getName().startswith('sdef'):
\r
155 objects.append(mesh_object)
\r
156 elif o.getName().startswith('anchor'):
\r
157 bl.object.setLayerMask(mesh_object, [0, 1])
\r
158 elif o.getName().startswith('bone'):
\r
159 bl.object.setLayerMask(mesh_object, [0, 1])
\r
162 vertices=[(v.x * scale, -v.z * scale, v.y * scale) for v in o.vertices]
\r
168 for i in reversed(range(f.index_count)):
\r
169 face_indices.append(f.getIndex(i))
\r
170 faces.append(face_indices)
\r
171 materialMap[f.material_index]=True
\r
172 bl.mesh.addGeometry(mesh, vertices, faces)
\r
174 # blender limits 16 materials per mesh
\r
175 for i, material_index in enumerate(materialMap.keys()):
\r
178 print("over 16 materials!")
\r
180 bl.mesh.addMaterial(mesh, materials[material_index])
\r
181 materialMap[material_index]=i
\r
184 assert(len(o.faces)==len(mesh.faces))
\r
185 bl.mesh.addUV(mesh)
\r
186 for i, (f, face) in enumerate(zip(o.faces, mesh.faces)):
\r
190 for j in reversed(range(f.index_count)):
\r
191 uv_array.append((f.getUV(j).x, 1.0-f.getUV(j).y))
\r
192 bl.mesh.setFaceUV(mesh, i, face, uv_array,
\r
193 imageMap.get(f.material_index, None))
\r
194 if f.material_index in materialMap:
\r
195 bl.face.setMaterial(face, materialMap[f.material_index])
\r
196 bl.face.setSmooth(face, True)
\r
200 bl.modifier.addMirror(mesh_object)
\r
203 bl.mesh.setSmooth(mesh, o.smoothing)
\r
206 bl.mesh.recalcNormals(mesh_object)
\r
211 ###############################################################################
\r
212 # for mqo mikoto bone.
\r
213 ###############################################################################
\r
214 class MikotoBone(object):
\r
217 'iHead', 'iTail', 'iUp',
\r
218 'vHead', 'vTail', 'vUp',
\r
219 'parent', 'isFloating',
\r
222 def __init__(self, face=None, vertices=None, materials=None):
\r
224 self.isFloating=False
\r
230 self.name=materials[face.material_index].name.encode('utf-8')
\r
232 i0=face.getIndex(0)
\r
233 i1=face.getIndex(1)
\r
234 i2=face.getIndex(2)
\r
241 sqNorm0=e01.getSqNorm()
\r
242 sqNorm1=e12.getSqNorm()
\r
243 sqNorm2=e20.getSqNorm()
\r
244 if sqNorm0>sqNorm1:
\r
245 if sqNorm1>sqNorm2:
\r
251 if sqNorm0>sqNorm2:
\r
263 if sqNorm1<sqNorm2:
\r
269 if sqNorm0<sqNorm2:
\r
279 self.vHead=vertices[self.iHead]
\r
280 self.vTail=vertices[self.iTail]
\r
281 self.vUp=vertices[self.iUp]
\r
283 if self.name.endswith('[]'):
\r
284 basename=self.name[0:-2]
\r
287 self.name="%s_L" % basename
\r
289 self.name="%s_R" % basename
\r
292 def setParent(self, parent, floating=False):
\r
294 self.isFloating=True
\r
296 parent.children.append(self)
\r
298 def printTree(self, indent=''):
\r
299 print("%s%s" % (indent, self.name))
\r
300 for child in self.children:
\r
301 child.printTree(indent+' ')
\r
304 def build_armature(armature, mikotoBone, parent=None):
\r
306 create a armature bone.
\r
308 bone = Armature.Editbone()
\r
309 bone.name = mikotoBone.name.encode('utf-8')
\r
310 armature.bones[bone.name] = bone
\r
312 bone.head = Mathutils.Vector(*mikotoBone.vHead.to_a())
\r
313 bone.tail = Mathutils.Vector(*mikotoBone.vTail.to_a())
\r
316 if mikotoBone.isFloating:
\r
319 bone.options=[Armature.CONNECTED]
\r
321 for child in mikotoBone.children:
\r
322 build_armature(armature, child, bone)
\r
325 def create_armature(mqo):
\r
330 for o in mqo.objects:
\r
331 if o.name.startswith('bone'):
\r
338 for f in boneObject.faces:
\r
339 if f.index_count!=3:
\r
340 print("invalid index_count: %d" % f.index_count)
\r
342 b=MikotoBone(f, boneObject.vertices, mqo.materials)
\r
345 ####################
\r
346 # build mikoto bone tree
\r
347 ####################
\r
348 mikotoRoot=MikotoBone()
\r
350 for b in tailMap.values():
\r
351 # each bone has unique parent or is root bone.
\r
352 if b.iHead in tailMap:
\r
353 b.setParent(tailMap[b.iHead])
\r
356 for e in boneObject.edges:
\r
357 if b.iHead==e.indices[0]:
\r
359 if e.indices[1] in tailMap:
\r
360 b.setParent(tailMap[e.indices[1]], True)
\r
363 elif b.iHead==e.indices[1]:
\r
365 if e.indices[0] in tailMap:
\r
366 b.setParent(tailMap[e.indices[0]], True)
\r
373 b.setParent(mikotoRoot, True)
\r
375 if len(mikotoRoot.children)==0:
\r
376 print("no root bone")
\r
379 if len(mikotoRoot.children)==1:
\r
381 mikotoRoot=mikotoRoot.children[0]
\r
382 mikotoRoot.parent=None
\r
384 mikotoRoot.vHead=Vector3(0, 10, 0)
\r
385 mikotoRoot.vTail=Vector3(0, 0, 0)
\r
387 ####################
\r
389 ####################
\r
390 armature = Armature.New()
\r
392 armature_object = scene.objects.new(armature)
\r
394 act = Armature.NLA.NewAction()
\r
395 act.setActive(armature_object)
\r
397 armature_object.drawMode |= Object.DrawModes.XRAY
\r
398 # armature settings
\r
399 armature.drawType = Armature.OCTAHEDRON
\r
400 armature.envelopes = False
\r
401 armature.vertexGroups = True
\r
402 armature.mirrorEdit = True
\r
403 armature.drawNames=True
\r
406 armature.makeEditable()
\r
407 build_armature(armature, mikotoRoot)
\r
410 return armature_object
\r
413 class TrianglePlane(object):
\r
415 mikoto
\e$BJ}<0%\!<%s$N%"%s%+!<%&%'%$%H7W;;MQ!#
\e(B
\r
418 __slots__=['normal',
\r
421 def __init__(self, v0, v1, v2):
\r
426 def isInsideXY(self, p):
\r
427 v0=Vector2(self.v0.x, self.v0.y)
\r
428 v1=Vector2(self.v1.x, self.v1.y)
\r
429 v2=Vector2(self.v2.x, self.v2.y)
\r
433 c0=Vector2.cross(e01, p-v0)
\r
434 c1=Vector2.cross(e12, p-v1)
\r
435 c2=Vector2.cross(e20, p-v2)
\r
436 if c0>=0 and c1>=0 and c2>=0:
\r
438 if c0<=0 and c1<=0 and c2<=0:
\r
441 def isInsideYZ(self, p):
\r
442 v0=Vector2(self.v0.y, self.v0.z)
\r
443 v1=Vector2(self.v1.y, self.v1.z)
\r
444 v2=Vector2(self.v2.y, self.v2.z)
\r
448 c0=Vector2.cross(e01, p-v0)
\r
449 c1=Vector2.cross(e12, p-v1)
\r
450 c2=Vector2.cross(e20, p-v2)
\r
451 if c0>=0 and c1>=0 and c2>=0:
\r
453 if c0<=0 and c1<=0 and c2<=0:
\r
456 def isInsideZX(self, p):
\r
457 v0=Vector2(self.v0.z, self.v0.x)
\r
458 v1=Vector2(self.v1.z, self.v1.x)
\r
459 v2=Vector2(self.v2.z, self.v2.x)
\r
463 c0=Vector2.cross(e01, p-v0)
\r
464 c1=Vector2.cross(e12, p-v1)
\r
465 c2=Vector2.cross(e20, p-v2)
\r
466 if c0>=0 and c1>=0 and c2>=0:
\r
468 if c0<=0 and c1<=0 and c2<=0:
\r
472 class MikotoAnchor(object):
\r
474 mikoto
\e$BJ}<0%9%1%k%H%s$N%"%s%+!<!#
\e(B
\r
477 "triangles", "bbox",
\r
479 def __init__(self):
\r
483 def push(self, face, vertices):
\r
484 if face.index_count==3:
\r
485 self.triangles.append(TrianglePlane(
\r
486 vertices[face.indices[0]],
\r
487 vertices[face.indices[1]],
\r
488 vertices[face.indices[2]]
\r
490 elif face.index_count==4:
\r
491 self.triangles.append(TrianglePlane(
\r
492 vertices[face.indices[0]],
\r
493 vertices[face.indices[1]],
\r
494 vertices[face.indices[2]]
\r
496 self.triangles.append(TrianglePlane(
\r
497 vertices[face.indices[2]],
\r
498 vertices[face.indices[3]],
\r
499 vertices[face.indices[0]]
\r
503 self.bbox=BoundingBox(vertices[face.indices[0]])
\r
504 for i in face.indices:
\r
505 self.bbox.expand(vertices[i])
\r
508 def calcWeight(self, v):
\r
509 if not self.bbox.isInside(v):
\r
512 if self.anyXY(v.x, v.y) and self.anyYZ(v.y, v.z) and self.anyZX(v.z, v.x):
\r
517 def anyXY(self, x, y):
\r
518 for t in self.triangles:
\r
519 if t.isInsideXY(Vector2(x, y)):
\r
523 def anyYZ(self, y, z):
\r
524 for t in self.triangles:
\r
525 if t.isInsideYZ(Vector2(y, z)):
\r
529 def anyZX(self, z, x):
\r
530 for t in self.triangles:
\r
531 if t.isInsideZX(Vector2(z, x)):
\r
536 def create_bone_weight(scene, mqo, armature_object, objects):
\r
538 create mikoto bone weight.
\r
541 # setup mikoto anchors
\r
542 for o in mqo.objects:
\r
543 if o.name.startswith("anchor"):
\r
545 name=mqo.materials[f.material_index].name
\r
546 if name.endswith('[]'):
\r
547 basename=name[0:-2]
\r
548 v=o.vertices[f.indices[0]]
\r
551 name_L=basename+'_L'
\r
552 if not name_L in anchorMap:
\r
553 anchorMap[name_L]=MikotoAnchor()
\r
554 anchorMap[name_L].push(f, o.vertices)
\r
557 name_R=basename+'_R'
\r
558 if not name_R in anchorMap:
\r
559 anchorMap[name_R]=MikotoAnchor()
\r
560 anchorMap[name_R].push(f, o.vertices)
\r
562 print("no side", v)
\r
564 if not name in anchorMap:
\r
565 anchorMap[name]=MikotoAnchor()
\r
566 anchorMap[name].push(f, o.vertices)
\r
569 # add armature modifier
\r
570 mod=o.modifiers.append(Modifier.Types.ARMATURE)
\r
571 mod[Modifier.Settings.OBJECT] = armature_object
\r
572 mod[Modifier.Settings.ENVELOPES] = False
\r
573 o.makeDisplayList()
\r
574 # create vertex group
\r
575 mesh=o.getData(mesh=True)
\r
576 for name in anchorMap.keys():
\r
577 mesh.addVertGroup(name)
\r
580 # assing vertices to vertex group
\r
582 mesh=o.getData(mesh=True)
\r
583 for i, mvert in enumerate(mesh.verts):
\r
585 for name, anchor in anchorMap.items():
\r
586 weight=anchor.calcWeight(mvert.co)
\r
588 mesh.assignVertsToGroup(
\r
589 name, [i], weight, Mesh.AssignModes.ADD)
\r
592 # debug orphan vertex
\r
593 print('orphan', mvert)
\r
597 def _execute(filepath='', scale=0.1):
\r
600 if not io.read(filepath):
\r
601 bl.message("fail to load %s" % filepath)
\r
605 materials, imageMap=__createMaterials(io, os.path.dirname(filepath))
\r
606 if len(materials)==0:
\r
607 materials.append(bl.material.create('default'))
\r
610 root=bl.object.createEmpty(os.path.basename(filepath))
\r
611 objects=__createObjects(io, root, materials, imageMap, scale)
\r
614 # create mikoto bone
\r
615 armature_object=create_armature(io)
\r
616 if armature_object:
\r
617 root.makeParent([armature_object])
\r
619 # create bone weight
\r
620 create_bone_weight(io, armature_object, objects)
\r