-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodeSelecter.py
297 lines (263 loc) · 11.8 KB
/
nodeSelecter.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
import numpy as np
import os
import random
from BVHFile import BVHFile
from transformationUtil import *
# node has file, startframe, endframe, and transformation
# to calculate joints positition from start to end of node
# additionally, it has requiredYRot and requiredTranslation that
# to be gradually applied during the motion
class Node:
def __init__(
self,
file: BVHFile,
startFrame: int,
endFrame: int,
transformation: np.ndarray = np.eye(4),
requiredYRot: float = 0,
requiredTranslation: np.ndarray = np.array([0, 0, 0]),
):
self.file: BVHFile = file
self.startFrame: int = startFrame
self.endFrame: int = endFrame
self.transformation = transformation
self.requiredYRot = requiredYRot
self.requiredTranslation = requiredTranslation
# find all contact points to get start of contacts
def findStartOfContacts(
file: BVHFile, contactJointName="LeftToe", velocityThreshold=30
):
contacts = []
contactJointIdx = file.jointNames.index(contactJointName)
for i in range(file.numFrames):
speed = file.getJointSpeed(contactJointIdx, i)
contacts.append(speed < velocityThreshold)
startOfContacts = [
i for i in range(1, len(contacts)) if contacts[i] and not contacts[i - 1]
]
return startOfContacts
# get direction of movment by current joint posture
# get direction by cross product of two vectors:
# spine to left up leg, spine to right up leg
def getDirection(file: BVHFile, jointsPosition: np.ndarray):
spinePos = toCartesian(jointsPosition[file.jointNames.index("Spine")])
leftPos = toCartesian(jointsPosition[file.jointNames.index("LeftUpLeg")])
rightPos = toCartesian(jointsPosition[file.jointNames.index("RightUpLeg")])
direction = np.cross(rightPos - spinePos, leftPos - spinePos)
direction[1] = 0
return normalize(direction)
class nodeSelecter:
def __init__(
self,
folderPath,
idleFolderPath,
rotationInterpolation: float = 0.0,
translationInterpolation: float = 0.0,
contactVelocityThreshold=30,
):
self.files: list[BVHFile] = []
for fileName in os.listdir(folderPath):
if fileName.endswith(".bvh"):
filePath = os.path.join(folderPath, fileName)
self.files.append(BVHFile(filePath))
self.idleFiles: list[BVHFile] = []
for fileName in os.listdir(idleFolderPath):
if fileName.endswith(".bvh"):
filePath = os.path.join(idleFolderPath, fileName)
self.idleFiles.append(BVHFile(filePath))
self.file = self.files[0]
# file, start, end, startDirection, endDirection
self.leftTransitions: list[tuple[BVHFile, int, int, np.ndarray, np.ndarray]] = (
[]
)
self.rightTransitions: list[
tuple[BVHFile, int, int, np.ndarray, np.ndarray]
] = []
self.rotationInterpolation = rotationInterpolation
self.translationInterpolation = translationInterpolation
# find all nodes among files
for file in self.files:
leftStartOfContacts = findStartOfContacts(
file, "LeftToe", contactVelocityThreshold
)
rightStartOfContacts = findStartOfContacts(
file, "RightToe", contactVelocityThreshold
)
left, right = 0, 0
while left < len(leftStartOfContacts) and right < len(rightStartOfContacts):
if leftStartOfContacts[left] < rightStartOfContacts[right]:
start = leftStartOfContacts[left]
end = rightStartOfContacts[right]
startJointsPosition = file.calculateJointsPositionFromFrame(start)
startDirection = getDirection(file, startJointsPosition)
endJointsPosition = file.calculateJointsPositionFromFrame(end)
endDirection = getDirection(file, endJointsPosition)
self.leftTransitions.append(
(file, start, end, startDirection, endDirection)
)
left += 1
else:
start = rightStartOfContacts[right]
end = leftStartOfContacts[left]
startJointsPosition = file.calculateJointsPositionFromFrame(start)
startDirection = getDirection(file, startJointsPosition)
endJointsPosition = file.calculateJointsPositionFromFrame(end)
endDirection = getDirection(file, endJointsPosition)
self.rightTransitions.append(
(file, start, end, startDirection, endDirection)
)
right += 1
self.leftContactIdx = self.file.jointNames.index("LeftToe")
self.rightContactIdx = self.file.jointNames.index("RightToe")
self.isLeftContact = True
# get start idle node by first position and direction
def getStartIdleNode(
self,
controlPosition,
controlDirection,
):
idleIdx = random.randrange(len(self.idleFiles))
file = self.idleFiles[idleIdx]
startJointsPosition = file.calculateJointsPositionFromFrame(0)
startDirection = getDirection(file, startJointsPosition)
rotation = quatToMat(vecToVecQuat(startDirection, controlDirection))
position = toCartesian(file.calculateJointPositionFromFrame(0, 0, rotation))
position[1] = 0
translation = translationMat(controlPosition - position)
return Node(file, 0, file.numFrames - 1, translation @ rotation)
# get idle node that can be smoothly interpolated from current motion
def getIdleNode(
self,
jointsPosition,
):
# select random idle motion from idle files
idleIdx = random.randrange(len(self.idleFiles))
file = self.idleFiles[idleIdx]
direction = getDirection(file, jointsPosition)
startJointsPosition = file.calculateJointsPositionFromFrame(0)
startDirection = getDirection(file, startJointsPosition)
rotation = quatToMat(vecToVecQuat(startDirection, direction))
# determine which foot is at front
rootPosition = toCartesian(jointsPosition[0])
rootPosition[1] = 0
leftContactPosition = toCartesian(jointsPosition[self.leftContactIdx])
leftContactPosition[1] = 0
rightContactPosition = toCartesian(jointsPosition[self.rightContactIdx])
rightContactPosition[1] = 0
leftDistance = np.linalg.norm(
normalize(leftContactPosition - rootPosition) - direction
)
rightDistance = np.linalg.norm(
normalize(rightContactPosition - rootPosition) - direction
)
frontContactIdx = (
self.leftContactIdx
if leftDistance < rightDistance
else self.rightContactIdx
)
frontContactPosition = (
leftContactPosition
if leftDistance < rightDistance
else rightContactPosition
)
# match front contact joint
position = toCartesian(
file.calculateJointPositionFromFrame(frontContactIdx, 0, rotation)
)
position[1] = 0
translation = translationMat(frontContactPosition - position)
return Node(file, 0, file.numFrames - 1, translation @ rotation)
# get next node from current transition and left right contact state
def getNextNode(
self,
currentJointsPosition,
currentDirection,
objectiveDirection,
):
currentPosition = toCartesian(currentJointsPosition[0])
currentPosition[1] = 0
transitions = (
self.leftTransitions if self.isLeftContact else self.rightTransitions
)
contactIdx = self.leftContactIdx if self.isLeftContact else self.rightContactIdx
# find best index (best next node) and list of nodes that are good enough
# good enough means rotation can be accurate when interpolated
bestIdx = 0
goodEnoughIdxes = []
bestError = float("inf")
for idx in range(len(transitions)):
file, start, end, startDirection, endDirection = transitions[idx]
rotation = quatToMat(vecToVecQuat(startDirection, currentDirection))
endDirection = toCartesian(rotation @ toProjective(endDirection))
error = np.linalg.norm(endDirection - objectiveDirection)
if error < bestError:
bestError = error
bestIdx = idx
if error < 2 * math.sin(self.rotationInterpolation * math.pi / 180 / 2):
goodEnoughIdxes.append(idx)
# if there is no good enough nodes we just ust bext index
# else, we choose the one with biggest displacement along objective direction
if len(goodEnoughIdxes) > 0:
bestIdx = goodEnoughIdxes[0]
bestDisplacement = -float("inf")
for idx in goodEnoughIdxes:
file, start, end, startDirection, endDirection = transitions[idx]
rotation = quatToMat(vecToVecQuat(startDirection, currentDirection))
startPosition = toCartesian(
file.calculateJointPositionFromFrame(0, start, rotation)
)
endPosition = toCartesian(
file.calculateJointPositionFromFrame(0, end, rotation)
)
displacement = np.dot(objectiveDirection, endPosition - startPosition)
if displacement > bestDisplacement:
bestIdx = idx
bestDisplacement = displacement
file, start, end, startDirection, endDirection = transitions[bestIdx]
rotation = quatToMat(vecToVecQuat(startDirection, currentDirection))
# rotation interpolation
# we adjust end Direction to be matched with objective direction
# maximum amount of adjustment is rotationInterpolation value in degree
endDirection = toCartesian(rotation @ toProjective(endDirection))
angleError = np.arccos(np.clip(np.dot(endDirection, objectiveDirection), -1, 1))
interpAngle = np.clip(
angleError,
-self.rotationInterpolation * math.pi / 180,
self.rotationInterpolation * math.pi / 180,
)
# translation interpolation
# from startPosition and endPosition, we get displacement
# we reduce orthogonal component of displacement with respect to objective direction
# maximum by translationInterpolation Value
startPosition = toCartesian(
file.calculateJointPositionFromFrame(0, start, rotation)
)
startPosition[1] = 0
endPosition = toCartesian(
file.calculateJointPositionFromFrame(0, end, rotation)
)
endPosition[1] = 0
translationError = orthogonalComponent(
objectiveDirection, endPosition - startPosition
)
translationErrorSize = np.linalg.norm(translationError)
interpTranslation = (
-min(translationErrorSize, self.translationInterpolation)
* translationError
/ translationErrorSize
)
# calculate translation by matching contact position
startContactPosition = toCartesian(
file.calculateJointPositionFromFrame(contactIdx, start, rotation)
)
currentContactPosition = toCartesian(currentJointsPosition[contactIdx])
translationVector = currentContactPosition - startContactPosition
translationVector[1] = 0
translation = translationMat(translationVector)
# revert contact state
self.isLeftContact = not self.isLeftContact
return Node(
file, start, end, translation @ rotation, interpAngle, interpTranslation
)
if __name__ == "__main__":
print("nothing implemented")