Advertisement
Guest User

Untitled

a guest
Feb 1st, 2012
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.48 KB | None | 0 0
  1. #!BPY
  2.  
  3. """ Registration info for Blender menus:
  4. Name: 'K2/HON (.model/.clip)...'
  5. Blender: 249
  6. Group: 'Import'
  7. Tip: 'Import a Heroes of Newerth model file'
  8. """
  9.  
  10. __author__ = "Anton Romanov"
  11. __version__ = "2010.03.24"
  12.  
  13. __bpydoc__ = """\
  14. """
  15.  
  16. # Copyright (c) 2010 Anton Romanov
  17. #
  18. # Permission is hereby granted, free of charge, to any person obtaining a
  19. # copy of this software and associated documentation files (the "Software"),
  20. # to deal in the Software without restriction, including without limitation
  21. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  22. # and/or sell copies of the Software, and to permit persons to whom the
  23. # Software is furnished to do so, subject to the following conditions:
  24. #
  25. # The above copyright notice and this permission notice shall be included in
  26. # all copies or substantial portions of the Software.
  27. #
  28. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  30. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  32. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  33. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  34. # IN THE SOFTWARE.
  35.  
  36. import Blender,bpy
  37. import os
  38. import struct, chunk
  39. from Blender.Mathutils import *
  40. # determines the verbosity of loggin.
  41. # 0 - no logging (fatal errors are still printed)
  42. # 1 - standard logging
  43. # 2 - verbose logging
  44. # 3 - debug level. really boring (stuff like vertex data and verbatim lines)
  45. IMPORT_LOG_LEVEL = 1
  46.  
  47. def log(msg):
  48. if IMPORT_LOG_LEVEL >= 1: print msg
  49.  
  50. def vlog(msg):
  51. if IMPORT_LOG_LEVEL >= 2: print msg
  52.  
  53. def dlog(msg):
  54. if IMPORT_LOG_LEVEL >= 3: print msg
  55.  
  56. def err(msg):
  57. Blender.Draw.PupMenu('Error|%s' % msg)
  58.  
  59. def roundVector(vec,dec=17):
  60. fvec=[]
  61. for v in vec:
  62. fvec.append(round(v,dec))
  63. return Vector(fvec)
  64. def roundMatrix(mat,dec=17):
  65. fmat = []
  66. for row in mat:
  67. fmat.append(roundVector(row,dec))
  68. return Matrix(*fmat)
  69.  
  70. def CreateBlenderMesh(filename):
  71. file = open(filename,'rb')
  72. if not file:
  73. log("can't open file")
  74. return
  75. sig = file.read(4)
  76. if sig != 'SMDL':
  77. err('unknown file signature')
  78. return
  79.  
  80. try:
  81. honchunk = chunk.Chunk(file,bigendian=0,align=0)
  82. except EOFError:
  83. log('error reading first chunk')
  84. return
  85. if honchunk.chunkname != 'head':
  86. log('file does not start with head chunk!')
  87. return
  88. version = read_int(honchunk)
  89. num_meshes = read_int(honchunk)
  90. num_sprites = read_int(honchunk)
  91. num_surfs = read_int(honchunk)
  92. num_bones = read_int(honchunk)
  93.  
  94. vlog("Version %d" % version)
  95. vlog("%d mesh(es)" % num_meshes)
  96. vlog("%d sprites(es)" % num_sprites)
  97. vlog("%d surfs(es)" % num_surfs)
  98. vlog("%d bones(es)" % num_bones)
  99. vlog("bounding box: (%f,%f,%f) - (%f,%f,%f)" % \
  100. struct.unpack("<ffffff", honchunk.read(24)))
  101. honchunk.skip()
  102.  
  103. scn= bpy.data.scenes.active
  104.  
  105. try:
  106. honchunk = chunk.Chunk(file,bigendian=0,align=0)
  107. except EOFError:
  108. log('error reading bone chunk')
  109. return
  110.  
  111.  
  112. #read bones
  113.  
  114. #create armature object
  115. armature_object = Blender.Object.New('Armature')
  116. armature_object.drawMode = Blender.Object.DrawModes.XRAY
  117. scn.objects.link(armature_object)
  118. armature = armature_object.getData()
  119. if armature is None:
  120. base_name = Blender.sys.basename(file_object.name)
  121. armature_name = Blender.sys.splitext(base_name)[0]
  122. armature = Blender.Armature.New(armature_name)
  123. armature_object.link(armature)
  124. armature.drawType = Blender.Armature.STICK
  125. armature.envelopes = False
  126. armature.vertexGroups = True
  127.  
  128. armature.makeEditable()
  129. bones = []
  130. bone_names = []
  131. parents = []
  132. for i in xrange(num_bones):
  133. name = ''
  134. parent_bone_index = read_int(honchunk)
  135.  
  136. if version == 3:
  137. inv_matrix = Matrix(struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  138. struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  139. struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  140. struct.unpack('<3f', honchunk.read(12)) + (1.0,))
  141. matrix = Matrix(struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  142. struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  143. struct.unpack('<3f', honchunk.read(12)) + (0.0,), \
  144. struct.unpack('<3f', honchunk.read(12)) + (1.0,))
  145. name_length = struct.unpack("B" , honchunk.read(1))[0]
  146. name = honchunk.read(name_length)
  147.  
  148. honchunk.read(1) #zero
  149. elif version == 1:
  150. name = ''
  151. pos = honchunk.tell() - 4
  152. b = honchunk.read(1)
  153. while b != '\0':
  154. name += b
  155. b = honchunk.read(1)
  156. honchunk.seek(pos + 0x24)
  157. inv_matrix = Matrix( struct.unpack('<4f', honchunk.read(16)), \
  158. struct.unpack('<4f', honchunk.read(16)), \
  159. struct.unpack('<4f', honchunk.read(16)), \
  160. struct.unpack('<4f', honchunk.read(16)))
  161.  
  162. matrix = Matrix(struct.unpack('<4f', honchunk.read(16)), \
  163. struct.unpack('<4f', honchunk.read(16)), \
  164. struct.unpack('<4f', honchunk.read(16)), \
  165. struct.unpack('<4f', honchunk.read(16)))
  166. dlog("bone name: %s,parent %d" % (name,parent_bone_index))
  167. bone_names.append(name)
  168. edit_bone = Blender.Armature.Editbone()
  169. edit_bone.name = name
  170. edit_bone.matrix = roundMatrix(matrix,4)
  171. parents.append(parent_bone_index)
  172. bones.append(edit_bone)
  173. armature.bones[name] = edit_bone
  174. for i in xrange(num_bones):
  175. if parents[i] != -1:
  176. bones[i].parent = bones[parents[i]]
  177. armature.update()
  178. honchunk.skip()
  179.  
  180.  
  181. try:
  182. honchunk = chunk.Chunk(file,bigendian=0,align=0)
  183. except EOFError:
  184. log('error reading mesh chunk')
  185. return
  186. while honchunk.chunkname == 'mesh':
  187. verts = []
  188. faces = []
  189. signs = []
  190. nrml = []
  191. texc = []
  192. colors = []
  193. #read mesh chunk
  194. vlog("mesh index: %d" % read_int(honchunk))
  195. mode = 1
  196. if version == 3:
  197. mode = read_int(honchunk)
  198. vlog("mode: %d" % mode)
  199. vlog("vertices count: %d" % read_int(honchunk))
  200. vlog("bounding box: (%f,%f,%f) - (%f,%f,%f)" % \
  201. struct.unpack("<ffffff", honchunk.read(24)))
  202. bone_link = read_int(honchunk)
  203. vlog("bone link: %d" % bone_link)
  204. sizename = struct.unpack('B',honchunk.read(1))[0]
  205. sizemat = struct.unpack('B',honchunk.read(1))[0]
  206. meshname = honchunk.read(sizename)
  207. honchunk.read(1) # zero
  208. materialname = honchunk.read(sizemat)
  209. elif version == 1:
  210. bone_link = -1
  211. pos = honchunk.tell() - 4
  212. b = honchunk.read(1)
  213. meshname = ''
  214. while b != '\0':
  215. meshname += b
  216. b = honchunk.read(1)
  217. honchunk.seek(pos + 0x24)
  218.  
  219. b = honchunk.read(1)
  220. materialname = ''
  221. while b != '\0':
  222. materialname += b
  223. b = honchunk.read(1)
  224.  
  225. honchunk.skip()
  226. if mode == 1 or not SKIP_NON_PHYSIQUE_MESHES:
  227. msh = bpy.data.meshes.new(meshname)
  228. #msh.mode |= Blender.Mesh.Modes.AUTOSMOOTH
  229. obj = scn.objects.new(msh)
  230.  
  231. while 1:
  232. try:
  233. honchunk = chunk.Chunk(file,bigendian=0,align=0)
  234. except EOFError:
  235. vlog('error reading chunk')
  236. break
  237. if honchunk.chunkname == 'mesh':
  238. break
  239. elif mode != 1 and SKIP_NON_PHYSIQUE_MESHES:
  240. honchunk.skip()
  241. else:
  242. if honchunk.chunkname == 'vrts':
  243. verts = parse_vertices(honchunk)
  244. msh.verts.extend(verts)
  245. elif honchunk.chunkname == 'face':
  246. faces = parse_faces(honchunk,version)
  247. elif honchunk.chunkname == 'nrml':
  248. nrml = parse_normals(honchunk)
  249. elif honchunk.chunkname == 'texc':
  250. texc = parse_texc(honchunk,version)
  251. elif honchunk.chunkname == 'colr':
  252. colors = parse_colr(honchunk)
  253. elif honchunk.chunkname == 'lnk1' or honchunk.chunkname == 'lnk3':
  254. armature_object.makeParentDeform([obj])
  255. parse_links(honchunk,msh,bone_names)
  256. elif honchunk.chunkname == 'sign':
  257. signs = parse_sign(honchunk)
  258. else:
  259. vlog('unknown chunk: %s' % honchunk.chunkname)
  260. honchunk.skip()
  261. if mode != 1 and SKIP_NON_PHYSIQUE_MESHES:
  262. continue
  263. try:
  264. msh.materials += [bpy.data.materials[materialname]]
  265. except:
  266. msh.materials += [bpy.data.materials.new(materialname)]
  267.  
  268. if bone_link >=0 :
  269. armature_object.makeParentDeform([obj])
  270. msh.addVertGroup(bone_names[bone_link])
  271. msh.assignVertsToGroup(bone_names[bone_link],list(xrange(len(msh.verts))),1.0,Blender.Mesh.AssignModes.ADD)
  272.  
  273. #vertices
  274. for i in xrange(len(nrml)):
  275. msh.verts[i].no = Vector(nrml[i])
  276.  
  277.  
  278. #remove doubles if needed
  279. if remove_doubles:
  280. doubles = []
  281. for vi,v in enumerate(verts):
  282. if vi in doubles:
  283. continue
  284. new_doubles = []
  285. for di,d in enumerate(verts[vi + 1:]):
  286. di += vi+1
  287. new_doubles = []
  288. if v == d and nrml[vi] == nrml[di]:
  289. new_doubles.append(di)
  290. if len(new_doubles) > 0:
  291. doubles.append(vi)
  292. doubles.extend(new_doubles)
  293. vlog('found %d duplicate vertices' % len(doubles))
  294.  
  295.  
  296. #faces
  297. if len(faces) > 0:
  298. for i in xrange(len(faces)):
  299. f = Blender.NMesh.Face()
  300. f.v.extend([vi for vi in faces[i]])
  301. f.materialIndex = 0
  302. msh.faces.extend(f)
  303. #UV texture coordinates
  304. if len(texc) > 0:
  305. msh.faceUV = True
  306. for fc in msh.faces:
  307. fc.mode |= Blender.NMesh.FaceModes['TEX']
  308. fc.mode |= Blender.NMesh.FaceModes['LIGHT']
  309. for ii, v in enumerate(fc):
  310. fc.uv[ii][0] = texc[v.index][0]
  311. if flip_uv:
  312. fc.uv[ii][1] = 1.0-texc[v.index][1]
  313. else:
  314. fc.uv[ii][1] = texc[v.index][1]
  315. #vertex colours
  316. if len(colors) > 0:
  317. msh.vertexColors = True
  318. for fc in msh.faces:
  319. for ii, v in enumerate(fc):
  320. for x in xrange(4):
  321. fc.col[ii][x] = colors[v.index][x]
  322.  
  323. if remove_doubles:
  324. for v in msh.verts:
  325. if v.index in doubles:
  326. v.sel = 1
  327. else:
  328. v.sel = 0
  329. removed = msh.remDoubles(0)
  330. vlog('removed %d duplicate vertices' % removed)
  331.  
  332. vlog('removing duplicate faces (making two-sided)')
  333. fdoubles = []
  334. for f in msh.faces:
  335. if f.index in fdoubles:
  336. continue
  337. newdoubles = []
  338. for f2 in [f2 for f2 in msh.faces if f2.index > f.index and f2.index not in fdoubles]:
  339. v1 = [v.co for v in f.verts]
  340. v2 = [v.co for v in f2.verts]
  341. v1.sort()
  342. v2.sort()
  343. n1 = [v.no for v in f.verts]
  344. n2 = [-v.no for v in f2.verts]
  345. n1.sort()
  346. n2.sort()
  347. double = True
  348. for i in xrange(len(v1)):
  349. if v1[i] != v2[i] or n1[i] != n2[i]:
  350. double = False
  351. if double:
  352. newdoubles.append(f2.index)
  353. if len(newdoubles) > 0:
  354. f.mode |= Blender.NMesh.FaceModes['TWOSIDE']
  355. fdoubles.extend(newdoubles)
  356. msh.faces.delete(1,fdoubles)
  357. vlog('removed %d duplicate faces' % len(fdoubles))
  358. vlog('removing orphaned vertices')
  359. for v in msh.verts:
  360. v.sel = 1
  361. for f in msh.faces:
  362. for v in f.verts:
  363. v.sel = 0
  364. selected = msh.verts.selected()
  365. vlog('removing %d orphaned vertices' % (len(selected)) )
  366. msh.verts.delete(selected)
  367. obj.select(False)
  368. #end reading submesh
  369. armature_object.select(True)
  370.  
  371. def read_int(honchunk):
  372. return struct.unpack("<i",honchunk.read(4))[0]
  373. def read_float(honchunk):
  374. return struct.unpack("<f",honchunk.read(4))[0]
  375.  
  376. def parse_links(honchunk,mesh,bone_names):
  377. mesh_index = read_int(honchunk)
  378. numverts = read_int(honchunk)
  379. dlog("links")
  380. dlog("mesh index: %d" % mesh_index)
  381. dlog("vertices number: %d" % numverts)
  382. for i in xrange(numverts):
  383. num_weights = read_int(honchunk)
  384. weights = struct.unpack("<%df" % num_weights,honchunk.read(num_weights * 4))
  385. indexes = struct.unpack("<%dI" % num_weights,honchunk.read(num_weights * 4))
  386. for ii, index in enumerate(indexes):
  387. name = bone_names[index]
  388. if name not in mesh.getVertGroupNames():
  389. mesh.addVertGroup(name)
  390. mesh.assignVertsToGroup(name,[i],weights[ii],Blender.Mesh.AssignModes.ADD)
  391. honchunk.skip()
  392.  
  393. def parse_vertices(honchunk):
  394. vlog('parsing vertices chunk')
  395. numverts = (honchunk.chunksize - 4)/12
  396. vlog('%d vertices' % numverts)
  397. meshindex = read_int(honchunk)
  398. return [struct.unpack("<3f", honchunk.read(12)) for i in xrange(numverts)]
  399. def parse_sign(honchunk):
  400. vlog('parsing sign chunk')
  401. numverts = (honchunk.chunksize - 8)
  402. meshindex = read_int(honchunk)
  403. vlog(read_int(honchunk)) # huh?
  404. return [struct.unpack("<b", honchunk.read(1)) for i in xrange(numverts)]
  405. def parse_faces(honchunk,version):
  406. vlog('parsing faces chunk')
  407. meshindex = read_int(honchunk)
  408. numfaces = read_int(honchunk)
  409. vlog('%d faces' % numfaces)
  410. if version == 3:
  411. size = struct.unpack('B',honchunk.read(1))[0]
  412. elif version == 1:
  413. size = 4
  414. if size == 2:
  415. return [struct.unpack("<3H", honchunk.read(6)) for i in xrange(numfaces)]
  416. elif size ==1:
  417. return [struct.unpack("<3B", honchunk.read(3)) for i in xrange(numfaces)]
  418. elif size == 4:
  419. return [struct.unpack("<3I", honchunk.read(12)) for i in xrange(numfaces)]
  420. else:
  421. log("unknown size for faces:%d" % size)
  422. return []
  423. def parse_normals(honchunk):
  424. vlog('parsing normals chunk')
  425. numverts = (honchunk.chunksize - 4)/12
  426. vlog('%d normals' % numverts)
  427. meshindex = read_int(honchunk)
  428. return [struct.unpack("<3f", honchunk.read(12)) for i in xrange(numverts)]
  429. def parse_texc(honchunk,version):
  430. vlog('parsing uv texc chunk')
  431. numverts = (honchunk.chunksize - 4)/8
  432. vlog('%d texc' % numverts)
  433. meshindex = read_int(honchunk)
  434. if version == 3:
  435. vlog(read_int(honchunk)) # huh?
  436. return [struct.unpack("<2f", honchunk.read(8)) for i in xrange(numverts)]
  437. def parse_colr(honchunk):
  438. vlog('parsing vertex colours chunk')
  439. numverts = (honchunk.chunksize - 4)/4
  440. meshindex = read_int(honchunk)
  441. return [struct.unpack("<4B", honchunk.read(4)) for i in xrange(numverts)]
  442.  
  443. ##############################
  444. #CLIPS
  445. ##############################
  446.  
  447. MKEY_X,MKEY_Y,MKEY_Z,\
  448. MKEY_PITCH,MKEY_ROLL,MKEY_YAW,\
  449. MKEY_VISIBILITY,\
  450. MKEY_SCALE_X,MKEY_SCALE_Y,MKEY_SCALE_Z \
  451. = range(10)
  452.  
  453.  
  454. def bone_depth(bone):
  455. if not bone.parent:
  456. return 0
  457. else:
  458. return 1+bone_depth(bone.parent)
  459.  
  460. def getTransformMatrix(motions,bone,i,version):
  461. motion = motions[bone.name]
  462. #translation
  463. if i >= len(motion[MKEY_X]):
  464. x = motion[MKEY_X][-1]
  465. else:
  466. x = motion[MKEY_X][i]
  467.  
  468. if i >= len(motion[MKEY_Y]):
  469. y = motion[MKEY_Y][-1]
  470. else:
  471. y = motion[MKEY_Y][i]
  472.  
  473. if i >= len(motion[MKEY_Z]):
  474. z = motion[MKEY_Z][-1]
  475. else:
  476. z = motion[MKEY_Z][i]
  477.  
  478. #rotation
  479. if i >= len(motion[MKEY_PITCH]):
  480. rx = motion[MKEY_PITCH][-1]
  481. else:
  482. rx = motion[MKEY_PITCH][i]
  483.  
  484. if i >= len(motion[MKEY_ROLL]):
  485. ry = motion[MKEY_ROLL][-1]
  486. else:
  487. ry = motion[MKEY_ROLL][i]
  488.  
  489. if i >= len(motion[MKEY_YAW]):
  490. rz = motion[MKEY_YAW][-1]
  491. else:
  492. rz = motion[MKEY_YAW][i]
  493.  
  494. #scaling
  495. if version == 1:
  496. if i >= len(motion[MKEY_SCALE_X]):
  497. sx = motion[MKEY_SCALE_X][-1]
  498. else:
  499. sx = motion[MKEY_SCALE_X][i]
  500. sy = sz = sx
  501. else:
  502. if i >= len(motion[MKEY_SCALE_X]):
  503. sx = motion[MKEY_SCALE_X][-1]
  504. else:
  505. sx = motion[MKEY_SCALE_X][i]
  506.  
  507. if i >= len(motion[MKEY_SCALE_Y]):
  508. sy = motion[MKEY_SCALE_Y][-1]
  509. else:
  510. sy = motion[MKEY_SCALE_Y][i]
  511.  
  512. if i >= len(motion[MKEY_SCALE_Z]):
  513. sz = motion[MKEY_SCALE_Z][-1]
  514. else:
  515. sz = motion[MKEY_SCALE_Z][i]
  516. size = Blender.Mathutils.Vector([sx,sy,sz])
  517.  
  518. #commented till i can specify rotation order
  519. #euler = Blender.Mathutils.Euler(rx,ry,rz)
  520. euler = Blender.Mathutils.Euler()
  521. RotateEuler(euler,rz,'z')
  522. RotateEuler(euler,rx,'x')
  523. RotateEuler(euler,ry,'y')
  524.  
  525.  
  526.  
  527. bone_rotation_matrix = euler.toMatrix()
  528. bone_rotation_matrix.resize4x4()
  529. bone_rotation_matrix *= Blender.Mathutils.TranslationMatrix(\
  530. Blender.Mathutils.Vector(x,y,z))
  531.  
  532. return bone_rotation_matrix,size
  533.  
  534. def AnimateBone(name,pose,motions,num_frames,armature,armOb,version):
  535. if name not in armature.bones.keys():
  536. log ('%s not found in armature' % name)
  537. return
  538. motion = motions[name]
  539. bone = armature.bones[name]
  540. bone_rest_matrix = bone.matrix['ARMATURESPACE'].copy()
  541.  
  542. if bone.parent is not None:
  543. parent_bone = bone.parent
  544. parent_rest_bone_matrix = parent_bone.matrix['ARMATURESPACE'].copy()
  545. parent_rest_bone_matrix.invert()
  546. bone_rest_matrix *= parent_rest_bone_matrix
  547.  
  548. bone_rest_matrix_inv = Blender.Mathutils.Matrix(bone_rest_matrix)
  549. bone_rest_matrix_inv.invert()
  550. pbone = pose.bones[name]
  551. for i in range(0, num_frames):
  552. transform,size = getTransformMatrix(motions,bone,i,version)
  553. pbone.localMatrix = transform * bone_rest_matrix_inv
  554. pbone.size = size
  555. pbone.insertKey(armOb, i + 1,[Blender.Object.Pose.ROT,Blender.Object.Pose.LOC,Blender.Object.Pose.SIZE],True)
  556.  
  557. def CreateBlenderClip(filename):
  558. basename = Blender.sys.basename(filename)
  559. clipname = basename[0:basename.lower().find('.clip')]
  560. file = open(filename,'rb')
  561. if not file:
  562. log("can't open file")
  563. return
  564. sig = file.read(4)
  565. if sig != 'CLIP':
  566. err('unknown file signature')
  567. return
  568.  
  569. try:
  570. clipchunk = chunk.Chunk(file,bigendian=0,align=0)
  571. except EOFError:
  572. log('error reading first chunk')
  573. return
  574. version = read_int(clipchunk)
  575. num_bones = read_int(clipchunk)
  576. num_frames = read_int(clipchunk)
  577. vlog ("version: %d" % version)
  578. vlog ("num bones: %d" % num_bones)
  579. vlog ("num frames: %d" % num_frames)
  580.  
  581.  
  582. objList = Blender.Object.GetSelected()
  583. if len(objList) != 1:
  584. err('select needed armature only')
  585. armOb = objList[0]
  586. action = Blender.Armature.NLA.NewAction(clipname)
  587. action.setActive(armOb)
  588. pose = armOb.getPose()
  589. armature = armOb.getData()
  590. bone_index = -1
  591. motions = {}
  592.  
  593.  
  594. while 1:
  595. try:
  596. clipchunk = chunk.Chunk(file,bigendian=0,align=0)
  597. except EOFError:
  598. vlog('error reading chunk')
  599. break
  600. if version == 1:
  601. name = clipchunk.read(32)
  602. if '\0' in name:
  603. name = name[:name.index('\0')]
  604. boneindex = read_int(clipchunk)
  605. keytype = read_int(clipchunk)
  606. numkeys = read_int(clipchunk)
  607. if version > 1:
  608. namelength = struct.unpack("B",clipchunk.read(1))[0]
  609. name = clipchunk.read(namelength)
  610. clipchunk.read(1)
  611.  
  612. if name not in motions:
  613. motions[name] = {}
  614. dlog ("%s,boneindex: %d,keytype: %d,numkeys: %d" % \
  615. (name,boneindex,keytype,numkeys))
  616. if keytype == MKEY_VISIBILITY:
  617. data = struct.unpack("%dB" % numkeys,clipchunk.read(numkeys))
  618. else:
  619. data = struct.unpack("<%df" % numkeys,clipchunk.read(numkeys * 4))
  620. motions[name][keytype] = list(data)
  621. clipchunk.skip()
  622. #file read, now animate that bastard!
  623. for bone_name in motions:
  624. AnimateBone(bone_name,pose,motions,num_frames,armature,armOb,version)
  625. pose.update()
  626.  
  627.  
  628. ############
  629. #common
  630. ###############################
  631. #-------------------------------\
  632. # common |
  633. #-------------------------------/
  634. ######################################################
  635. # GUI STUFF
  636. ######################################################
  637.  
  638. draw_busy_screen = 0
  639. EVENT_NOEVENT = 1
  640. EVENT_IMPORT = 2
  641. EVENT_QUIT = 3
  642. EVENT_MESHFILENAME = 4
  643. EVENT_ANIMFILENAME = 5
  644. EVENT_MESHFILENAME_STRINGBUTTON = 6
  645. EVENT_ANIMFILENAME_STRINGBUTTON = 7
  646. SKIP_NON_PHYSIQUE_MESHES = False
  647. mesh_filename = Blender.Draw.Create("")
  648. anim_filename = Blender.Draw.Create("")
  649. import_all_clips = True
  650. IMPORT_ALL_CLIPS = Blender.Draw.Create(0)
  651. SKIP_NON_PHYSIQUE_MESHES_BUTTON = Blender.Draw.Create(0)
  652. REMOVE_DOUBLES = Blender.Draw.Create(1)
  653. FLIP_UV = Blender.Draw.Create(1)
  654. flip_uv = True
  655. remove_doubles = True
  656. ######################################################
  657. # Callbacks for Window functions
  658. ######################################################
  659. def meshname_callback(filename):
  660. global mesh_filename
  661. mesh_filename.val=filename
  662.  
  663. def animname_callback(filename):
  664. global anim_filename
  665. anim_filename.val=filename
  666.  
  667. ######################################################
  668. # GUI Functions
  669. ######################################################
  670. def handle_event(evt, val):
  671. if evt == Blender.Draw.ESCKEY:
  672. Blender.Draw.Exit()
  673. return
  674.  
  675. def handle_button_event(evt):
  676. global EVENT_NOEVENT, EVENT_IMPORT, EVENT_QUIT, EVENT_MESHFILENAME, EVENT_ANIMFILENAME, EVENT_MESHFILENAME_STRINGBUTTON, EVENT_ANIMFILENAME_STRINGBUTTON,SKIP_NON_PHYSIQUE_MESHES_BUTTON
  677. global draw_busy_screen, mesh_filename, anim_filename, import_all_clips,IMPORT_ALL_CLIPS,REMOVE_DOUBLES,FLIP_UV,flip_uv,remove_doubles,SKIP_NON_PHYSIQUE_MESHES
  678. if evt == EVENT_IMPORT:
  679. import_all_clips = IMPORT_ALL_CLIPS.val
  680. remove_doubles = REMOVE_DOUBLES.val
  681. SKIP_NON_PHYSIQUE_MESHES = SKIP_NON_PHYSIQUE_MESHES_BUTTON.val
  682. flip_uv = FLIP_UV.val
  683. Blender.Window.WaitCursor(1)
  684. draw_busy_screen = 1
  685. Blender.Draw.Draw()
  686. if len(mesh_filename.val)>0:
  687. CreateBlenderMesh(mesh_filename.val)
  688. if len(anim_filename.val)>0:
  689. if not import_all_clips:
  690. CreateBlenderClip(anim_filename.val)
  691. else:
  692. dirname = Blender.sys.dirname(anim_filename.val)
  693. for fname in os.listdir(dirname):
  694. if fname.endswith('.clip'):
  695. CreateBlenderClip(Blender.sys.join(dirname,fname))
  696. draw_busy_screen = 0
  697. Blender.Draw.Redraw(1)
  698. Blender.Window.WaitCursor(0)
  699. return
  700. if evt == EVENT_QUIT:
  701. Blender.Draw.Exit()
  702. if evt == EVENT_MESHFILENAME:
  703. Blender.Window.FileSelector(meshname_callback, "Select mesh file...")
  704. Blender.Draw.Redraw(1)
  705. if evt == EVENT_ANIMFILENAME:
  706. Blender.Window.FileSelector(animname_callback, "Select anim file...")
  707. Blender.Draw.Redraw(1)
  708.  
  709. def show_gui():
  710. global EVENT_NOEVENT, EVENT_IMPORT, EVENT_QUIT, EVENT_MESHFILENAME, EVENT_ANIMFILENAME, EVENT_MESHFILENAME_STRINGBUTTON, EVENT_ANIMFILENAME_STRINGBUTTON,SKIP_NON_PHYSIQUE_MESHES_BUTTON
  711. global draw_busy_screen, mesh_filename, anim_filename, IMPORT_ALL_CLIPS,REMOVE_DOUBLES,FLIP_UV
  712. global startframe_slider, endframe_slider
  713. button_width = 240
  714. browsebutton_width = 60
  715. button_height = 25
  716. if draw_busy_screen == 1:
  717. Blender.BGL.glClearColor(0.3,0.3,0.3,1.0)
  718. Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
  719. Blender.BGL.glColor3f(1,1,1)
  720. Blender.BGL.glRasterPos2i(20,25)
  721. Blender.Draw.Text("Please wait...")
  722. return
  723. Blender.BGL.glClearColor(0.6,0.6,0.6,1.0)
  724. Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
  725. Blender.Draw.Button("Import!", EVENT_IMPORT, 20, 2*button_height, button_width, button_height, "Start the import")
  726. Blender.Draw.Button("Quit", EVENT_QUIT, 20, button_height, button_width, button_height, "Quit this script")
  727. Blender.Draw.Button("Browse...", EVENT_MESHFILENAME, 21+button_width-browsebutton_width, 4*button_height, browsebutton_width, button_height, "Specify mesh-file")
  728. Blender.Draw.Button("Browse...", EVENT_ANIMFILENAME, 21+button_width-browsebutton_width, 3*button_height, browsebutton_width, button_height, "Specify anim-file")
  729. mesh_filename = Blender.Draw.String("Mesh file:", EVENT_MESHFILENAME_STRINGBUTTON, 20, 4*button_height, button_width-browsebutton_width, button_height, mesh_filename.val, 255, "Mesh-File to import")
  730. anim_filename = Blender.Draw.String("Anim dir/file:", EVENT_ANIMFILENAME_STRINGBUTTON, 20, 3*button_height, button_width-browsebutton_width, button_height, anim_filename.val, 255, "Anim-File to import")
  731. SKIP_NON_PHYSIQUE_MESHES_BUTTON = Blender.Draw.Toggle('Skip non physique meshes', EVENT_NOEVENT, 20, 6*button_height, button_width, button_height, SKIP_NON_PHYSIQUE_MESHES_BUTTON.val, 'Skip non-deforming objects')
  732. IMPORT_ALL_CLIPS = Blender.Draw.Toggle('All clips', EVENT_NOEVENT, 20, 7*button_height, button_width, button_height, IMPORT_ALL_CLIPS.val, 'Import all clips available in the same directory.')
  733. REMOVE_DOUBLES = Blender.Draw.Toggle('Remove doubles', EVENT_NOEVENT, 20, 8*button_height, button_width, button_height, REMOVE_DOUBLES.val, 'Merge duplicated vertices')
  734. FLIP_UV = Blender.Draw.Toggle('V-Flip UV', EVENT_NOEVENT, 20, 9*button_height, button_width, button_height, FLIP_UV.val, 'Flip UV mapping vertically')
  735. Blender.Draw.Register (show_gui, handle_event, handle_button_event)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement