forked from jhoolmans/mayaImporterBVH
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bvh_importer.py
317 lines (261 loc) · 8.75 KB
/
bvh_importer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#
# BVH Importer script for Maya.
#
# Importer for .bvh files (BioVision Hierachy files).
# BVH is a common ascii motion capture data format containing skeletal and motion data.
#
# <license>
# BVH Importer script for Maya.
# Copyright (C) 2012 Jeroen Hoolmans
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# </license>
__author__ = "Jeroen Hoolmans"
__copyright__ = "Copyright 2012, Jeroen Hoolmans"
__credits__ = ["Jeroen Hoolmans"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Jeroen Hoolmans"
__email__ = "jhoolmans@gmail.com"
__status__ = "Production"
import pymel.core as pm
import maya.cmds as mc
import os
# This maps the BVH naming convention to Maya
translationDict = {
"Xposition" : "translateX",
"Yposition" : "translateY",
"Zposition" : "translateZ",
"Xrotation" : "rotateX",
"Yrotation" : "rotateY",
"Zrotation" : "rotateZ"
}
class TinyDAG(object):
#
# Small helper class to keep track of parents
#
def __init__(self, obj, pObj = None):
self.obj = obj
self.pObj = pObj
def __str__(self):
# returns object name
return str(self.obj)
def _fullPath(self):
# returns full object path
if self.pObj is not None:
return "%s|%s" % (self.pObj._fullPath(), self.__str__())
return str(self.obj)
class BVHImporterDialog(object):
#
# Dialog class..
#
def __init__(self, debug=False):
# Don't use debug when importing more than 10 frames.. Otherwise it gets messy
self._name = "bvhImportDialog"
self._title = "BVH Importer %s" % __version__
# UI related
self._textfield = ""
self._scaleField = ""
self._frameField = ""
self._rotationOrder = ""
self._reload = ""
# Other
self._rootNode = None # Used for targeting
self._debug = debug
# BVH specific stuff
self._filename = ""
self._channels = []
self.setup_ui()
def setup_ui(self):
# Creates the great dialog
win = self._name
if mc.window(win, ex=True):
mc.deleteUI(win)
# Non sizeable dialog
win = mc.window(self._name, title=self._title, w=200, rtf=True, sizeable=False)
mc.columnLayout(adj=1, rs=5)
mc.separator()
mc.text("Options")
mc.separator()
mc.rowColumnLayout( numberOfColumns=2,
columnWidth=[(1, 80), (2, 150)],
cal=[(1, "right"), (2, "center")],
cs=[(1,5), (2,5)],
rs=[(1,5), (2,5)])
mc.text("Rig scale")
self._scaleField = mc.floatField(minValue=0.01, maxValue=2, value=1)
mc.text("Frame offset")
self._frameField = mc.intField(minValue=0)
mc.text("Rotation Order")
self._rotationOrder = mc.optionMenu()
mc.menuItem( label='XYZ' )
mc.menuItem( label='YZX' )
mc.menuItem( label='ZXY' )
mc.menuItem( label='XZY' )
mc.menuItem( label='YXZ' )
mc.menuItem( label='ZYX' )
mc.setParent("..")
mc.separator()
# Targeting UI
mc.text("Skeleton Targeting")
mc.text("(Select the hips)")
mc.separator()
mc.rowColumnLayout( numberOfColumns=2,
columnWidth=[(1, 150), (2, 80)],
cs=[(1,5), (2,5)],
rs=[(1,5), (2,5)])
self._textfield = mc.textField(editable=False)
mc.button("Select/Clear", c=self._on_select_root)
mc.setParent("..")
mc.separator()
mc.button("Import..", c=self._on_select_file)
self._reload = mc.button("Reload", enable=False, c=self._read_bvh)
# Sorry :)
mc.text("Created by Jeroen Hoolmans")
mc.window(win, e=True, rtf=True, sizeable=False)
mc.showWindow(win)
def _on_select_file(self, e):
# Without All Files it didn't work for some reason..
filter = "All Files (*.*);;Motion Capture (*.bvh)"
dialog = mc.fileDialog2(fileFilter=filter, dialogStyle=1, fm=1)
if dialog is None:
return
if not len(dialog):
return
self._filename = dialog[0]
mc.button(self._reload, e=True, enable=True)
# Action!
self._read_bvh()
def _read_bvh(self, e=False):
# Safe close is needed for End Site part to keep from setting new parent.
safeClose = False
# Once motion is active, animate.
motion = False
# Clear channels before appending
self._channels = []
# Scale the entire rig and animation
rigScale = mc.floatField(self._scaleField, q=True, value=True)
frame = mc.intField(self._frameField, q=True, value=True)
rotOrder = mc.optionMenu(self._rotationOrder, q=True, select=True) - 1
with open(self._filename) as f:
# Check to see if the file is valid (sort of)
if not f.next().startswith("HIERARCHY"):
mc.error("No valid .bvh file selected.")
return False
if self._rootNode is None:
# Create a group for the rig, easier to scale. (Freeze transform when ungrouping please..)
mocapName = os.path.basename(self._filename)
grp = pm.group(em=True,name="_mocap_%s_grp" % mocapName)
grp.scale.set(rigScale, rigScale, rigScale)
# The group is now the 'root'
myParent = TinyDAG(str(grp), None)
else:
myParent = TinyDAG(str(self._rootNode), None)
self._clear_animation()
for line in f:
if not motion:
# root joint
if line.startswith("ROOT"):
# Set the Hip joint as root
if self._rootNode:
myParent = TinyDAG(str(self._rootNode), None)
else:
myParent = TinyDAG(line[5:].rstrip(), myParent)
if "JOINT" in line:
jnt = line.split(" ")
# Create the joint
myParent = TinyDAG(jnt[-1].rstrip(), myParent)
if "End Site" in line:
# Finish up a hierarchy and ignore a closing bracket
safeClose = True
if "}" in line:
# Ignore when safeClose is on
if safeClose:
safeClose = False
continue
# Go up one level
if myParent is not None:
myParent = myParent.pObj
if myParent is not None:
mc.select(myParent._fullPath())
if "CHANNELS" in line:
chan = line.strip().split(" ")
if self._debug:
print chan
# Append the channels that are animated
for i in range(int(chan[1]) ):
self._channels.append("%s.%s" % (myParent._fullPath(), translationDict[chan[2 + i]] ) )
if "OFFSET" in line:
offset = line.strip().split(" ")
if self._debug:
print offset
jntName = str(myParent)
# When End Site is reached, name it "_tip"
if safeClose:
jntName += "_tip"
# skip if exists
if mc.objExists(myParent._fullPath()):
jnt = pm.PyNode(myParent._fullPath())
jnt.rotateOrder.set(rotOrder)
jnt.translate.set([float(offset[1]), float(offset[2]), float(offset[3])])
continue
# Build the joint and set its properties
jnt = pm.joint(name=jntName, p=(0,0,0))
jnt.translate.set([float(offset[1]), float(offset[2]), float(offset[3])])
jnt.rotateOrder.set(rotOrder)
if "MOTION" in line:
# Animate!
motion = True
if self._debug:
if myParent is not None:
print "parent: %s" % myParent._fullPath()
else:
# We don't really need to use Framecount and time(since Python handles file reads nicely)
if "Frame" not in line:
data = line.split(" ")
if self._debug:
print "Animating.."
print "Data size: %d" % len(data)
print "Channels size: %d" % len(self._channels)
# Set the values to channels
for x in range(0, len(data) - 1 ):
if self._debug:
print "Set Attribute: %s %f" % (self._channels[x], float(data[x]))
mc.setKeyframe(self._channels[x], time=frame, value=float(data[x]))
frame = frame + 1
def _clear_animation(self):
# select root joint
pm.select(str(self._rootNode), hi=True)
nodes = pm.ls(sl=True)
trans_attrs = ["translateX", "translateY", "translateZ"]
rot_attrs = ["rotateX", "rotateY", "rotateZ"]
for node in nodes:
for attr in trans_attrs:
connections = node.attr(attr).inputs()
pm.delete(connections)
for attr in rot_attrs:
connections = node.attr(attr).inputs()
pm.delete(connections)
node.attr(attr).set(0)
def _on_select_root(self, e):
# When targeting, set the root joint (Hips)
selection = pm.ls(sl=True, type="joint")
if len(selection) == 0:
self._rootNode = None
mc.textField(self._textfield, e=True, text="")
else:
self._rootNode = selection[0]
mc.textField(self._textfield, e=True, text=str(self._rootNode))
if __name__ == "__main__":
dialog = BVHImporterDialog()