Advertisement
Guest User

Untitled

a guest
Feb 1st, 2012
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.28 KB | None | 0 0
  1. #!BPY
  2.  
  3. """ Registration info for Blender menus:
  4. Name: 'K2/HON (.model/.clip)...'
  5. Blender: 249
  6. Group: 'Export'
  7. Tip: 'Export 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.  
  37.  
  38. import Blender,bpy
  39. import struct, chunk
  40. import cStringIO
  41. from Blender.Mathutils import *
  42. from Blender import Mesh, Scene, Window, sys, Image, Draw
  43. import BPyMesh
  44. import BPyObject
  45. # determines the verbosity of loggin.
  46. # 0 - no logging (fatal errors are still printed)
  47. # 1 - standard logging
  48. # 2 - verbose logging
  49. # 3 - debug level. really boring (stuff like vertex data and verbatim lines)
  50. IMPORT_LOG_LEVEL = 3
  51.  
  52. def log(msg):
  53. if IMPORT_LOG_LEVEL >= 1: print msg
  54.  
  55. def vlog(msg):
  56. if IMPORT_LOG_LEVEL >= 2: print msg
  57.  
  58. def dlog(msg):
  59. if IMPORT_LOG_LEVEL >= 3: print msg
  60.  
  61. def err(msg):
  62. Blender.Draw.PupMenu('Error|%s' % msg)
  63.  
  64. def bone_depth(bone):
  65. if not bone.parent:
  66. return 0
  67. else:
  68. return 1+bone_depth(bone.parent)
  69. def create_bone_data(armature,armob):
  70. bones = []
  71. for bone in sorted(armature.bones.values(),cmp=lambda x, y: bone_depth(x) - bone_depth(y)):
  72. bones.append(bone.name)
  73. bonedata = cStringIO.StringIO()
  74.  
  75. for name in bones:
  76. bone = armature.bones[name]
  77. base = bone.matrix['ARMATURESPACE'].copy()
  78. if transform:
  79. base *= armob.mat
  80. baseInv = base.copy().invert()
  81. if bone.parent :
  82. parent_index = bones.index(bone.parent.name)
  83. else:
  84. parent_index = -1
  85. #parent bone index
  86. bonedata.write(struct.pack("<i",parent_index))
  87. #inverted matrix
  88. bonedata.write(struct.pack('<12f', *sum([row[0:3] for row in baseInv],[])))
  89. #base matrix
  90. bonedata.write(struct.pack('<12f', *sum([row[0:3] for row in base],[])))
  91. #bone name
  92. bonedata.write(struct.pack("B" ,len(name)))
  93. bonedata.write(name)
  94. bonedata.write(struct.pack("B" ,0))
  95. return bones,bonedata.getvalue()
  96. def generate_bbox(meshes):
  97. # need to transform verts here?
  98. xx = []
  99. yy = []
  100. zz = []
  101. for mesh in meshes:
  102. nv = [v.co for v in mesh.verts]
  103. xx += [ co[0] for co in nv ]
  104. yy += [ co[1] for co in nv ]
  105. zz += [ co[2] for co in nv ]
  106. return [min(xx),min(yy),min(zz),max(xx),max(yy),max(zz)]
  107.  
  108. def create_mesh_data(mesh,vert,index):
  109. meshdata = cStringIO.StringIO()
  110. meshdata.write(struct.pack("<i",index))
  111. meshdata.write(struct.pack("<i",1)) # mode? huh? dunno...
  112. meshdata.write(struct.pack("<i",len(vert))) # vertices count
  113. meshdata.write(struct.pack("<6f",*generate_bbox([mesh]))) # bounding box
  114. meshdata.write(struct.pack("<i",-1)) # bone link... dunno... TODO
  115. meshdata.write(struct.pack("<B",len(mesh.name)))
  116. meshdata.write(struct.pack("<B",len(mesh.materials[0].name)))
  117. meshdata.write(mesh.name)
  118. meshdata.write(struct.pack("<B",0))
  119. meshdata.write(mesh.materials[0].name)
  120. meshdata.write(struct.pack("<B",0))
  121. return meshdata.getvalue()
  122.  
  123. def create_vrts_data(verts,meshindex):
  124. data = cStringIO.StringIO()
  125. data.write(struct.pack("<i",meshindex))
  126. for v in verts:
  127. data.write(struct.pack("<3f",*v.co))
  128. return data.getvalue()
  129.  
  130. def create_face_data(verts,faces,meshindex):
  131. data = cStringIO.StringIO()
  132. data.write(struct.pack("<i",meshindex))
  133. data.write(struct.pack("<i",len(faces)))
  134.  
  135. if len(verts) < 255 :
  136. data.write(struct.pack("<B",1))
  137. str = '<3B'
  138. else:
  139. data.write(struct.pack("<B",2))
  140. str = '<3H'
  141. for f in faces:
  142. data.write(struct.pack(str,*f))
  143. return data.getvalue()
  144.  
  145. def create_tang_data(tang,meshindex):
  146. data = cStringIO.StringIO()
  147. data.write(struct.pack("<i",meshindex))
  148. data.write(struct.pack("<i",0)) # huh?
  149. for t in tang:
  150. data.write(struct.pack('<3f',*list(t)))
  151. return data.getvalue()
  152.  
  153. def write_block(file,name,data):
  154. file.write(name)
  155. file.write(struct.pack("<i",len(data)))
  156. file.write(data)
  157.  
  158. def create_texc_data(texc,meshindex):
  159. if flip_uv:
  160. for i in xrange(len(texc)):
  161. texc[i] = [texc[i][0],1.0-texc[i][1]]
  162. data = cStringIO.StringIO()
  163. data.write(struct.pack("<i",meshindex))
  164. data.write(struct.pack("<i",0)) # huh?
  165. for t in texc:
  166. data.write(struct.pack("<2f",*t))
  167. return data.getvalue()
  168.  
  169. def create_colr_data(colr,meshindex):
  170. data = cStringIO.StringIO()
  171. data.write(struct.pack("<i",meshindex))
  172. for c in colr:
  173. data.write(struct.pack("<4B",c.r,c.g,c.b,c.a))
  174. return data.getvalue()
  175.  
  176. def create_nrml_data(verts,meshindex):
  177. data = cStringIO.StringIO()
  178. data.write(struct.pack("<i",meshindex))
  179. for v in verts:
  180. data.write(struct.pack("<3f",*v.no))
  181. return data.getvalue()
  182.  
  183. def create_lnk1_data(lnk1,meshindex,bone_indices):
  184. data = cStringIO.StringIO()
  185. data.write(struct.pack("<i",meshindex))
  186. data.write(struct.pack("<i",len(lnk1)))
  187. for influences in lnk1:
  188. influences = [inf for inf in influences if inf[0] in bone_indices]
  189. l = len(influences)
  190. data.write(struct.pack("<i",l))
  191. if l > 0:
  192. data.write(struct.pack('<%df' % l,\
  193. *[inf[1] for inf in influences]))
  194. data.write(struct.pack('<%dI' % l,\
  195. *[bone_indices.index(inf[0]) for inf in influences]))
  196. return data.getvalue()
  197.  
  198. def create_sign_data(meshindex,sign):
  199. data = cStringIO.StringIO()
  200. data.write(struct.pack("<i",meshindex))
  201. data.write(struct.pack("<i",0))
  202. for s in sign:
  203. data.write(struct.pack("<b",s))
  204. return data.getvalue()
  205.  
  206. def calcFaceSigns(ftexc):
  207. fsigns = []
  208. for uv in ftexc:
  209. if ((uv[1][0] - uv[0][0]) * (uv[2][1] - uv[1][1]) - (uv[1][1] - uv[0][1]) * (uv[2][0] - uv[1][0])) > 0:
  210. fsigns.append((0,0,0))
  211. else:
  212. fsigns.append((-1,-1,-1))
  213. return fsigns
  214.  
  215. def face_to_vertices_dup(faces,fdata,verts):
  216. vdata = [None]*len(verts)
  217. for fi,f in enumerate(faces):
  218. for vi,v in enumerate(f):
  219. if vdata[v] is None or vdata[v] == fdata[fi][vi]:
  220. vdata[v] = fdata[fi][vi]
  221. else:
  222. newind = len(verts)
  223. verts.append(verts[v])
  224. faces[fi][vi] = newind
  225. vdata.append(fdata[fi][vi])
  226. return vdata
  227. def face_to_vertices(faces,fdata,verts):
  228. vdata = [None]*len(verts)
  229. for fi,f in enumerate(faces):
  230. for vi,v in enumerate(f):
  231. vdata[v] = fdata[fi][vi]
  232. return vdata
  233. def duplicate_twosided_faces(mesh,faces,vert,ftexc,flnk1,ftang,fcolr):
  234. for fi in [f.index for f in mesh.faces if f.mode & Blender.NMesh.FaceModes['TWOSIDE']]:
  235. newf = []
  236. for v in faces[fi]:
  237. newv = len(vert)
  238. newf.append(newv)
  239. vert.append(Blender.Mesh.MVert(vert[v].co))
  240. vert[newv].no = -(vert[v].no.copy())
  241. newf.reverse()
  242. faces.append(newf)
  243. for ar in [ar for ar in [ftexc,flnk1,ftang,fcolr] if ar is not None]:
  244. ar.append(ar[fi])
  245. if type(ar[-1]) == type(list()):
  246. ar[-1].reverse()
  247. else:
  248. tmp = list(ar[-1])
  249. tmp.reverse()
  250. ar[-1] = tuple(tmp)
  251.  
  252. def CreateK2Mesh(filename):
  253.  
  254. if not filename.lower().endswith('.model'):
  255. filename += '.model'
  256. scn = Blender.Scene.GetCurrent()
  257.  
  258. #meshes = [ob for ob in scn.objects if ob.type == 'Mesh']
  259. meshes = []
  260. armOb = [ob for ob in scn.objects if ob.type == 'Armature'][0]
  261. armature = armOb.getData()
  262. rest = armature.restPosition
  263. armature.restPosition = True
  264. armOb.makeDisplayList()
  265. # This causes the makeDisplayList command to effect the mesh
  266. Blender.Set('curframe', Blender.Get('curframe'))
  267.  
  268. vlog ("==========================export start=======================================")
  269. for ob_main in [ob for ob in scn.objects if ob.type == 'Mesh']:
  270. for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
  271. mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, True, scn)
  272. if not mesh:
  273. continue
  274. #triangulate
  275. mesh.name = ob.name
  276. has_quads = False
  277. for f in mesh.faces:
  278. if len(f) == 4:
  279. has_quads = True
  280. break
  281. if has_quads:
  282. vlog('triangulating')
  283. oldmode = Mesh.Mode()
  284. Mesh.Mode(Mesh.SelectModes['FACE'])
  285. mesh.sel = True
  286. tempob = scn.objects.new(mesh)
  287. mesh.quadToTriangle(0) # more=0 shortest length
  288. oldmode = Mesh.Mode(oldmode)
  289. scn.objects.unlink(tempob)
  290. Mesh.Mode(oldmode)
  291. #copy normals
  292. for v in ob.getData(mesh=1).verts:
  293. mesh.verts[v.index].no = v.no
  294.  
  295. mesh.transform(ob_mat)
  296.  
  297. # High Quality Normals
  298. if hq_normals:
  299. BPyMesh.meshCalcNormals(mesh)
  300. else:
  301. # transforming normals is incorrect
  302. # when the matrix is scaled,
  303. # better to recalculate them
  304. mesh.calcNormals()
  305. meshes.append(mesh)
  306.  
  307. bone_indices,bonedata = create_bone_data(armature,armOb)
  308.  
  309. headdata = cStringIO.StringIO()
  310. headdata.write(struct.pack("<i",3))
  311. headdata.write(struct.pack("<i",len(meshes)))
  312. headdata.write(struct.pack("<i",0))
  313. headdata.write(struct.pack("<i",0))
  314. headdata.write(struct.pack("<i",len(armature.bones.values())))
  315.  
  316. headdata.write(struct.pack("<6f",*generate_bbox(meshes))) # bounding box
  317.  
  318. meshindex = 0
  319.  
  320. file = open(filename, 'wb')
  321. file.write('SMDL')
  322.  
  323. write_block(file,'head',headdata.getvalue())
  324. write_block(file,'bone',bonedata)
  325.  
  326. for mesh in meshes:
  327. vert = [vert for vert in mesh.verts]
  328. flnk1 = [[mesh.getVertexInfluences(v.index) for v in f.v] for f in mesh.faces]
  329. faces = [[v.index for v in f.v] for f in mesh.faces]
  330. ftang = mesh.getTangents()
  331. ftexc = [[(round(uv.x, 6), round(uv.y, 6)) for uv in f.uv] for f in mesh.faces]
  332.  
  333. if mesh.vertexColors:
  334. fcolr = [[c for c in f.col] for f in mesh.faces]
  335. else:
  336. fcolr = None
  337.  
  338. duplicate_twosided_faces(mesh,faces,vert,ftexc,flnk1,ftang,fcolr)
  339.  
  340. if mesh.faceUV:
  341. #duplication
  342. texc = face_to_vertices_dup(faces,ftexc,vert)
  343. if hq_lighting:
  344. fsign = calcFaceSigns(ftexc)
  345. #duplication
  346. sign = face_to_vertices_dup(faces,fsign,vert)
  347. #recreate texc data due to duplicated vertices
  348. texc = face_to_vertices(faces,ftexc,vert)
  349.  
  350. tang = face_to_vertices(faces,ftang,vert)
  351. #Gram-Schmidt orthogonalize
  352. for i in xrange(len(vert)):
  353. tang[i] = (tang[i] - vert[i].no * DotVecs(tang[i],vert[i].no)).normalize()
  354.  
  355. lnk1 = face_to_vertices(faces,flnk1,vert)
  356. if mesh.vertexColors:
  357. colr = face_to_vertices(faces,fcolr,vert)
  358. else:
  359. colr = None
  360.  
  361. write_block(file,'mesh',create_mesh_data(mesh,vert,meshindex))
  362. write_block(file,'vrts',create_vrts_data(vert,meshindex))
  363. write_block(file,'lnk1',create_lnk1_data(lnk1,meshindex,bone_indices))
  364. if len(faces) > 0:
  365. write_block(file,'face',create_face_data(vert,faces,meshindex))
  366. if mesh.faceUV:
  367. write_block(file,"texc",create_texc_data(texc,meshindex))
  368. if hq_lighting:
  369. for i in xrange(len(tang)):
  370. if sign[i] == 0:
  371. tang[i] = -(tang[i].copy())
  372. write_block(file,"tang",create_tang_data(tang,meshindex))
  373. if hq_lighting:
  374. write_block(file,"sign",create_sign_data(meshindex,sign))
  375. write_block(file,"nrml",create_nrml_data(vert,meshindex))
  376. if mesh.vertexColors:
  377. write_block(file,"colr",create_colr_data(colr,meshindex))
  378. meshindex+=1
  379. vlog('total vertices duplicated: %d' % (len(vert) - len(mesh.verts)))
  380.  
  381. armature.restPosition = rest
  382. armOb.makeDisplayList()
  383. # This causes the makeDisplayList command to effect the mesh
  384. Blender.Set('curframe', Blender.Get('curframe'))
  385. def roundVector(vec,dec=17):
  386. fvec=[]
  387. for v in vec:
  388. fvec.append(round(v,dec))
  389. return Vector(fvec)
  390. def roundMatrix(mat,dec=17):
  391. fmat = []
  392. for row in mat:
  393. fmat.append(roundVector(row,dec))
  394. return Matrix(*fmat)
  395. ##############################
  396. #CLIPS
  397. ##############################
  398.  
  399. MKEY_X,MKEY_Y,MKEY_Z,\
  400. MKEY_PITCH,MKEY_ROLL,MKEY_YAW,\
  401. MKEY_VISIBILITY,\
  402. MKEY_SCALE_X,MKEY_SCALE_Y,MKEY_SCALE_Z, \
  403. MKEY_COUNT \
  404. = range(11)
  405.  
  406. from math import sqrt,atan2,degrees
  407. from sys import float_info
  408.  
  409. def MatToEulerYXZ_(M):
  410. e = Vector(0.0,0.0,0.0)
  411. i = 1
  412. j = 0
  413. k = 2
  414. cy = sqrt(M[i][i]*M[i][i] + M[j][i]*M[j][i])
  415. if (cy > 16*float_info.epsilon):
  416. e[0] = atan2(M[j][k], M[k][k])
  417. e[1] = atan2(-M[i][k], cy)
  418. e[2] = atan2(M[i][j], M[i][i])
  419. else:
  420. e[0] = atan2(-M[k][j], M[j][j])
  421. e[1] = atan2(-M[i][k], cy)
  422. e[2] = 0
  423. e[0] = -e[0]
  424. e[1] = -e[1]
  425. e[2] = -e[2]
  426. return e
  427.  
  428. _epsilon = 1E-12
  429.  
  430. def _eulerIndices(i, neg, alt):
  431. """Helper function for _getRotation()."""
  432. next = [1, 2, 0, 1]
  433. j = next[i+int(neg)]
  434. k = 3-i-j
  435. h = next[k+(1^int(neg)^int(alt))]
  436. return j,k,h
  437. def _eulerGivens(a, b):
  438. """Helper function for _getRotation()."""
  439. global _epsilon
  440.  
  441. absa = abs(a)
  442. absb = abs(b)
  443. # b=0?
  444. if absb<=_epsilon:
  445. if a>=0:
  446. c = 1.0
  447. else:
  448. c = -1.0
  449. return (c, 0.0, absa)
  450. # a=0?
  451. elif absa<=_epsilon:
  452. if b>=0:
  453. s = 1.0
  454. else:
  455. s = -1.0
  456. return (0.0, s, absb)
  457. # General case
  458. else:
  459. if absb>absa:
  460. t = a/b
  461. u = sqrt(1.0+t*t)
  462. if b<0:
  463. u = -u
  464. s = 1.0/u
  465. c = s*t
  466. r = b*u
  467. else:
  468. t = b/a
  469. u = sqrt(1.0+t*t)
  470. if (a<0):
  471. u = -u
  472. c = 1.0/u
  473. s = c*t
  474. r = a*u
  475. return c,s,r
  476.  
  477. def MatToEulerYXZ(M):
  478. y,x,z = _getRotation(2, True, True, True,M)
  479. return Vector(x,y,z)
  480.  
  481. def _getRotation(i, neg, alt, rev,M):
  482. i = 2
  483. neg = True
  484. alt = True
  485. rev = True
  486. v = [M[0][i], M[1][i], M[2][i]]
  487. j,k,h = _eulerIndices(i, neg, alt)
  488. a = v[h]
  489. b = v[k]
  490. c,s,r = _eulerGivens(a, b)
  491. v[h] = r
  492. s1 = c*M[k][j] - s*M[h][j]
  493. c1 = c*M[k][k] - s*M[h][k]
  494. r1 = atan2(s1, c1)
  495. r2 = atan2(v[j], v[i])
  496. r3 = atan2(s, c)
  497. if alt:
  498. r3 = -r3
  499. if neg:
  500. r1 = -r1
  501. r2 = -r2
  502. r3 = -r3
  503. if rev:
  504. tmp = r1
  505. r1 = r3
  506. r3 = tmp
  507. return r1,r2,r3
  508.  
  509. def ClipBone(file,bone_name,motion,index):
  510. for keytype in xrange(MKEY_COUNT):
  511. keydata = cStringIO.StringIO()
  512. key = motion[keytype]
  513. if keytype != MKEY_VISIBILITY:
  514. key = map(lambda k: round(k,ROUND_KEYS), key)
  515. if min(key) == max(key):
  516. key = [key[0]]
  517. numkeys = len(key)
  518. keydata.write(struct.pack("<i",index))
  519. keydata.write(struct.pack("<i",keytype))
  520. keydata.write(struct.pack("<i",numkeys))
  521. keydata.write(struct.pack("B",len(bone_name)))
  522. keydata.write(bone_name)
  523. keydata.write(struct.pack("B",0))
  524. if keytype == MKEY_VISIBILITY:
  525. keydata.write(struct.pack('%dB' % numkeys,*key))
  526. else:
  527. keydata.write(struct.pack('<%df' % numkeys,*key))
  528. write_block(file,'bmtn',keydata.getvalue())
  529.  
  530. def CreateK2Clip(filename):
  531. objList = Blender.Object.GetSelected()
  532. if len(objList) != 1 or objList[0].type != 'Armature':
  533. err('Select needed armature only')
  534. return
  535. armob = objList[0]
  536. motions = {}
  537. vlog ('baking animation')
  538. armature = armob.getData()
  539. if transform:
  540. worldmat = armob.mat.copy()
  541. else:
  542. worldmat = Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])
  543.  
  544. for frame in range(startframe,endframe):
  545. armob.evaluatePose(frame)
  546. pose = armob.getPose()
  547. for bone in pose.bones.values():
  548. matrix = bone.poseMatrix
  549. if bone.parent:
  550. matrix = matrix * (bone.parent.poseMatrix.copy().invert())
  551. else:
  552. matrix = matrix * worldmat
  553. if bone.name not in motions:
  554. motions[bone.name] = []
  555. for i in xrange(MKEY_COUNT):
  556. motions[bone.name].append([])
  557. motion = motions[bone.name]
  558.  
  559. translation = matrix.translationPart()
  560. rotation = MatToEulerYXZ(matrix.rotationPart())
  561. scale = matrix.scalePart()
  562. visibility = 255
  563.  
  564. motion[MKEY_X].append(translation[0])
  565. motion[MKEY_Y].append(translation[1])
  566. motion[MKEY_Z].append(translation[2])
  567.  
  568. motion[MKEY_PITCH].append(-degrees(rotation[0]))
  569. motion[MKEY_ROLL].append(-degrees(rotation[1]))
  570. motion[MKEY_YAW].append(-degrees(rotation[2]))
  571.  
  572. motion[MKEY_SCALE_X].append(scale[0])
  573. motion[MKEY_SCALE_Y].append(scale[1])
  574. motion[MKEY_SCALE_Z].append(scale[2])
  575.  
  576. motion[MKEY_VISIBILITY].append(visibility)
  577.  
  578. headdata = cStringIO.StringIO()
  579. headdata.write(struct.pack("<i",2))
  580. headdata.write(struct.pack("<i",len(motions.keys())))
  581. headdata.write(struct.pack("<i",endframe - startframe))
  582.  
  583. file = open(filename, 'wb')
  584. file.write('CLIP')
  585. write_block(file,'head',headdata.getvalue())
  586.  
  587. index = 0
  588. for bone_name in sorted(armature.bones.keys(),cmp=lambda x, y: bone_depth(armature.bones[x]) - bone_depth(armature.bones[y])):
  589. ClipBone(file,bone_name,motions[bone_name],index)
  590. index+=1
  591. #file.close()
  592.  
  593. #-------------------------------\
  594. # common |
  595. #-------------------------------/
  596. ######################################################
  597. # GUI STUFF
  598. ######################################################
  599.  
  600. draw_busy_screen = 0
  601. EVENT_NOEVENT = 1
  602. EVENT_EXPORT = 2
  603. EVENT_QUIT = 3
  604. EVENT_MESHFILENAME = 4
  605. EVENT_ANIMFILENAME = 5
  606. EVENT_MESHFILENAME_STRINGBUTTON = 6
  607. EVENT_ANIMFILENAME_STRINGBUTTON = 7
  608. EVENT_APPLY_TRANSFORM = 7
  609. mesh_filename = Blender.Draw.Create("")
  610. anim_filename = Blender.Draw.Create("")
  611. apply_transform = True
  612. EXPORT_APPLY_MODIFIERS = Blender.Draw.Create(1)
  613. EXPORT_HQ_NORMALS = Blender.Draw.Create(1)
  614. EXPORT_HQ_LIGHTING = Blender.Draw.Create(1)
  615. EXPORT_FLIP_UV = Blender.Draw.Create(1)
  616.  
  617.  
  618. startframe = 1
  619. endframe = Blender.Scene.GetCurrent().getRenderingContext().endFrame() + 1
  620. STATRFRAME_slider = Blender.Draw.Create(startframe)
  621. ENDFRAME_slider = Blender.Draw.Create(endframe - 1)
  622.  
  623.  
  624.  
  625. flip_uv = True
  626. scale = 1.0
  627. hq_normals = True
  628. transform = True
  629. hq_lighting = True
  630. ROUND_KEYS = 4
  631.  
  632. ROUNDING_slider = Blender.Draw.Create(ROUND_KEYS)
  633. ######################################################
  634. # Callbacks for Window functions
  635. ######################################################
  636. def meshname_callback(filename):
  637. global mesh_filename
  638. mesh_filename.val=filename
  639.  
  640. def animname_callback(filename):
  641. global anim_filename
  642. #anim_filename.val=Blender.sys.dirname(filename)
  643. anim_filename.val=filename
  644.  
  645. ######################################################
  646. # GUI Functions
  647. ######################################################
  648. def handle_event(evt, val):
  649. if evt == Blender.Draw.ESCKEY:
  650. Blender.Draw.Exit()
  651. return
  652.  
  653. def handle_button_event(evt):
  654. global EVENT_NOEVENT, EVENT_EXPORT, EVENT_QUIT, EVENT_MESHFILENAME, EVENT_ANIMFILENAME, EVENT_MESHFILENAME_STRINGBUTTON, EVENT_ANIMFILENAME_STRINGBUTTON,EXPORT_FLIP_UV
  655. global flip_uv,draw_busy_screen, mesh_filename, anim_filename, scale_slider, scale,EXPORT_HQ_NORMALS,hq_normals,EXPORT_APPLY_MODIFIERS,transform,EXPORT_HQ_LIGHTING,hq_lighting
  656. global STATRFRAME_slider,startframe,ENDFRAME_slider,endframe,ROUND_KEYS,ROUNDING_slider
  657. if evt == EVENT_EXPORT:
  658. transform = EXPORT_APPLY_MODIFIERS.val
  659. hq_normals = EXPORT_HQ_NORMALS.val
  660. hq_lighting = EXPORT_HQ_LIGHTING.val
  661. flip_uv = EXPORT_FLIP_UV.val
  662. Blender.Window.WaitCursor(1)
  663. draw_busy_screen = 1
  664. startframe = STATRFRAME_slider.val
  665. endframe = ENDFRAME_slider.val + 1
  666. ROUND_KEYS = ROUNDING_slider.val
  667. Blender.Draw.Draw()
  668. if len(mesh_filename.val)>0:
  669. CreateK2Mesh(mesh_filename.val)
  670. if len(anim_filename.val)>0:
  671. CreateK2Clip(anim_filename.val)
  672. draw_busy_screen = 0
  673. Blender.Draw.Redraw(1)
  674. Blender.Window.WaitCursor(0)
  675. return
  676. if evt == EVENT_QUIT:
  677. Blender.Draw.Exit()
  678. if evt == EVENT_MESHFILENAME:
  679. Blender.Window.FileSelector(meshname_callback, "Select mesh file...")
  680. Blender.Draw.Redraw(1)
  681. if evt == EVENT_ANIMFILENAME:
  682. Blender.Window.FileSelector(animname_callback, "Select anim file...")
  683. Blender.Draw.Redraw(1)
  684.  
  685. def show_gui():
  686. global EVENT_NOEVENT, EVENT_EXPORT, EVENT_QUIT, EVENT_MESHFILENAME, EVENT_ANIMFILENAME, EVENT_MESHFILENAME_STRINGBUTTON, EVENT_ANIMFILENAME_STRINGBUTTON,EXPORT_FLIP_UV
  687. global draw_busy_screen, mesh_filename, anim_filename, scale_slider,EXPORT_APPLY_MODIFIERS,EXPORT_HQ_NORMALS,EXPORT_HQ_LIGHTING
  688. global STATRFRAME_slider,startframe,ENDFRAME_slider,endframe,ROUND_KEYS,ROUNDING_slider
  689. button_width = 240
  690. browsebutton_width = 60
  691. button_height = 25
  692. if draw_busy_screen == 1:
  693. Blender.BGL.glClearColor(0.3,0.3,0.3,1.0)
  694. Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
  695. Blender.BGL.glColor3f(1,1,1)
  696. Blender.BGL.glRasterPos2i(20,25)
  697. Blender.Draw.Text("Please wait...")
  698. return
  699. Blender.BGL.glClearColor(0.6,0.6,0.6,1.0)
  700. Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
  701. Blender.Draw.Button("Export!", EVENT_EXPORT, 20, 2*button_height, button_width, button_height, "Start the export")
  702. Blender.Draw.Button("Quit", EVENT_QUIT, 20, button_height, button_width, button_height, "Quit this script")
  703.  
  704. Blender.Draw.Button("Browse...", EVENT_MESHFILENAME, 21+button_width-browsebutton_width, 8*button_height, browsebutton_width, button_height, "Specify mesh-file")
  705. Blender.Draw.Button("Browse...", EVENT_ANIMFILENAME, 21+button_width-browsebutton_width, 3*button_height, browsebutton_width, button_height, "Specify anim-file")
  706. mesh_filename = Blender.Draw.String("Mesh file:", EVENT_MESHFILENAME_STRINGBUTTON, 20, 8*button_height, button_width-browsebutton_width, button_height, mesh_filename.val, 255, "Mesh-File to export")
  707. anim_filename = Blender.Draw.String("Anim file:", EVENT_ANIMFILENAME_STRINGBUTTON, 20, 3*button_height, button_width-browsebutton_width, button_height, anim_filename.val, 255, "Anim-File to export")
  708. EXPORT_FLIP_UV = Blender.Draw.Toggle('V-Flip UV', EVENT_NOEVENT, 20, 9*button_height, button_width, button_height, EXPORT_FLIP_UV.val, 'Flip UV mapping vertically.')
  709. EXPORT_APPLY_MODIFIERS = Blender.Draw.Toggle('Apply Modifiers', EVENT_NOEVENT, 20, 10*button_height, button_width, button_height, EXPORT_APPLY_MODIFIERS.val, 'Use transformed mesh data from each object.')
  710. EXPORT_HQ_NORMALS = Blender.Draw.Toggle('HQ Normals', EVENT_NOEVENT ,20, 11*button_height, button_width, button_height, EXPORT_HQ_NORMALS.val, 'Calculate high quality normals for rendering.')
  711. EXPORT_HQ_LIGHTING = Blender.Draw.Toggle('HQ Lighting', EVENT_NOEVENT ,20, 12*button_height, button_width, button_height, EXPORT_HQ_LIGHTING.val, 'Proper saving when mesh uses mirrored normal map. Increases vertex count.. etc')
  712.  
  713. ROUNDING_slider = Blender.Draw.Number("Round Motion Keys to:", EVENT_NOEVENT, 20, 6*button_height, button_width, button_height, ROUNDING_slider.val, 0,20, "How many digits leave after the decimal point in float motion keys")
  714. STATRFRAME_slider = Blender.Draw.Number("Start Frame:", EVENT_NOEVENT, 20, 5*button_height, button_width, button_height, STATRFRAME_slider.val, 1,1000, "Set starting frame")
  715. ENDFRAME_slider = Blender.Draw.Number("End Frame:", EVENT_NOEVENT, 20, 4*button_height, button_width, button_height, ENDFRAME_slider.val, 1, 1000, "Set ending frame")
  716. Blender.Draw.Register (show_gui, handle_event, handle_button_event)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement