def getBlendedNextMotion2(nextMotionA, nextMotionB, prevEndPosture, t=None, attachPosition=True, attachOrientation=True):
     
    dA = prevEndPosture - nextMotionA[0]
    dB = prevEndPosture - nextMotionB[0]
    
    newNextMotionA = nextMotionA.copy()
    newNextMotionB = nextMotionB.copy()

    if attachPosition:
        p_offset_A = dA.rootPos
        p_offset_B = dB.rootPos
#        d.disableTranslation()
        newNextMotionA.translateByOffset(p_offset_A)
        newNextMotionB.translateByOffset(p_offset_B)

    if attachOrientation:
        R_offset_A = dA.getJointOrientationLocal(0)
        R_offset_A = mm.exp(mm.projectionOnVector(mm.logSO3(R_offset_A), mm.v3(0,1,0))) # # project on y axis
        R_offset_B = dA.getJointOrientationLocal(0)
        R_offset_B = mm.exp(mm.projectionOnVector(mm.logSO3(R_offset_B), mm.v3(0,1,0))) # # project on y axis
#        d.disableRotations([0])
        newNextMotionA.rotateTrajectory(R_offset_A)
        newNextMotionB.rotateTrajectory(R_offset_B)

    if t==None:
        blendedNextMotion = blendSegmentSmooth(newNextMotionA, newNextMotionB)
    else:
        blendedNextMotion = blendSegmentFixed(newNextMotionA, newNextMotionB, t)
    
#    del blendedNextMotion[0]
    return blendedNextMotion
Ejemplo n.º 2
0
def test_calcPointCloudMetric():
    pointsA = [(1,0,0), (0,0,0), (0,0,1)]
    R = mmMath.exp(mmMath.v3(0,1,0), math.pi/4)
    pointsB = []
    for p in pointsA:
        pointsB.append(np.dot(R, p)+(0,1,0))
    
    T = mmMath.I_SE3()
    distance = cmt.calcPointCloudMetric(pointsA, pointsB, T)
    print distance
    print T
    
    pointsC = []
    for p in pointsB:
        pointsC.append(mmMath.T2p(np.dot(T, mmMath.p2T(p))))
    
    viewer = ysv.SimpleViewer()
    def extraDrawCallback():
        for p in pointsA:
            ygh.drawPoint(p, (255,0,0))
        for p in pointsB:
            ygh.drawPoint(p, (0,255,0))
        for p in pointsC:
            ygh.drawPoint(p, (0,255,255))
    viewer.setExtraDrawCallback(extraDrawCallback)
    
    viewer.startTimer(1/30.)
    viewer.show()
    
    Fl.run()
def blendSegmentFixed(motionSegment0, motionSegment1, t, attachPosition=True, attachOrientation=True):
    motionSegment1 = motionSegment1.copy()
    if attachPosition:
        p_offset = motionSegment0[0].rootPos - motionSegment1[0].rootPos
        motionSegment1.translateByOffset(p_offset)
    if attachOrientation:
        R_offset = np.dot(motionSegment0[0].localRs[0], motionSegment1[0].localRs[0].T)
        R_offset = mm.exp(mm.projectionOnVector(mm.logSO3(R_offset), mm.v3(0,1,0))) # # project on y axis
        motionSegment1.rotateTrajectory(R_offset)
    
#    newMotion = ym.JointMotion( [None]*(int( (len(motionSegment    0)+len(motionSegment1))/2.) ) )
    newMotion = ym.JointMotion( [None]*(int( (1-t)*len(motionSegment0) + t*len(motionSegment1)) ) )
#    df0 = float(len(newMotion)) / len(motionSegment0)
#    df1 = float(len(newMotion)) / len(motionSegment1)
    for frame in range(len(newMotion)):
        normalizedFrame = float(frame)/(len(newMotion)-1)
#        normalizedFrame2 = yfg.H1(normalizedFrame)
#        normalizedFrame2 += df0*yfg.H2(normalizedFrame)
#        normalizedFrame2 += df1*yfg.H3(normalizedFrame)
#        posture0_at_normalizedFrame = motionSegment0.getPostureAt(normalizedFrame2*(len(motionSegment0)-1))
#        posture1_at_normalizedFrame = motionSegment1.getPostureAt(normalizedFrame2*(len(motionSegment1)-1))
#        newMotion[frame] = posture0_at_normalizedFrame.blendPosture(posture1_at_normalizedFrame, normalizedFrame2)
#        print normalizedFrame*(len(motionSegment0)-1)
        posture0_at_normalizedFrame = motionSegment0.getPostureAt(normalizedFrame*(len(motionSegment0)-1))
        posture1_at_normalizedFrame = motionSegment1.getPostureAt(normalizedFrame*(len(motionSegment1)-1))
#        newMotion[frame] = posture0_at_normalizedFrame.blendPosture(posture1_at_normalizedFrame, normalizedFrame)
        newMotion[frame] = posture0_at_normalizedFrame.blendPosture(posture1_at_normalizedFrame, t)
    return newMotion
    def test_setPositionTarget():
        bvhFilePath = '../samples/wd2_WalkSameSame00.bvh'
        motion = yf.readBvhFile(bvhFilePath, .01)
        print motion[0].skeleton
        
        lFoot = motion[0].skeleton.getJointIndex('LeftFoot')
        oripos = motion[0].getJointPositionGlobal(lFoot)
        newpos = oripos + mm.v3(0,1,0)

        motion_edit1 = copy.deepcopy(motion)
        setPositionTarget(motion_edit1, lFoot, newpos)
        
        motion_edit2 = copy.deepcopy(motion)
        setPositionTarget(motion_edit2, lFoot, newpos, [10,20], 5, yfg.identity)
        print len(motion), len(motion_edit2)
        
        viewer = ysv.SimpleViewer()
        viewer.record(False)
        viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,0,255), yr.LINK_LINE))
        viewer.doc.addObject('motion', motion)
        viewer.doc.addRenderer('motion_edit1', yr.JointMotionRenderer(motion_edit1, (0,255,0), yr.LINK_LINE))
        viewer.doc.addObject('motion_edit1', motion_edit1)
        viewer.doc.addRenderer('motion_edit2', yr.JointMotionRenderer(motion_edit2, (255,255,0), yr.LINK_LINE))
        viewer.doc.addObject('motion_edit2', motion_edit2)
        
        
        viewer.startTimer(1/30.)
        viewer.show()
        Fl.run()
Ejemplo n.º 5
0
def _readOgreSkeletonAnimations(dom, jointSkeleton, initialRs, scale=1.0):
    jointMotions = []
    animationEles = dom.getElementsByTagName('animation')

    for animationEle in animationEles:
        jointMotion = ym.Motion()
        #        jointMotion.resourceName = animationEle.getAttribute('name').encode()
        trackEles = animationEle.getElementsByTagName('track')
        first_keyframes = trackEles[0].getElementsByTagName('keyframe')
        len_keyframes = len(first_keyframes)
        time2frameMap = {}
        for i in range(len_keyframes):
            jointPosture = ym.JointPosture(jointSkeleton)
            #            jointPosture.initLocalRMap(initialRMap)
            jointPosture.initLocalRs(initialRs)
            jointMotion.append(jointPosture)

            # because each bone may not have same number of keyframes
            time2frameMap[first_keyframes[i].getAttribute('time')] = i

        for trackEle in trackEles:
            #            print i, trackEle.getAttribute('bone'), len(trackEle.getElementsByTagName('keyframe'))
            keyframeEles = trackEle.getElementsByTagName('keyframe')

            for keyframeEle in keyframeEles:
                keyframeTime = keyframeEle.getAttribute('time')

                # because each bone may not have same number of keyframes
                frame = time2frameMap[keyframeTime]
                jointPosture = jointMotion[frame]

                boneName = trackEle.getAttribute('bone').encode()
                if boneName == jointSkeleton.root.name:
                    transEle = keyframeEle.getElementsByTagName('translate')[0]
                    jointPosture.rootPos[0] = float(
                        transEle.getAttribute('x')) * scale
                    jointPosture.rootPos[1] = float(
                        transEle.getAttribute('y')) * scale
                    jointPosture.rootPos[2] = float(
                        transEle.getAttribute('z')) * scale

                rotEle = keyframeEle.getElementsByTagName('rotate')[0]
                angle = float(rotEle.getAttribute('angle'))
                axisEle = rotEle.getElementsByTagName('axis')[0]
                axis = mmMath.v3(float(axisEle.getAttribute('x')),
                                 float(axisEle.getAttribute('y')),
                                 float(axisEle.getAttribute('z')))
                R = mmMath.exp(axis, angle)

                #                jointPosture.mulLocalR(boneName, R)
                jointPosture.mulLocalR(jointSkeleton.getElementIndex(boneName),
                                       R)
                jointPosture.updateGlobalT()

        jointMotions.append(jointMotion)
    return jointMotions
Ejemplo n.º 6
0
def test_inertia_matrix():
    bvhFilePath = '../samples/chain_1.bvh'
    motion = yf.readBvhFile(bvhFilePath)
    
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 100.
    mcfg.defaultBoneRatio = 1.
    for i in range(motion[0].skeleton.getElementNum()):
        mcfg.addNode(motion[0].skeleton.getElementName(i))
    
    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    wcfg.gravity = (0,0,0)
    stepsPerFrame = 30
    wcfg.timeStep = (1/30.)/stepsPerFrame
    
    vpWorld = cvw.VpWorld(wcfg)
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    controlModel2 = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    vpWorld.initialize()
    
    controlModel2.translateByOffset((0,0,1))
    controlModel2.rotate(mm.exp(mm.v3(0,1,0), math.pi/2))
    
    print 'model local'
    print controlModel.getBodyInertiasLocal()
    print 
    print 'model global'
    print controlModel.getBodyInertiasGlobal()
    print
    print 'model2 global'
    print controlModel2.getBodyInertiasGlobal()

    viewer = ysv.SimpleViewer()
#    viewer.record(False)
#    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,0,255), yr.LINK_WIREBOX))
#    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer('model', cvr.VpModelRenderer(controlModel, (255,240,255), yr.POLYGON_LINE))
    viewer.doc.addRenderer('model2', cvr.VpModelRenderer(controlModel2, (255,240,255), yr.POLYGON_LINE))
    viewer.setMaxFrame(100)

    viewer.show()
    
    Fl.run()         
    def test_FramesRenderer_OrientationsRenderer():
        frame0 = mm.I_SE3()
        frame1 = mm.Rp2T(mm.exp(mm.v3(0, 1, 0), math.pi / 8.), (1, 0, 0))

        viewer = ysv.SimpleViewer()
        viewer.doc.addRenderer('frame0', FramesRenderer([frame0], (255, 0, 0)))
        viewer.doc.addRenderer('frame1', FramesRenderer([frame1], (255, 0, 0)))
        viewer.doc.addRenderer(
            'orientation0',
            OrientationsRenderer([mm.T2R(frame0)], [mm.T2p(frame0)],
                                 (0, 255, 0)))
        viewer.doc.addRenderer(
            'orientation1',
            OrientationsRenderer([mm.T2R(frame1)], [mm.T2p(frame1)],
                                 (0, 255, 0)))

        viewer.show()
        Fl.run()
Ejemplo n.º 8
0
def main():

    np.set_printoptions(precision=4, linewidth=200)
    
#    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()
        
    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    motionModel.recordVelByFiniteDiff()
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    
    elasticity = 20000
    damping = 2*(elasticity**.5)
    
    springBody1 = 1
    springBody2 = 2        
    springBody1Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
    springBody2Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))

    initialDist = mm.length(springBody1Pos - springBody2Pos)*1.
    node = mcfg.getNode(mit.RIGHT_METATARSAL_1)
    initialDist -= node.width#0.084
    v1 = (-node.width*0.5,0.0,node.length*0.4)
    v2 = (node.width*0.5,0.0,node.length*0.4)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)
     
    v1 = (-node.width*0.5,0.0,-node.length*0.4)
    v2 = (node.width*0.5,0.02,-node.length*0.4)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)
    
    elasticity2 = 10000
    damping2 = 2*(elasticity**.5)
    springBody3 = 5
    springBody4 = 6    
    springBody3Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody3]))
    springBody4Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody4]))

    initialDist2 = mm.length(springBody3Pos - springBody4Pos)*1.
    node2 = mcfg.getNode(mit.RIGHT_CALCANEUS_1)
    initialDist2 -= node2.width
    v3 = (-node2.width*0.5,0.0,-node2.length*0.4)
    v4 = (node2.width*0.5,0.0,-node2.length*0.4)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody3]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody4]), elasticity2, damping2, v4, v3, initialDist2)
    controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody3]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody4]), elasticity2, damping2, v3, v4, initialDist2)
    
    vpWorld.initialize()
    controlModel.initializeHybridDynamics()
    
    #ModelOffset = (1.5, -0.01, 0)
    ModelOffset = (1.5, 0.1, 0)
    controlModel.translateByOffset(ModelOffset)
    
    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()
        
    # parameter 
    Kt = config['Kt']; Dt = config['Dt'] # tracking gain
    Kl = config['Kl']; Dl = config['Dl'] # linear balance gain
    Kh = config['Kh']; Dh = config['Dh'] # angular balance gain
    Ks = config['Ks']; Ds = config['Ds']  # penalty force spring gain
    
    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']
        
    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w2 = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap2'])
    #w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL =  motion[0].skeleton.getJointIndex(config['supLink'])
    supR =  motion[0].skeleton.getJointIndex(config['supLink2'])
    rootB = motion[0].skeleton.getJointIndex(config['root'])

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex(config['const'])
    
    # jacobian 
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()
        
    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    ###############

    footPartNum = config['FootPartNum']
    
    indexFootL = [None]*footPartNum
    indexFootR = [None]*footPartNum
    jFootL = [None]*footPartNum
    dJFootL = [None]*footPartNum
    jFootR = [None]*footPartNum
    dJFootR = [None]*footPartNum
    jointMasksFootL = [None]*footPartNum
    jointMasksFootR = [None]*footPartNum
    
    jAngFootL = [None]*footPartNum
    dJAngFootL = [None]*footPartNum
    jAngFootR = [None]*footPartNum
    dJAngFootR = [None]*footPartNum

    for i in range(footPartNum) :
        jFootL[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootL[i] = jFootL[i].copy()
        jFootR[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootR[i] = jFootR[i].copy()
        
        jAngFootL[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootL[i] = jAngFootL[i].copy()
        jAngFootR[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootR[i] = jAngFootR[i].copy()
        
        indexFootL[i] = motion[0].skeleton.getJointIndex(config['FootLPart'][i])
        indexFootR[i] = motion[0].skeleton.getJointIndex(config['FootRPart'][i])
        jointMasksFootL[i] = [yjc.getLinkJointMask(motion[0].skeleton, indexFootL[i])]
        jointMasksFootR[i] = [yjc.getLinkJointMask(motion[0].skeleton, indexFootR[i])]       
   

    constJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [indexFootL[1], indexFootR[1]])]
    #constJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [indexFootL[0]])]
    #constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)
    
    '''
    maskArray = [foreSupLJointMasks, foreSupRJointMasks, rearSupLJointMasks, rearSupRJointMasks]
    parentArray = [supL, supR, supL, supR]
    effectorArray = [foreSupL, foreSupR, rearSupL, rearSupR]
    for j in range(4) :
        for i in range(len(foreSupLJointMasks)) :
            if i == parentArray[j] or i == effectorArray[j] :
                maskArray[j][0][i] = 1
            else :
                maskArray[j][0][i] = 0
    '''     
    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses) 
    dTO = ymt.make_dTO(len(linkMasses))
    
    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0,0,0, 0,0,0) #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0,0,0, 0,0,0]#R
    a_sup_2 = [0,0,0, 0,0,0, 0,0,0, 0,0,0]
    CP_old = [mm.v3(0.,0.,0.)]
        
    # penalty method 
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.]*len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)


    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM_ref = [None]
    rd_CM = [None]
    rd_CM_vec = [None]
    rd_CM_ref_vec = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    rd_footCenter_des = [None]
    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]
    
    rd_root = [None]
    
    rd_footL_vec = [None]
    rd_footR_vec = [None]
        
    rd_CMP = [None]
    
    rd_DesPosL = [None]
    rd_DesPosR = [None]
    
    rd_DesForePosL = [None]
    rd_DesForePosR = [None]
    rd_DesRearPosL = [None]
    rd_DesRearPosR = [None]

    rd_Joint = [None]
    rd_Joint2 = [None]
    rd_Joint3 = [None]
    rd_Joint4 = [None]
        
    rd_contactForces = [None]*1000
    rd_contactPositions = [None]*1000

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0,0,0]

    normalVector = [[0,2,0]]
    
    viewer = ysv.SimpleViewer()
#    viewer.record(False)
#    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer('motionModel', cvr.VpModelRenderer(motionModel, (150,150,255), yr.POLYGON_FILL))
    viewer.doc.addRenderer('controlModel', cvr.VpModelRenderer(controlModel, (255,240,255), yr.POLYGON_FILL))
    viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))    
    viewer.doc.addRenderer('rd_footCenter_des', yr.PointsRenderer(rd_footCenter_des, (150,0,150))    )
    #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))  
    #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
    #viewer.doc.addRenderer('rd_CM_plane', yr.PointsRenderer(rd_CM_plane, (255,255,0)))
    viewer.doc.addRenderer('rd_CM', yr.PointsRenderer(rd_CM_plane, (255,255,0)))
    #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (0,255,0)))
    #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (255,0,255)))
#    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
#    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
    viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP, (0,255,255), .001))

    viewer.doc.addRenderer('rd_exf_des', yr.ForcesRenderer(rd_exf_des, rd_root_des, (0,255,0), .009, 0.05))
        
    viewer.doc.addRenderer('rd_CMP', yr.PointsRenderer(rd_CMP, (0,0,255)))
    
    viewer.doc.addRenderer('rd_DesPosL', yr.PointsRenderer(rd_DesPosL, (0,0,255)))
    viewer.doc.addRenderer('rd_DesPosR', yr.PointsRenderer(rd_DesPosR, (0,100,255)))
    
    #viewer.doc.addRenderer('rd_DesForePosL', yr.PointsRenderer(rd_DesForePosL, (150,0,200)))
    #viewer.doc.addRenderer('rd_DesForePosR', yr.PointsRenderer(rd_DesForePosR, (150,0,250)))
    #viewer.doc.addRenderer('rd_DesRearPosL', yr.PointsRenderer(rd_DesRearPosL, (0,150,200)))
    #viewer.doc.addRenderer('rd_DesRearPosR', yr.PointsRenderer(rd_DesRearPosR, (0,150,250)))

    viewer.doc.addRenderer('softConstraint', yr.VectorsRenderer(rd_soft_const_vec, rd_CMP, (150,100,100), 3))
        
    viewer.doc.addRenderer('rd_footLVec', yr.VectorsRenderer(rd_footL_vec, rd_footCenterL, (255,0,0), 3))
    viewer.doc.addRenderer('rd_footRVec', yr.VectorsRenderer(rd_footR_vec, rd_footCenterR, (255,255,0), 3))

    #viewer.doc.addRenderer('rd_footCenter_ref', yr.PointsRenderer(rd_footCenter_ref))    
    #viewer.doc.addRenderer('rd_CM_plane_ref', yr.PointsRenderer(rd_CM_plane_ref, (255,255,0)))
        
    viewer.doc.addRenderer('rd_refNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter_ref, (255,0,0), 3))
    viewer.doc.addRenderer('rd_refCMVec', yr.VectorsRenderer(rd_CM_ref_vec, rd_footCenter_ref, (255,0,255), 3))
    
    viewer.doc.addRenderer('rd_curNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter, (255,0,0), 3))
    viewer.doc.addRenderer('rd_CMVec', yr.VectorsRenderer(rd_CM_vec, rd_footCenter, (255,0,255), 3))
        
    #viewer.doc.addRenderer('rd_contactForces', yr.ForcesRenderer(rd_contactForces, rd_contactPositions, (0,255,0), .009, 0.009))

    
    viewer.doc.addRenderer('rd_Joint', yr.PointsRenderer(rd_Joint, (255,0,0)))
    viewer.doc.addRenderer('rd_Joint2', yr.PointsRenderer(rd_Joint2, (0,255,0)))
    viewer.doc.addRenderer('rd_Joint3', yr.PointsRenderer(rd_Joint3, (0,0,255)))
    viewer.doc.addRenderer('rd_Joint4', yr.PointsRenderer(rd_Joint4, (255,255,0)))

    stage = STATIC_BALANCING

    contactRendererName = []
    
    for i in range (motion[0].skeleton.getJointNum()):
        print(i, motion[0].skeleton.getJointName(i))       

    def simulateCallback(frame):
        global g_initFlag
        global forceShowFrame
        global forceApplyFrame
        global JsysPre
        global JsupPreL
        global JsupPreR
        global JsupPre
        global softConstPoint
        global stage
        global contactRendererName

        motionModel.update(motion[frame])

        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, Bsc = viewer.GetParam()
        
        Dt = 2*(Kt**.5)
        Dk = 2*(Kk**.5)
        Dl = 2*(Kl**.5)
        Dh = 2*(Kh**.5)
        Dsc = 2*(Ksc**.5)
                
        if Bsc == 0.0 :
            viewer.doc.showRenderer('softConstraint', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('softConstraint', True)
            renderer1 = viewer.doc.getRenderer('softConstraint')
            renderer1.rc.setLineWidth(0.1+Bsc*3)
            viewer.motionViewWnd.update(1, viewer.doc)
                        
        # tracking
        th_r = motion.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt)
        ddth_c = controlModel.getDOFAccelerations()

        ype.flatten(ddth_des, ddth_des_flat)
        ype.flatten(dth, dth_flat)

        ype.flatten(ddth_c, ddth_c_flat)
        
        # jacobian                                 
        refFootL = motionModel.getBodyPositionGlobal(supL)        
        refFootR = motionModel.getBodyPositionGlobal(supR)
               
        positionFootL = [None]*footPartNum
        positionFootR = [None]*footPartNum
        for i in range(footPartNum):
            positionFootL[i] = controlModel.getBodyPositionGlobal(indexFootL[i])
            positionFootR[i] = controlModel.getBodyPositionGlobal(indexFootR[i])
        
        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()
        
        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        CM_plane = copy.copy(CM); CM_plane[1]=0.
        dCM_plane = copy.copy(dCM); dCM_plane[1]=0.
                
        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        CM_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        CM_plane_ref = copy.copy(CM_ref)
        CM_plane_ref[1] = 0.
        
        P = ymt.getPureInertiaMatrix(TO, linkMasses, linkPositions, CM, linkInertias)
        dP = ymt.getPureInertiaMatrixDerivative(dTO, linkMasses, linkVelocities, dCM, linkAngVelocities, linkInertias)

        yjc.computeJacobian2(Jsys, DOFs, jointPositions, jointAxeses, linkPositions, allLinkJointMasks)       
        yjc.computeJacobianDerivative2(dJsys, DOFs, jointPositions, jointAxeses, linkAngVelocities, linkPositions, allLinkJointMasks)
                
        yjc.computeJacobian2(jFootL[0], DOFs, jointPositions, jointAxeses, [positionFootL[0]], jointMasksFootL[0])
        yjc.computeJacobianDerivative2(dJFootL[0], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootL[0]], jointMasksFootL[0], False)
        
        yjc.computeJacobian2(jFootR[0], DOFs, jointPositions, jointAxeses, [positionFootR[0]], jointMasksFootR[0])
        yjc.computeJacobianDerivative2(dJFootR[0], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootR[0]], jointMasksFootR[0], False)
                
        yjc.computeAngJacobian2(jAngFootL[0], DOFs, jointPositions, jointAxeses, [positionFootL[0]], jointMasksFootL[0])
        yjc.computeAngJacobianDerivative2(dJAngFootL[0], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootL[0]], jointMasksFootL[0], False)
        
        yjc.computeAngJacobian2(jAngFootR[0], DOFs, jointPositions, jointAxeses, [positionFootR[0]], jointMasksFootR[0])
        yjc.computeAngJacobianDerivative2(dJAngFootR[0], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootR[0]], jointMasksFootR[0], False)
        
        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)

        for i in range(len(bodyIDsToCheck)) :
            controlModel.SetBodyColor(bodyIDsToCheck[i], 0, 0, 0)
        
        ##########################################
        
        for i in range(len(rd_contactPositions)):
            rd_contactPositions[i] = [0,0,0]
            rd_contactForces[i] = [0,0,0]

        for i in range(len(contactPositions)):
            rd_contactPositions[i] = np.copy(contactPositions[i])
            rd_contactForces[i] = np.copy(contactForces[i])
        '''
        if len(contactPositions) > 0:
            rd_contactPositions = np.copy(contactPositions)
            rd_contactForces = np.copy(contactForces)
            print("rd_contactPositions", rd_contactPositions)
            print("contactPositions", contactPositions)
        '''
        '''
        for i in range(len(contactRendererName)):
                viewer.doc.removeRenderer(contactRendererName[i])
                
        del contactRendererName[:]

        for i in range(len(contactPositions)):
            contactRendererName.append(str(i))
            #viewer.doc.addRenderer(str(i), yr.PointsRenderer([contactPositions[i]], (0,255,0)))
            viewer.doc.addRenderer(str(i), yr.ForcesRenderer([contactForces[i]], [contactPositions[i]], (0,255,0), .009, 0.009))


        viewer.motionViewWnd.update(1, viewer.doc)
        '''
        ##########################################


        contactFlagFootL = [0]*footPartNum
        contactFlagFootR = [0]*footPartNum

        partialDOFIndex = [22, 22]
        for i in range(len(bodyIDs)) :
            controlModel.SetBodyColor(bodyIDs[i], 255, 105, 105)
            index = controlModel.id2index(bodyIDs[i])
            for j in range(len(indexFootL)):
                if index == indexFootL[j]:
                    contactFlagFootL[j] = 1
                    if j != 0:
                        yjc.computePartialJacobian2(jFootL[j], DOFs, jointPositions, jointAxeses, [positionFootL[j]], jointMasksFootL[j], partialDOFIndex)
                        yjc.computePartialJacobianDerivative2(dJFootL[j], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootL[j]], jointMasksFootL[j], False, partialDOFIndex)
                    break
            for j in range(len(indexFootR)):
                if index == indexFootR[j]:
                    contactFlagFootR[j] = 1
                    if j != 0:
                        yjc.computePartialJacobian2(jFootR[j], DOFs, jointPositions, jointAxeses, [positionFootR[j]], jointMasksFootR[j], partialDOFIndex)
                        yjc.computePartialJacobianDerivative2(dJFootR[j], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootR[j]], jointMasksFootR[j], False, partialDOFIndex)
                    break
                

        for j in range(len(indexFootL)):
            yjc.computeAngJacobian2(jAngFootL[j], DOFs, jointPositions, jointAxeses, [positionFootL[j]], jointMasksFootL[j])
            yjc.computeAngJacobianDerivative2(dJAngFootL[j], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootL[j]], jointMasksFootL[j], False)            
            yjc.computeAngJacobian2(jAngFootR[j], DOFs, jointPositions, jointAxeses, [positionFootR[j]], jointMasksFootR[j])
            yjc.computeAngJacobianDerivative2(dJAngFootR[j], DOFs, jointPositions, jointAxeses, linkAngVelocities, [positionFootR[j]], jointMasksFootR[j], False)

        '''
        if footPartNum == 1:
             footCenterL = controlModel.getBodyPositionGlobal(supL)
             footCenterR = controlModel.getBodyPositionGlobal(supR)             
        else:
            if ((contactFlagFootL[3] == 1 or contactFlagFootL[4] == 1) and contactFlagFootL[0] == 0) or ((contactFlagFootR[3] == 1 or contactFlagFootR[4] == 1) and contactFlagFootR[0] == 0):
                r = 0.8
                footCenterL = (controlModel.getBodyPositionGlobal(supL)*r + controlModel.getBodyPositionGlobal(indexFootL[1])*(1.0-r))
                footCenterR = (controlModel.getBodyPositionGlobal(supR)*r + controlModel.getBodyPositionGlobal(indexFootR[1])*(1.0-r))
                #footCenterL = controlModel.getBodyPositionGlobal(indexFootL[1]) 
                #footCenterR = controlModel.getBodyPositionGlobal(indexFootR[1])                 
            else :
                #footCenterL = (controlModel.getBodyPositionGlobal(supL) + controlModel.getBodyPositionGlobal(indexFootL[1]))/2.0
                #footCenterR = (controlModel.getBodyPositionGlobal(supR) + controlModel.getBodyPositionGlobal(indexFootR[1]))/2.0
                #footCenterL = controlModel.getBodyPositionGlobal(indexFootL[1])                    
                #footCenterR = controlModel.getBodyPositionGlobal(indexFootR[1])
                r = 0.8
                footCenterL = (controlModel.getBodyPositionGlobal(indexFootL[1])*r + controlModel.getBodyPositionGlobal(indexFootL[3])*(1.0-r))
                footCenterR = (controlModel.getBodyPositionGlobal(indexFootR[1])*r + controlModel.getBodyPositionGlobal(indexFootR[3])*(1.0-r))
        '''
        
        '''
        if stage == POWERFUL_BALANCING:
            footCenterL = controlModel.getBodyPositionGlobal(indexFootL[1])        
            footCenterR = controlModel.getBodyPositionGlobal(indexFootR[1])
        else:
            footCenterL = (controlModel.getBodyPositionGlobal(indexFootL[1]) + controlModel.getBodyPositionGlobal(indexFootL[3]) )/2.0       
            footCenterR = (controlModel.getBodyPositionGlobal(indexFootR[1]) + controlModel.getBodyPositionGlobal(indexFootR[3]))/2.0
        '''
        '''
        p1 = controlModel.getBodyPositionGlobal(indexFootL[0])
        p2 = controlModel.getBodyPositionGlobal(indexFootR[0])
        p3 = controlModel.getBodyPositionGlobal(indexFootL[3])
        p4 = controlModel.getBodyPositionGlobal(indexFootR[3])
        print(frame, "supL", p1[1])
        print(frame, "supR", p2[1])
        print(frame, "calcL", p3[1])
        print(frame, "calcR", p4[1])        
        '''

        #footCenter = footCenterL + (footCenterR - footCenterL)/2.0
        #footCenter[1] = 0.     
        
        #
        '''
        if checkAll(contactFlagFootL, 0) == 1 and checkAll(contactFlagFootR, 0) == 1:
            footCenter = footCenter
        elif checkAll(contactFlagFootL, 0) == 1 :
            footCenter = footCenterR
        elif checkAll(contactFlagFootR, 0) == 1 :
            footCenter = footCenterL
        '''

        if footPartNum == 1:
            desFCL = (controlModel.getBodyPositionGlobal(supL))
            desFCR = (controlModel.getBodyPositionGlobal(supR))
        else :
            r = .4
            desFCL = (controlModel.getBodyPositionGlobal(indexFootL[1])*r + controlModel.getBodyPositionGlobal(indexFootL[3])*(1.0-r))#controlModel.getBodyPositionGlobal(indexFootL[1])
            desFCR = (controlModel.getBodyPositionGlobal(indexFootR[1])*r + controlModel.getBodyPositionGlobal(indexFootR[3])*(1.0-r))#controlModel.getBodyPositionGlobal(indexFootR[1])
        desFC = desFCL + (desFCR - desFCL)/2.0  
           
        if checkAll(contactFlagFootL, 0) == 1 and checkAll(contactFlagFootR, 0) == 1:
            desFC = desFC
        elif checkAll(contactFlagFootL, 0) == 1 :
            desFC = desFCR
        elif checkAll(contactFlagFootR, 0) == 1 :
            desFC = desFCL
           
        #if stage == MOTION_TRACKING:
        #    desFC = desFCL
        
        desFC[1] = 0
        rd_footCenter_des[0] = desFC.copy()
        curRelCMVec = CM_plane - desFC
        vecRatio = mm.length(curRelCMVec)*0.
        #print(frame, vecRatio)
        footCenter = desFC - curRelCMVec*(vecRatio)#/10.0

        footCenter_ref = refFootL + (refFootR - refFootL)/2.0
        #footCenter_ref[1] = 0.    
        footCenter[1] = 0.  

        
        vecRatio = mm.length(curRelCMVec)*0.
        softConstPointOffset = -curRelCMVec*(vecRatio)#/10.0
        #print(frame, vecRatio, softConstPointOffset)

        desForeSupLAcc = [0,0,0]
        desForeSupRAcc = [0,0,0]
                
        totalNormalForce = [0,0,0]    
        
        for i in range(len(contactForces)):
            totalNormalForce[0] += contactForces[i][0]
            totalNormalForce[1] += contactForces[i][1]
            totalNormalForce[2] += contactForces[i][2]
                                   
        #print((totalMass*mm.s2v(wcfg.gravity))[1])
        print("totalNormalForce=", totalNormalForce[1])
        print("F_Diff=", (totalMass*mm.s2v(wcfg.gravity))[1]+totalNormalForce[1])

        # linear momentum
        CM_ref_plane = footCenter
        dL_des_plane = Kl*totalMass*(CM_ref_plane - CM_plane) - Dl*totalMass*dCM_plane
    
        print("CM_Diff=",mm.length(CM_ref_plane - CM_plane))
        # angular momentum
        CP_ref = footCenter

        timeStep = 30.
        if CP_old[0]==None or CP==None:
            dCP = None
        else:
            dCP = (CP - CP_old[0])/(1/timeStep)
        CP_old[0] = CP            
        
        if CP!=None and dCP!=None:
            ddCP_des = Kh*(CP_ref - CP) - Dh*(dCP)
            CP_des = CP + dCP*(1/timeStep) + .5*ddCP_des*((1/timeStep)**2)
            #dH_des = np.cross((CP_des - CM), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))            
            dH_des = np.cross((CP_des - CM_plane), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))
            print("CP_Diff=",mm.length(CP_des - CP))
        else:
            dH_des = None
                        
 
        # momentum matrix
        RS = np.dot(P, Jsys)
        R, S = np.vsplit(RS, 2)
        
        rs = np.dot((np.dot(dP, Jsys) + np.dot(P, dJsys)), dth_flat)
        r_bias, s_bias = np.hsplit(rs, 2)


        ##############################
        # soft point constraint

        #####################################################
        P_cur = controlModel.getBodyPositionGlobal(constBody)
        constBodyVec = P_cur - footCenter
        softConstPoint = [footCenter[0]+softConstPointOffset[0], mm.length(constBodyVec), footCenter[2]+softConstPointOffset[2]]
        #####################################################

        P_des = softConstPoint
        #P_cur = controlModel.getBodyPositionGlobal(constBody)
        dP_des = [0, 0, 0]
        dP_cur = controlModel.getBodyVelocityGlobal(constBody)
        ddP_des1 = Ksc*(-(P_des - P_cur)) - Dsc*(-(dP_cur - dP_des))

        r = -(P_des - P_cur)
        I = np.vstack(([1,0,0],[0,1,0],[0,0,1]))
        Z = np.hstack((I, mm.getCrossMatrixForm(-r)))
          
        yjc.computeJacobian2(Jconst, DOFs, jointPositions, jointAxeses, [P_cur], constJointMasks)
        JL, JA = np.vsplit(Jconst, 2)
        Q1 = np.dot(Z, Jconst)
                  
        q1 = np.dot(JA, dth_flat)
        q2 = np.dot(mm.getCrossMatrixForm(q1), np.dot(mm.getCrossMatrixForm(q1), r))
        
        yjc.computeJacobianDerivative2(dJconst, DOFs, jointPositions, jointAxeses, linkAngVelocities, [P_cur], constJointMasks, False)
        q_bias1 = np.dot(np.dot(Z, dJconst), dth_flat) + q2
        
        ##############################
        
         
        flagContact = True
        if dH_des==None or np.any(np.isnan(dH_des)) == True:
            flagContact = False 
            viewer.doc.showRenderer('rd_grf_des', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('rd_grf_des', True)
            viewer.motionViewWnd.update(1, viewer.doc)
        '''
        0 : initial
        1 : contact
        2 : fly
        3 : landing
        '''

        #MOTION = FORWARD_JUMP
        if mit.MOTION == mit.FORWARD_JUMP :
            frame_index = [136, 100]
            #frame_index = [100000, 100000]
        elif mit.MOTION == mit.TAEKWONDO:
            frame_index = [130, 100]
            #frame_index = [100000, 100000]
        elif mit.MOTION == mit.TAEKWONDO2:
            frame_index = [130+40, 100]
        elif mit.MOTION == mit.WALK:
            frame_index = [10000, 60]
        else :
            frame_index = [1000000, 1000000]
        
        #MOTION = TAEKWONDO 
        #frame_index = [135, 100]

        '''
        if frame > 300 :
            if stage != DYNAMIC_BALANCING:
                print("#", frame,"-DYNAMIC_BALANCING")
            stage = DYNAMIC_BALANCING
            Kk = Kk*1
            Dk = 2*(Kk**.5)        
        '''
        if frame > frame_index[0] :
            if stage != POWERFUL_BALANCING:
                print("#", frame,"-POWERFUL_BALANCING")
            stage = POWERFUL_BALANCING
            Kk = Kk*2
            Dk = 2*(Kk**.5)            
        elif frame > frame_index[1]:
            if stage != MOTION_TRACKING:
                print("#", frame,"-MOTION_TRACKING")
            stage = MOTION_TRACKING

        trackingW = w

        #if checkAll(contactFlagFootR, 0) != 1 :
        if stage == MOTION_TRACKING:
            trackingW = w2
            #stage = POWERFUL_BALANCING
            Bt = Bt*2

        # optimization
                
        mot.addTrackingTerms(problem, totalDOF, Bt, trackingW, ddth_des_flat)
                
        mot.addSoftPointConstraintTerms(problem, totalDOF, Bsc, ddP_des1, Q1, q_bias1)

        if flagContact == True:
            if stage != MOTION_TRACKING+10:
                mot.addLinearTerms(problem, totalDOF, Bl, dL_des_plane, R, r_bias) 
                mot.addAngularTerms(problem, totalDOF, Bh, dH_des, S, s_bias)
            
        a_sup_2 = [None]
        Jsup_2 = [None]
        dJsup_2 = [None]

        ##############################
        # Hard constraint        
        if stage != MOTION_TRACKING:
            Kk2 = Kk * 2.0
        else :
            Kk2 = Kk * 1.5
                    
        Dk2 = 2*(Kk2**.5)

        '''
        desLinearAccL, desPosL = getDesFootLinearAcc(motionModel, controlModel, supL, ModelOffset, CM_ref, CM, Kk2, Dk2) 
        desLinearAccR, desPosR = getDesFootLinearAcc(motionModel, controlModel, supR, ModelOffset, CM_ref, CM, Kk2, Dk2) 

        desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, supL, Kk2, Dk2)
        desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, supR, Kk2, Dk2)
        '''
        
        if stage != MOTION_TRACKING:
            idx = 0 #LEFT/RIGHT_TOES 
                        
            if stage != MOTION_TRACKING:
                desLinearAccL, desPosL = getDesFootLinearAcc(motionModel, controlModel, indexFootL[idx], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.14)#0.076) 
                desLinearAccR, desPosR = getDesFootLinearAcc(motionModel, controlModel, indexFootR[idx], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.14) 

                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2, [0,0,-1], [0,1,1.5])
                desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, indexFootR[idx], Kk2, Dk2, [0,0,-1], [0,1,1.5])
        
                a_sup_2 = np.hstack(( np.hstack((desLinearAccL, desAngularAccL)), np.hstack((desLinearAccR, desAngularAccR)) ))
 
                Jsup_2 = np.vstack((jFootL[idx], jFootR[idx]))
                dJsup_2 = np.vstack((dJFootL[idx], dJFootR[idx]))   
            else:
                desLinearAccL, desPosL = getDesFootLinearAcc(motionModel, controlModel, indexFootL[idx], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.040) 
                desLinearAccR, desPosR = getDesFootLinearAcc(motionModel, controlModel, indexFootR[idx], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.040) 

                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2)
                    
                a_sup_2 = np.hstack((desLinearAccL, desAngularAccL))
 
                Jsup_2 = jFootL[idx] 
                dJsup_2 = dJFootL[idx]
            
            rd_DesPosL[0] = desPosL.copy()
            rd_DesPosR[0] = desPosR.copy()
        else:
            if footPartNum != 5:
                idx = 0
                desLinearAccL, desPosL = getDesFootLinearAcc(motionModel, controlModel, indexFootL[idx], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.045) 
                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2)
        
                a_sup_2 = np.hstack(( desLinearAccL, desAngularAccL))
 
                Jsup_2 = (jFootL[idx])
                dJsup_2 = (dJFootL[idx])  
                '''
                idx = 4
                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2)
        
                a_sup_2 = np.hstack(( a_sup_2, desAngularAccL))
 
                Jsup_2 = np.vstack(( Jsup_2, jAngFootL[idx]))
                dJsup_2 = np.vstack(( dJsup_2, dJAngFootL[idx]))
                '''
                '''                
                idx = 1
                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2)        
                a_sup_2 = np.hstack(( a_sup_2, desAngularAccL))
 
                Jsup_2 = np.vstack(( Jsup_2, jAngFootL[idx]))
                dJsup_2 = np.vstack(( dJsup_2, dJAngFootL[idx]))
                '''
            else:                
                idx = 0
                desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[idx], Kk2, Dk2)
                desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, indexFootR[idx], Kk2, Dk2)
        
                a_sup_2 = np.hstack(( desAngularAccL, desAngularAccR ))
 
                Jsup_2 = np.vstack((jAngFootL[idx], jAngFootR[idx]))
                dJsup_2 = np.vstack((dJAngFootL[idx], dJAngFootR[idx]))             
                       

        ##############################
        
        ##############################
        # Additional constraint          

        if stage != MOTION_TRACKING+10:
            #Kk2 = Kk * 2.5
            Kk2 = Kk * 2.5
            Dk2 = 2*(Kk2**.5)
            desForePosL = [0,0,0]
            desForePosR = [0,0,0]
            desRearPosL = [0,0,0]
            desRearPosR = [0,0,0]
            
            for i in range(1, footPartNum) :
                if stage != MOTION_TRACKING:
                    axis = [0,1,0]
                    desAng = [0,1,0]
                    desY = 0.04
                    if i == 1 or i == 2:
                        desAng = [0,1,1.2]
                        desY = 0.076
                    if contactFlagFootL[i] == 1:
                        desLinearAccL, desForePosL = getDesFootLinearAcc(motionModel, controlModel, indexFootL[i], ModelOffset, CM_ref, CM, Kk2, Dk2, desY) 
                        desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[i], Kk2, Dk2, axis, desAng)
                        a_sup_2 = np.hstack(( a_sup_2, np.hstack((desLinearAccL, desAngularAccL)) ))
                        Jsup_2 = np.vstack(( Jsup_2, jFootL[i] ))
                        dJsup_2 = np.vstack(( dJsup_2, dJFootL[i] ))                
                    if contactFlagFootR[i] == 1:
                        desLinearAccR, desForePosR = getDesFootLinearAcc(motionModel, controlModel, indexFootR[i], ModelOffset, CM_ref, CM, Kk2, Dk2, desY) 
                        desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, indexFootR[i], Kk2, Dk2, axis, desAng)
                        a_sup_2 = np.hstack(( a_sup_2, np.hstack((desLinearAccR, desAngularAccR)) ))            
                        Jsup_2 = np.vstack(( Jsup_2, jFootR[i] ))
                        dJsup_2 = np.vstack(( dJsup_2, dJFootR[i] ))
                else:
                    if contactFlagFootL[i] == 1:
                        desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[i], Kk2, Dk2)
                        a_sup_2 = np.hstack(( a_sup_2, desAngularAccL ))
                        Jsup_2 = np.vstack(( Jsup_2, jAngFootL[i] ))
                        dJsup_2 = np.vstack(( dJsup_2, dJAngFootL[i] ))                
                    if contactFlagFootR[i] == 1:
                        desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, indexFootR[i], Kk2, Dk2)
                        a_sup_2 = np.hstack(( a_sup_2, desAngularAccR ))            
                        Jsup_2 = np.vstack(( Jsup_2, jAngFootR[i] ))
                        dJsup_2 = np.vstack(( dJsup_2, dJAngFootR[i] ))

            '''
            for i in range(1, footPartNum) :
                if contactFlagFootL[i] == 1:
                    desLinearAccL, desForePosL = getDesFootLinearAcc(motionModel, controlModel, indexFootL[i], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.034) 
                    desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, indexFootL[i], Kk2, Dk2)
                    a_sup_2 = np.hstack(( a_sup_2, np.hstack((desLinearAccL, desAngularAccL)) ))
                    Jsup_2 = np.vstack(( Jsup_2, jFootL[i] ))
                    dJsup_2 = np.vstack(( dJsup_2, dJFootL[i] ))                
                if contactFlagFootR[i] == 1:
                    desLinearAccR, desForePosR = getDesFootLinearAcc(motionModel, controlModel, indexFootR[i], ModelOffset, CM_ref, CM, Kk2, Dk2, 0.034) 
                    desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, indexFootR[i], Kk2, Dk2)
                    a_sup_2 = np.hstack(( a_sup_2, np.hstack((desLinearAccR, desAngularAccR)) ))            
                    Jsup_2 = np.vstack(( Jsup_2, jFootR[i] ))
                    dJsup_2 = np.vstack(( dJsup_2, dJFootR[i] ))
            '''
            rd_DesForePosL[0] = desForePosL
            rd_DesForePosR[0] = desForePosR
            rd_DesRearPosL[0] = desRearPosL
            rd_DesRearPosR[0] = desRearPosR
        ##############################
        

        mot.setConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)
        

        r = problem.solve()
        problem.clear()
        ype.nested(r['x'], ddth_sol)
                      
        rootPos[0] = controlModel.getBodyPositionGlobal(selectedBody)
        localPos = [[0, 0, 0]]   

        rd_Joint[0] = controlModel.getJointPositionGlobal(motion[0].skeleton.getJointIndex('LeftMetatarsal_1'))
        rd_Joint2[0] = controlModel.getJointPositionGlobal(motion[0].skeleton.getJointIndex('LeftMetatarsal_3'))
        rd_Joint3[0] = controlModel.getJointPositionGlobal(motion[0].skeleton.getJointIndex('LeftPhalange_1'))
        rd_Joint4[0] = controlModel.getJointPositionGlobal(motion[0].skeleton.getJointIndex('LeftPhalange_3'))
                
        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
     
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals, contactForces)                      
            
            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0 or extraForce[0][2] != 0) :
                forceApplyFrame += 1
                #vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                controlModel.applyBodyForceGlobal(selectedBody, extraForce[0])
                applyedExtraForce[0] = extraForce[0]
            
            if forceApplyFrame*wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0            

            controlModel.setDOFAccelerations(ddth_sol)
            
            controlModel.solveHybridDynamics()
            '''
            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0 or extraForce[0][2] != 0) :
                forceApplyFrame += 1
                vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                applyedExtraForce[0] = extraForce[0]
            
            if forceApplyFrame*wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0            
            '''
            vpWorld.step()                    
            
        # rendering        

        rd_footCenter[0] = footCenter
        
        rd_CM[0] = CM.copy()
        
        rd_CM_plane[0] = CM_plane.copy()
        
        rd_footCenter_ref[0] = footCenter_ref
        rd_CM_plane_ref[0] = CM_ref.copy()
        rd_CM_ref[0] = CM_ref.copy()
        rd_CM_ref_vec[0] = (CM_ref - footCenter_ref)*3.
        rd_CM_vec[0] = (CM - footCenter)*3

        #rd_CM_plane[0][1] = 0.
        
        if CP!=None and dCP!=None:
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des
        
        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des
        
        rd_grf_des[0] = totalNormalForce# - totalMass*mm.s2v(wcfg.gravity)#dL_des_plane - totalMass*mm.s2v(wcfg.gravity)
                
        rd_exf_des[0] = applyedExtraForce[0]
        rd_root_des[0] = rootPos[0]

        rd_CMP[0] = softConstPoint

        rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(constBody)-softConstPoint


        #indexL = motion[0].skeleton.getJointIndex('Hips')
        #indexR = motion[0].skeleton.getJointIndex('Spine1')
        indexL = indexFootL[0]        
        indexR = indexFootR[0]

        curAng = [controlModel.getBodyOrientationGlobal(indexL)]                        
        curAngY = np.dot(curAng, np.array([0,0,1]))

        rd_footL_vec[0] = np.copy(curAngY[0])
        rd_footCenterL[0] = controlModel.getBodyPositionGlobal(indexL)
                
        curAng = [controlModel.getBodyOrientationGlobal(indexR)]                        
        curAngY = np.dot(curAng, np.array([0,0,1]))

        rd_footR_vec[0] = np.copy(curAngY[0])
        rd_footCenterR[0] = controlModel.getBodyPositionGlobal(indexR)
        
        if (forceApplyFrame == 0) :
            applyedExtraForce[0] = [0, 0, 0]

    viewer.setSimulateCallback(simulateCallback)
    
    viewer.startTimer(1/60.)
    viewer.show()
    
    Fl.run()
Ejemplo n.º 9
0
def create_biped():
    # motion
    #motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        motionName = 'wd2_stand.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'

    #motionName = 'ww13_41_V001.bvh'
    motion = yf.readBvhFile(motionName, .01)

    yme.removeJoint(motion, HEAD, False)
    yme.removeJoint(motion, RIGHT_SHOULDER, False)
    yme.removeJoint(motion, LEFT_SHOULDER, False)

    if FOOT_PART_NUM == 1:
        yme.removeJoint(motion, RIGHT_TOES_END, False)
        yme.removeJoint(motion, LEFT_TOES_END, False)

    yme.removeJoint(motion, RIGHT_HAND_END, False)
    yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1, 0, 0), .01), False)

    yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(2.5, -0.0, .3), -.5),
                         False)
    yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(2.5, 0.0, -.3), -.5),
                         False)

    if MOTION == FORWARD_JUMP:
        yme.rotateJointLocal(motion, LEFT_UP_LEG,
                             mm.exp(mm.v3(0.0, .0, 1.), .08), False)
        yme.rotateJointLocal(motion, LEFT_LEG, mm.exp(mm.v3(0.0, 1.0, 0.),
                                                      -.2), False)

    if FOOT_PART_NUM > 1:
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_TARSUS)
        yme.addJoint(motion, RIGHT_TARSUS, 'RIGHT_Dummy1')
        yme.addJoint(motion, LEFT_FOOT, LEFT_TARSUS)
        yme.addJoint(motion, LEFT_TARSUS, 'LEFT_Dummy1')
        yme.rotateJointLocal(motion, LEFT_TOES, mm.exp(mm.v3(1., 0.0, 0.0),
                                                       .45), False)
        yme.rotateJointLocal(motion, RIGHT_TOES,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_TARSUS,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)
        yme.rotateJointLocal(motion, RIGHT_TARSUS,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)

    if FOOT_PART_NUM == 5:
        yme.addJoint(motion, LEFT_FOOT, LEFT_FOOT_SIDE_L)
        yme.addJoint(motion, LEFT_FOOT_SIDE_L, 'LEFT_Dummy2')
        yme.addJoint(motion, LEFT_FOOT, LEFT_FOOT_SIDE_R)
        yme.addJoint(motion, LEFT_FOOT_SIDE_R, 'LEFT_Dummy2')
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_FOOT_SIDE_L)
        yme.addJoint(motion, RIGHT_FOOT_SIDE_L, 'RIGHT_Dummy2')
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_FOOT_SIDE_R)
        yme.addJoint(motion, RIGHT_FOOT_SIDE_R, 'RIGHT_Dummy2')
        yme.rotateJointLocal(motion, LEFT_FOOT_SIDE_L,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_FOOT_SIDE_R,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, RIGHT_FOOT_SIDE_L,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, RIGHT_FOOT_SIDE_R,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    ## Taekwondo turning-kick
    #motion = motion[108:-1]
    #motion = motion[108:109]

    motion[0:0] = [motion[0]] * 100
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    #node.length = .2 ####

    if FOOT_PART_NUM == 1:
        length1 = .25
        width1 = .2
        mass1 = 4.
    elif FOOT_PART_NUM == 3:
        length1 = .1
        width1 = .2
        mass1 = 1.5
        length2 = .1
        width2 = .2
        mass2 = 1.5
    elif FOOT_PART_NUM == 5:
        length1 = .1
        width1 = .065
        mass1 = .5
        length2 = .1
        width2 = .2
        mass2 = 1.5

    node = mcfg.getNode(RIGHT_FOOT)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_FOOT)
    node.length = length1
    node.width = width1
    node.mass = mass1

    if FOOT_PART_NUM == 5:
        node = mcfg.getNode(LEFT_FOOT_SIDE_L)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0.07, 0.0, 0.015)
        node = mcfg.getNode(LEFT_FOOT_SIDE_R)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (-0.07, 0.0, 0.015)

        node = mcfg.getNode(RIGHT_FOOT_SIDE_L)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0.07, 0.0, 0.015)
        node = mcfg.getNode(RIGHT_FOOT_SIDE_R)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (-0.07, 0.0, 0.015)

    if FOOT_PART_NUM > 1:
        node = mcfg.getNode(LEFT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.02)

        node = mcfg.getNode(RIGHT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.02)

        node = mcfg.getNode(LEFT_TARSUS)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.08)

        node = mcfg.getNode(RIGHT_TARSUS)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.08)

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 30
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    if FOOT_PART_NUM == 1:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 1.,
            LEFT_FOOT: 1.,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.
        }
    elif FOOT_PART_NUM == 3:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .3,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .3,
            LEFT_LEG: .3,
            LEFT_TOES: .3,
            RIGHT_TOES: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.5,
            LEFT_FOOT: 2.5,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_TOES: .3,
            RIGHT_TOES: .3
        }
    elif FOOT_PART_NUM == 5:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3,
            LEFT_TOES: .3,
            RIGHT_TOES: .3,
            LEFT_TARSUS: .3,
            RIGHT_TARSUS: .3,
            LEFT_FOOT_SIDE_L: .3,
            LEFT_FOOT_SIDE_R: .3,
            RIGHT_FOOT_SIDE_L: .3,
            RIGHT_FOOT_SIDE_R: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.5,
            LEFT_FOOT: 2.5,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_TOES: .3,
            RIGHT_TOES: .3,
            LEFT_TARSUS: .3,
            RIGHT_TARSUS: .3,
            LEFT_FOOT_SIDE_L: .3,
            LEFT_FOOT_SIDE_R: .3,
            RIGHT_FOOT_SIDE_L: .3,
            RIGHT_FOOT_SIDE_R: .3
        }

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    #config['end'] = 'HIP'
    config['end'] = SPINE1
    config['const'] = HIP
    config['root'] = HIP

    config['FootPartNum'] = FOOT_PART_NUM
    config['FootLPart'] = [
        LEFT_FOOT, LEFT_TOES, LEFT_TARSUS, LEFT_FOOT_SIDE_L, LEFT_FOOT_SIDE_R
    ]
    config['FootRPart'] = [
        RIGHT_FOOT, RIGHT_TOES, RIGHT_TARSUS, RIGHT_FOOT_SIDE_L,
        RIGHT_FOOT_SIDE_R
    ]

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 10
0
def main():

    np.set_printoptions(precision=4, linewidth=200)

    #    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()
    mcfg_motion = mit.normal_mcfg()

    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    motionModel.recordVelByFiniteDiff()

    motionOriModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)

    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)

    footPartNum = config['FootPartNum']

    if footPartNum > 1:
        elasticity = 2000
        damping = 2 * (elasticity**.5)

        springBody1 = 5
        springBody2 = 6
        springBody1Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        springBody2Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))

        initialDist = mm.length(springBody1Pos - springBody2Pos) * 1.
        node = mcfg.getNode(mit.LEFT_PHALANGE_1)
        initialDist -= node.width  #0.084
        v1 = (-node.width * 0.5, 0.0, node.length * 0.4)
        v2 = (node.width * 0.5, 0.0, node.length * 0.4)
        controlModel.setSpring(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]),
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]),
            elasticity, damping, v2, v1, initialDist)
        controlModel.setSpring(
            motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]),
            motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]),
            elasticity, damping, v1, v2, initialDist)

        #elasticity = 10
        #damping = 2*(elasticity**.5)
        #springBody1 = 3
        #springBody2 = 4
        #node = mcfg.getNode(mit.LEFT_PHALANGE_1)
        #springBody1Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        #springBody2Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))
        #initialDist = mm.length(springBody1Pos - springBody2Pos)*1.
        #initialDist -= node.width#0.084
        #v1 = (-node.width*0.5,0.0,-node.length*0.4)
        #v2 = (node.width*0.5,0.0,-node.length*0.4)
        ##controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
        ##controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)

    vpWorld.initialize()
    controlModel.initializeHybridDynamics()

    #ModelOffset = (1.5, -0.01, 0)
    ModelOffset = (1.5, 0.04, 0)
    controlModel.translateByOffset(ModelOffset)

    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()

    # parameter
    Kt = config['Kt']
    Dt = config['Dt']  # tracking gain
    Kl = config['Kl']
    Dl = config['Dl']  # linear balance gain
    Kh = config['Kh']
    Dh = config['Dh']  # angular balance gain
    Ks = config['Ks']
    Ds = config['Ds']  # penalty force spring gain

    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']

    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w2 = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap2'])
    #w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL = motion[0].skeleton.getJointIndex(config['supLink'])
    supR = motion[0].skeleton.getJointIndex(config['supLink2'])
    rootB = motion[0].skeleton.getJointIndex(config['root'])

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex(config['const'])

    # jacobian
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys_IK = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()

    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    Jcom = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcom = Jcom.copy()

    JcomAng = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcomAng = JcomAng.copy()

    ###############

    jFootL_IK = [None] * footPartNum
    jFootR_IK = [None] * footPartNum

    indexFootL = [None] * footPartNum
    indexFootR = [None] * footPartNum
    jFootL = [None] * footPartNum
    dJFootL = [None] * footPartNum
    jFootR = [None] * footPartNum
    dJFootR = [None] * footPartNum
    jointMasksFootL = [None] * footPartNum
    jointMasksFootR = [None] * footPartNum

    for i in range(footPartNum):
        jFootL[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootL[i] = jFootL[i].copy()
        jFootR[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootR[i] = jFootR[i].copy()

        indexFootL[i] = motion[0].skeleton.getJointIndex(
            config['FootLPart'][i])
        indexFootR[i] = motion[0].skeleton.getJointIndex(
            config['FootRPart'][i])

        jointMasksFootL[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootL[i])
        ]
        jointMasksFootR[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootR[i])
        ]

    constJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton,
                              [indexFootL[0], indexFootR[0]])
    ]
    #constJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [indexFootL[0]])]
    #constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)

    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks = [
        yjc.getLinkJointMask(motion[0].skeleton, selectedBody)
    ]
    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks[0][0] = 0
    #comUpperJointMasks[0][1] = 1
    #comUpperJointMasks[0][10] = 1
    comUpperJointMasks[0][2] = 1
    comUpperJointMasks[0][11] = 1

    #print(comUpperJointMasks)

    comLowerJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton, [
            motion[0].skeleton.getJointIndex('LeftLeg'),
            motion[0].skeleton.getJointIndex('RightLeg')
        ])
    ]
    '''
    maskArray = [foreSupLJointMasks, foreSupRJointMasks, rearSupLJointMasks, rearSupRJointMasks]
    parentArray = [supL, supR, supL, supR]
    effectorArray = [foreSupL, foreSupR, rearSupL, rearSupR]
    for j in range(4) :
        for i in range(len(foreSupLJointMasks)) :
            if i == parentArray[j] or i == effectorArray[j] :
                maskArray[j][0][i] = 1
            else :
                maskArray[j][0][i] = 0
    '''
    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses)
    dTO = ymt.make_dTO(len(linkMasses))

    # optimization
    qps = hqp.QPSimulator()
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0, 0, 0, 0, 0, 0)  #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0, 0, 0, 0, 0, 0]  #R
    a_sup_2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    CP_old = [mm.v3(0., 0., 0.)]

    # penalty method
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.] * len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    dth_IK = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)

    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM_ref = [None]
    rd_CM_des = [None]
    rd_CM = [None]
    rd_CM_vec = [None]
    rd_CM_ref_vec = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    rd_footCenter_des = [None]
    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]

    rd_root = [None]

    rd_footL_vec = [None]
    rd_footR_vec = [None]

    rd_CMP = [None]

    rd_DesPosL = [None]
    rd_DesPosR = [None]

    rd_DesForePosL = [None]
    rd_DesForePosR = [None]
    rd_DesRearPosL = [None]
    rd_DesRearPosR = [None]

    rd_Joint = [None]
    rd_Joint2 = [None]
    rd_Joint3 = [None]
    rd_Joint4 = [None]
    rd_desPoints = [None]

    #rd_contactForces = [None]*10000
    #rd_contactPositions = [None]*10000
    rd_virtualForce = [None]

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0, 0, 0]

    normalVector = [[0, 2, 0]]

    if MULTI_VIEWER:
        viewer = ymv.MultiViewer(800, 655)
        #viewer = ymv.MultiViewer(1600, 1255)
        viewer.setRenderers1([
            cvr.VpModelRenderer(motionModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])
        viewer.setRenderers2([
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])

    else:
        viewer = ysv.SimpleViewer()
        #    viewer.record(False)
        #    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
        viewer.doc.addObject('motion', motion)
        viewer.doc.addRenderer(
            'motionModel',
            cvr.VpModelRenderer(motionModel, (100, 100, 100),
                                yr.POLYGON_FILL))  #(150,150,255)
        viewer.doc.addRenderer(
            'controlModel',
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR,
                                yr.POLYGON_FILL))
        #viewer.doc.addRenderer('controlModel', cvr.VpModelRenderer(controlModel, CHARACTER_COLOR, yr.POLYGON_LINE))
        #viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))
        #viewer.doc.addRenderer('rd_footCenter_des', yr.PointsRenderer(rd_footCenter_des, (150,0,150))    )
        #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))
        #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
        viewer.doc.addRenderer('rd_CM_plane',
                               yr.PointsRenderer(rd_CM_plane, (255, 255, 0)))
        viewer.doc.addRenderer('rd_CM',
                               yr.PointsRenderer(rd_CM, (255, 0, 255)))
        viewer.doc.addRenderer('rd_CM_des',
                               yr.PointsRenderer(rd_CM_des, (64, 64, 255)))
        viewer.doc.addRenderer(
            'rd_CM_vec',
            yr.VectorsRenderer(rd_CM_vec, rd_CM_plane, (255, 0, 0), 3))
        #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (0,255,0)))
        viewer.doc.addRenderer('rd_CP_des',
                               yr.PointsRenderer(rd_CP_des, (255, 0, 128)))
        #    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
        #    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
        #viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP, (0,255,255), .001))

        viewer.doc.addRenderer(
            'rd_exf_des',
            yr.ForcesRenderer(rd_exf_des, rd_root_des, (0, 255, 0), .009,
                              0.04))

        #viewer.doc.addRenderer('rd_CMP', yr.PointsRenderer(rd_CMP, (0,0,255)))

        #viewer.doc.addRenderer('rd_DesPosL', yr.PointsRenderer(rd_DesPosL, (0,0,255)))
        #viewer.doc.addRenderer('rd_DesPosR', yr.PointsRenderer(rd_DesPosR, (0,100,255)))

        #viewer.doc.addRenderer('rd_DesForePosL', yr.PointsRenderer(rd_DesForePosL, (150,0,200)))
        #viewer.doc.addRenderer('rd_DesForePosR', yr.PointsRenderer(rd_DesForePosR, (150,0,250)))
        #viewer.doc.addRenderer('rd_DesRearPosL', yr.PointsRenderer(rd_DesRearPosL, (0,150,200)))
        #viewer.doc.addRenderer('rd_DesRearPosR', yr.PointsRenderer(rd_DesRearPosR, (0,150,250)))

        #viewer.doc.addRenderer('softConstraint', yr.VectorsRenderer(rd_soft_const_vec, rd_CMP, (150,100,100), 3))

        #viewer.doc.addRenderer('rd_footLVec', yr.VectorsRenderer(rd_footL_vec, rd_footCenterL, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_footRVec', yr.VectorsRenderer(rd_footR_vec, rd_footCenterR, (255,255,0), 3))

        #viewer.doc.addRenderer('rd_footCenter_ref', yr.PointsRenderer(rd_footCenter_ref))
        #viewer.doc.addRenderer('rd_CM_plane_ref', yr.PointsRenderer(rd_CM_plane_ref, (255,255,0)))

        #viewer.doc.addRenderer('rd_refNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter_ref, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_refCMVec', yr.VectorsRenderer(rd_CM_ref_vec, rd_footCenter_ref, (255,0,255), 3))

        #viewer.doc.addRenderer('rd_curNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_CMVec', yr.VectorsRenderer(rd_CM_vec, rd_footCenter, (255,0,255), 3))

        #viewer.doc.addRenderer('rd_contactForces', yr.ForcesRenderer(rd_contactForces, rd_contactPositions, (0,255,0), .009, 0.009))

        #viewer.doc.addRenderer('rd_virtualForce', yr.ForcesRenderer(rd_virtualForce, rd_CM, (50,255,0), 0.5, 0.02))

        #viewer.doc.addRenderer('rd_Joint', yr.PointsRenderer(rd_Joint, (255,0,0)))
        #viewer.doc.addRenderer('rd_Joint2', yr.PointsRenderer(rd_Joint2, (0,255,0)))
        #viewer.doc.addRenderer('rd_Joint3', yr.PointsRenderer(rd_Joint3, (0,0,255)))
        #viewer.doc.addRenderer('rd_Joint4', yr.PointsRenderer(rd_Joint4, (255,255,0)))

        viewer.doc.addRenderer('rd_desPoints',
                               yr.PointsRenderer(rd_desPoints, (255, 0, 0)))

    stage = STATIC_BALANCING

    contactRendererName = []

    for i in range(motion[0].skeleton.getJointNum()):
        print(i, motion[0].skeleton.getJointName(i))

    desCOMOffset = 0.0

    pt = [0.]

    timeReport = [0.] * 7

    viewer.objectInfoWnd.comOffsetY.value(-0.05)
    viewer.objectInfoWnd.comOffsetZ.value(0.00)

    viewer.objectInfoWnd.begin()
    viewer.objectInfoWnd.Bc = Fl_Value_Input(100, 450, 40, 10, 'Bc')
    viewer.objectInfoWnd.Bc.value(0.1)

    viewer.objectInfoWnd.ankleAngleX = Fl_Value_Input(50, 510, 40, 10,
                                                      'Ankle X')
    viewer.objectInfoWnd.ankleAngleX.value(0)
    viewer.objectInfoWnd.ankleAngleY = Fl_Value_Input(110, 510, 40, 10, 'Y')
    viewer.objectInfoWnd.ankleAngleY.value(1)
    viewer.objectInfoWnd.ankleAngleZ = Fl_Value_Input(170, 510, 40, 10, 'Z')
    viewer.objectInfoWnd.ankleAngleZ.value(0)

    viewer.objectInfoWnd.end()
    viewer.objectInfoWnd.labelKt.value(50)
    viewer.objectInfoWnd.labelKk.value(17)




    config['Phalange'] = [  motion[0].skeleton.getJointIndex('LeftPhalange_1'),\
                            motion[0].skeleton.getJointIndex('LeftPhalange_2'),\
                            motion[0].skeleton.getJointIndex('RightPhalange_1'),\
                            motion[0].skeleton.getJointIndex('RightPhalange_2')]
    config['Talus'] = [ motion[0].skeleton.getJointIndex('LeftTalus_1'),\
                        motion[0].skeleton.getJointIndex('LeftTalus_2'),\
                        motion[0].skeleton.getJointIndex('RightTalus_1'),\
                        motion[0].skeleton.getJointIndex('RightTalus_2')]
    config['Calcaneus'] = [ motion[0].skeleton.getJointIndex('LeftCalcaneus_1'),\
                            motion[0].skeleton.getJointIndex('LeftCalcaneus_2'),\
                            motion[0].skeleton.getJointIndex('RightCalcaneus_1'),\
                            motion[0].skeleton.getJointIndex('RightCalcaneus_2')]
    pose = motion[0].copy()
    timeReport = [0.] * 2

    def simulateCallback(frame):
        curTime = time.time()
        Ke = 0.0
        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, B_CM, B_CMSd, B_Toe = viewer.GetParam(
        )
        motionModel.update(motion[frame])
        controlToMotionOffset = [-2.0, 0., 0.]
        motionModel.translateByOffset(controlToMotionOffset)

        stepsPerFrame = 10
        for i in range(stepsPerFrame):
            Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, B_CM, B_CMSd, B_Toe = viewer.GetParam(
            )
            #Kt, Kl, Kh, Bl, Bh, Ke = viewer.GetParam()
            #qps.setupWeight(Kt, Kl, Kh, Ke, Bt, Btau, Bcon, Bl, Bh, Be)
            qps.setupWeight(Kt, Kl, Kh, Ke, 10., .1, .1, Bl, Bh, 10.)
            cPositions, CP, CM, footCenter, dL_des, CM_ref = qps.setupQP(
                frame, motion, mcfg, controlModel, vpWorld, config,
                1. / (30. * stepsPerFrame))
            CM_ref[1] = 0.
            timeReport[0] += time.time() - curTime
            curTime = time.time()
            #forceforce = np.array([viewer.objectInfoWnd.labelForceX.value(), viewer.objectInfoWnd.labelForceY.value(), viewer.objectInfoWnd.labelForceZ.value()])
            #extraForce[0] = viewer.objectInfoWnd.labelFm.value() * mm.normalize2(forceforce)
            #extraForcePos[0] = controlModel.getBodyPositionGlobal(selectedBody)
            #if viewer.GetForceState() :
            #    qps.addExternalForces(extraForce[0], selectedBody, viewer.objectInfoWnd.labelForceDur.value());
            #    viewer.ResetForceState()
            x, cForce = qps.stepQP(controlModel, 1. / (30. * stepsPerFrame))
            timeReport[1] += time.time() - curTime
            curTime = time.time()

        print timeReport

        if frame % 30 == 0:
            print 'elapsed time for 30 frames:', time.time() - pt[0]
        # rendering

        #rd_footCenter[0] = footCenter
        #
        #rd_CM[0] = CM.copy()
        #
        #rd_CM_plane[0] = CM_plane.copy()
        #
        #rd_footCenter_ref[0] = footCenter_ref
        #rd_CM_plane_ref[0] = CM_ref.copy()
        #rd_CM_ref[0] = CM_ref.copy()
        #rd_CM_ref_vec[0] = (CM_ref - footCenter_ref)*3.
        #rd_CM_vec[0] = (CM - CM_plane)
        #rd_CM_des[0] = CM_ref_plane.copy()
        #rd_CM_des[0][1] = .01

        #rd_CM_plane[0][1] = 0.

        #if CP!=None and dCP!=None:


#        #    rd_CP[0] = CP
#        #    rd_CP_des[0] = CP_des
#        #
#        #rd_dL_des_plane[0] = dL_des_plane
#        #rd_dH_des[0] = dH_des
#        #
#        #rd_grf_des[0] = totalNormalForce# - totalMass*mm.s2v(wcfg.gravity)#dL_des_plane - totalMass*mm.s2v(wcfg.gravity)
#        #
#        #rd_exf_des[0] = applyedExtraForce[0]
#        #rd_root_des[0] = rootPos[0]
#
#        #rd_CMP[0] = softConstPoint
#
#        #rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(constBody)-softConstPoint
#
#
#        ##indexL = motion[0].skeleton.getJointIndex('Hips')
#        ##indexR = motion[0].skeleton.getJointIndex('Spine1')
#        #indexL = indexFootL[0]
#        #indexR = indexFootR[0]
#
#        #curAng = [controlModel.getBodyOrientationGlobal(indexL)]
#        #curAngY = np.dot(curAng, np.array([0,0,1]))
#
#        #rd_footL_vec[0] = np.copy(curAngY[0])
#        #rd_footCenterL[0] = controlModel.getBodyPositionGlobal(indexL)
#        #
#        #curAng = [controlModel.getBodyOrientationGlobal(indexR)]
#        #curAngY = np.dot(curAng, np.array([0,0,1]))
#
#rd_footR_vec[0] = np.copy(curAngY[0])
#rd_footCenterR[0] = controlModel.getBodyPositionGlobal(indexR)
#
#if (forceApplyFrame == 0) :
#    applyedExtraForce[0] = [0, 0, 0]

    viewer.setSimulateCallback(simulateCallback)

    viewer.startTimer(1 / 30.)
    viewer.show()

    Fl.run()
Ejemplo n.º 11
0
    
    node = mcfg.getNode('Spine')
    node.width = .22
    
    node = mcfg.getNode('RightFoot')
    node.length = .25
    
    node = mcfg.getNode('LeftFoot')
    node.length = .25
    
    return mcfg
    
    
g_motionDirConfigMap = {}
g_motionDirConfigMap['../../../Data/woody2/Motion/Physics2/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), -.4), 'yOffset': .0, 'scale':1.,'rootRot': mm.I_SO3()}
g_motionDirConfigMap['../../../Data/woody2/Motion/Balancing/'] = \
    {'footRot': mm.exp(mm.v3(1,-.5,0), -.6), 'yOffset': .0, 'scale':1.,'rootRot': mm.exp(mm.v3(1,0,0), .01)}
g_motionDirConfigMap['../../../Data/woody2/Motion/Picking/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), -.5), 'yOffset': .0, 'scale':1.,'rootRot': mm.I_SO3()}
g_motionDirConfigMap['../../../Data/woody2/Motion/Samsung/'] = \
    {'footRot': mm.rotX(-.5), 'yOffset': .0, 'scale':2.53999905501,'rootRot': mm.I_SO3()}
g_motionDirConfigMap['../../../Data/woody2/Motion/VideoMotion/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), -.05), 'yOffset': .01, 'scale':2.53999905501,'rootRot': mm.exp(mm.v3(1,0,0), .0)}


if __name__=='__main__':
    #===============================================================================
    # initialize motion
    #===============================================================================
    motionFiles = [] 
Ejemplo n.º 12
0
    config['FootRPart'] = [
        RIGHT_FOOT, RIGHT_TOES, RIGHT_TARSUS, RIGHT_FOOT_SIDE_L,
        RIGHT_FOOT_SIDE_R
    ]

    return motion, mcfg, wcfg, stepsPerFrame, config


#===============================================================================
# biped config
#===============================================================================

# motion, mesh config
g_motionDirConfigMap = {}
g_motionDirConfigMap['../Data/woody2/Motion/Physics2/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), .05), 'yOffset': .0, 'scale':1.,\
     'rootRot': mm.I_SO3()}
g_motionDirConfigMap['../Data/woody2/Motion/Balancing/'] = \
    {'footRot': mm.exp(mm.v3(1,-.5,0), -.6), 'yOffset': .0, 'scale':1.,\
     'rootRot': mm.exp(mm.v3(1,0,0), .01)}
g_motionDirConfigMap['../Data/woody2/Motion/VideoMotion/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), -.05), 'yOffset': .01, 'scale':2.53999905501,\
     'rootRot': mm.exp(mm.v3(1,0,0), .0)}
g_motionDirConfigMap['../Data/woody2/Motion/Samsung/'] = \
    {'footRot': mm.exp(mm.v3(1,0,0), -.03), 'yOffset': .0, 'scale':2.53999905501,\
     'rootRot': mm.exp(mm.v3(1,0,0), .03)}


#===============================================================================
# # reloadable config
#===============================================================================
Ejemplo n.º 13
0
def main():
    np.set_printoptions(precision=4, linewidth=200)

    #    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()

    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)

    #controlModel2 = cvm.VpControlModel(vpWorld, motion[0], mcfg)

    vpWorld.initialize()
    controlModel.initializeHybridDynamics()
    controlModel.translateByOffset((1.5, 0, 0))

    #controlModel2.initializeHybridDynamics()
    #controlModel2.translateByOffset((2.5,0,0))

    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()

    # parameter
    Kt = config['Kt']
    Dt = config['Dt']  # tracking gain
    Kl = config['Kl']
    Dl = config['Dl']  # linear balance gain
    Kh = config['Kh']
    Dh = config['Dh']  # angular balance gain
    Ks = config['Ks']
    Ds = config['Ds']  # penalty force spring gain

    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']

    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    sup = motion[0].skeleton.getJointIndex(config['supLink'])

    sup2 = motion[0].skeleton.getJointIndex(config['supLink2'])

    # jacobian
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()

    supJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, sup)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)

    Jsup2 = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup2 = Jsup2.copy()

    supJointMasks2 = [yjc.getLinkJointMask(motion[0].skeleton, sup2)]

    CMJointMask = supJointMasks
    for iMask in range(len(CMJointMask[0])):
        if supJointMasks2[0][iMask] == 1:
            CMJointMask[0][iMask] = 1

    Jt = yjc.makeEmptyJacobian(DOFs, 1)

    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses)
    dTO = ymt.make_dTO(len(linkMasses))

    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0, 0, 0, 0, 0, 0)
    CP_old = [mm.v3(0., 0., 0.)]

    # penalty method
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.] * len(bodyIDsToCheck)

    ##### Parameter
    '''
    (0, 'Hips')
    (1, 'LeftUpLeg')
    (2, 'LeftLeg')
    (3, 'LeftFoot')
    (4, 'RightUpLeg')
    (5, 'RightLeg')
    (6, 'RightFoot')
    (7, 'Spine')
    (8, 'Spine1')
    (9, 'LeftArm')
    (10, 'LeftForeArm')
    (11, 'RightArm')
    (12, 'RightForeArm')
    '''
    Kp = [None] * len(bodyIDsToCheck)
    Kd = [None] * len(bodyIDsToCheck)
    #Kp = [0,  400, 450, 400,  400, 450, 400,  300, 250,   60, 25, 60, 25]
    #Kp = [0,  450, 450, 400,  450, 450, 400,  450, 300,   100, 25, 100, 25]

    UpLeg = 310
    Leg = 400
    Foot = 310
    Spine = 350
    Neck = 200
    Arm = 10
    Hand = 10
    Kp = [
        0, UpLeg, Leg, Foot, UpLeg, Leg, Foot, Spine, Neck, Arm, Hand, Arm,
        Hand
    ]
    '''
    for i in range(0, len(Kp)) :
        Kp[i] = Kp[i]*0.8
    '''

    #Kd = [0,  0, 0, 0,    0, 0, 0,    0, 0,  0, 0, 0, 0]
    #Kd = [0,  2.0, 1.5, 1.2,    2.0, 1.5, 1.2,    2.0, 0.1,  0.1, 0.1, 0.1, 0.1]
    #Kd = [0,  1.5, 2.0, 1.2,    1.5, 2.0, 1.2,    1.5, 0.4,  0.5, 0.2, 0.5, 0.2]
    '''
    dUpLeg = 1.7
    dLeg = 1.7
    dFoot = 1.2
    dSpine = 1.4
    dNeck = 0.9
    dArm = 0.8
    dHand = 0.2
    '''
    dUpLeg = 2 * (UpLeg**.5)
    dLeg = 2 * (Leg**.5)
    dFoot = 2 * (Foot**.5)
    dSpine = 2 * (Spine**.5)
    dNeck = 2 * (Neck**.5)
    dArm = 2 * (Arm**.5)
    dHand = 2 * (Hand**.5)

    Kd = [
        0, dUpLeg, dLeg, dFoot, dUpLeg, dLeg, dFoot, dSpine, dNeck, dArm,
        dHand, dArm, dHand
    ]

    for i in range(0, len(Kd)):
        Kd[i] = Kd[i] * 0.022
    '''
    for ii in bodyIDsToCheck :
        print(ii, controlModel.index2name(ii))
    '''

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    # viewer
    rd_footCenter = [None]
    rd_footCenter1 = [None]
    rd_footCenter2 = [None]
    rd_CM_plane = [None]
    rd_CM = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    rd_vf = [None]

    rd_contactPoint1 = [None]
    rd_contactPoint2 = [None]

    viewer = ysv.SimpleViewer()
    #    viewer.record(False)
    #    viewer.doc.addRenderer('control', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer(
        'motionModel',
        cvr.VpModelRenderer(motionModel, (150, 150, 255), yr.POLYGON_FILL))
    viewer.doc.addRenderer(
        'controlModel',
        cvr.VpModelRenderer(controlModel, (255, 240, 255), yr.POLYGON_FILL))
    #viewer.doc.addRenderer('controlModel2', cvr.VpModelRenderer(controlModel2, (155,100,100), yr.POLYGON_FILL))

    #viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))
    #viewer.doc.addRenderer('rd_footCenter1', yr.PointsRenderer(rd_footCenter1, (255, 0, 255)))
    #viewer.doc.addRenderer('rd_footCenter2', yr.PointsRenderer(rd_footCenter2, (0, 255, 255)))
    #viewer.doc.addRenderer('rd_CM_plane', yr.PointsRenderer(rd_CM_plane, (255,255,0)))
    #viewer.doc.addRenderer('rd_CM', yr.PointsRenderer(rd_CM, (255,255,0)))

    #viewer.doc.addRenderer('rd_contactPoint', yr.PointsRenderer(rd_contactPoint1, (0,0,255)))
    #viewer.doc.addRenderer('rd_contactPoint2', yr.PointsRenderer(rd_contactPoint2, (0,255,255)))
    #viewer.doc.addRenderer('rd_CP', yr.PointsRenderer(rd_CP, (255,0,255)))
    #    viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (255,0,255)))
    #    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
    #    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
    #viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP_des, (0,255,0), .001))
    viewer.doc.addRenderer('rd_vf',
                           yr.ForcesRenderer(rd_vf, rd_CM, (0, 0, 255), .005))

    global stage
    stage = 0

    def simulateCallback(frame):
        motionModel.update(motion[frame])

        # tracking
        th_r = motion.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r,
                                                  Kt, Dt)
        '''
        th2 = controlModel2.getDOFPositions()
        dth2 = controlModel2.getDOFVelocities()
        ddth_des2 = yct.getDesiredDOFAccelerations(th_r, th2, dth_r, dth2, ddth_r, Kt, Dt)
        '''

        #ype.flatten(ddth_des, ddth_des_flat)
        #ype.flatten(dth, dth_flat)

        #Control

        #tracking control
        #print(Kt, Dt)
        #Tpd = yct.getDesiredDOFTorques(th_r, th, dth_r, dth, 100.0, 0.1)#0.65, 0.031)

        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()

        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        footCenter1 = controlModel.getBodyPositionGlobal(sup)
        footCenter2 = controlModel.getBodyPositionGlobal(sup2)
        footCenter = (footCenter1 + footCenter2) / 2
        '''
        yjc.computeJacobian2(Jt, DOFs, jointPositions, jointAxeses, [CM], CMJointMask)

        pHatCom = CM - footCenter
        vCom = dCM
        '''

        CM_plane = copy.copy(CM)
        CM_plane[1] = 0.
        dCM_plane = copy.copy(dCM)
        dCM_plane[1] = 0.
        CM_ref_plane = footCenter
        dL_des_plane = Kl * totalMass * (CM_ref_plane -
                                         CM_plane) - Dl * totalMass * dCM_plane
        dL_des_plane[1] = 0.

        CP_ref = footCenter
        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
            bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)

        if CP_old[0] == None or CP == None:
            dCP = None
        else:
            dCP = (CP - CP_old[0]) / (1 / 30.)
        CP_old[0] = CP

        if CP != None and dCP != None:
            ddCP_des = Kh * (CP_ref - CP) - Dh * (dCP)
            CP_des = CP + dCP * (1 / 30.) + .5 * ddCP_des * ((1 / 30.)**2)
            dH_des = np.cross(
                (CP_des - CM),
                (dL_des_plane - totalMass * mm.s2v(wcfg.gravity)))
        else:
            dH_des = None

        ################
        '''
        linkPositions = motionModel.getBodyPositionsGlobal()
        linkVelocities = motionModel.getBodyVelocitiesGlobal()
        linkAngVelocities = motionModel.getBodyAngVelocitiesGlobal()
        linkInertias = motionModel.getBodyInertiasGlobal()
                    
        CM2 = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM2 = yrp.getCM(linkVelocities, linkMasses, totalMass)            
        footCenter1 = motionModel.getBodyPositionGlobal(sup)
        footCenter2 = motionModel.getBodyPositionGlobal(sup2)
        footCenter = (footCenter1+footCenter2)/2
        pHatComDes = CM2 - footCenter
        vComDes = dCM2

        Wcp = -750
        Wcv = -10
        fCom = Wcp*(pHatComDes - pHatCom) + Wcv*(vComDes - vCom)
        '''

        #print("VirtualForce", fCom)
        #fCom[0] = 0.
        #fCom[1] = 0.
        #fCom[2] = -20.
        #fCom = [0., 0., 100.]
        #print("VirtualForce", fCom)

        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
                bodyIDsToCheck, mus, Ks, Ds)
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals,
                                      contactForces)

            controlModel.setDOFAccelerations(ddth_des)

            linkPositions = controlModel.getBodyPositionsGlobal()
            linkVelocities = controlModel.getBodyVelocitiesGlobal()
            linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
            linkInertias = controlModel.getBodyInertiasGlobal()

            jointPositions = controlModel.getJointPositionsGlobal()
            jointAxeses = controlModel.getDOFAxeses()

            CM = yrp.getCM(linkPositions, linkMasses, totalMass)
            dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
            footCenter1 = controlModel.getBodyPositionGlobal(sup)
            footCenter2 = controlModel.getBodyPositionGlobal(sup2)
            footCenter = (footCenter1 + footCenter2) / 2

            CM_plane = copy.copy(CM)
            CM_plane[1] = 0.
            footCenter_plane = copy.copy(footCenter)
            footCenter_plane[1] = 0.

            yjc.computeJacobian2(Jt, DOFs, jointPositions, jointAxeses, [CM],
                                 CMJointMask)

            pHatCom = CM - footCenter
            vCom = dCM

            linkPositions2 = motionModel.getBodyPositionsGlobal()
            linkVelocities2 = motionModel.getBodyVelocitiesGlobal()
            linkAngVelocities2 = motionModel.getBodyAngVelocitiesGlobal()
            linkInertias2 = motionModel.getBodyInertiasGlobal()

            CM2 = yrp.getCM(linkPositions2, linkMasses, totalMass)
            dCM2 = yrp.getCM(linkVelocities2, linkMasses, totalMass)
            footCenter1 = motionModel.getBodyPositionGlobal(sup)
            footCenter2 = motionModel.getBodyPositionGlobal(sup2)
            footCenter = (footCenter1 + footCenter2) / 2
            pHatComDes = CM2 - footCenter
            vComDes = dCM2

            Wcp = 0
            Wcv = 0
            Wcm = 0
            '''
            0 : initial
            1 : contact
            2 : fly
            3 : landing
            '''

            global stage
            if len(contactForces) == 0:
                if stage == 1:
                    stage = 2
                    print("fly")
            else:
                if stage == 0:
                    stage = 1
                    print("contact")
                elif stage == 2:
                    stage = 3
                    print("landing")

            Wcp = -550
            Wcv = -100
            Wcm = 0

            if stage == 1:
                Wcp = -550
                Wcv = -100
                Wcm = 0
                #Wcp = -550
                #Wcv = -100
            elif stage == 3:
                #Wcp = -950
                #Wcv = -300
                Wcp = -950
                Wcv = -300
                Wcm = 0

            # COM Position control
            fCom = Wcp * (pHatComDes - pHatCom) + Wcv * (
                vComDes - vCom) + Wcm * (footCenter_plane - CM_plane)

            if len(contactForces) == 0:
                fCom[0] = 0.
                fCom[1] = -10.  #-10
                fCom[2] = 0.
            '''
            fCom[0] = 10.
            fCom[1] = 0.
            fCom[2] = 250.
            '''

            # Angular Momentum control
            L_ref = 0
            L_con = 0
            #R,i
            for i in range(1, controlModel.getBodyNum()):
                L_ref += (
                    linkMasses[i] *
                    np.cross(linkPositions2[i] - [CM], linkVelocities2[i]) +
                    linkInertias2[i] * linkAngVelocities2[i])
                L_con += (
                    linkMasses[i] *
                    np.cross(linkPositions[i] - [CM], linkVelocities[i]) +
                    linkInertias[i] * linkAngVelocities[i])

            for iJoint in range(1, 7):  # from 'LeftUpLeg'(1) to 'RightFoot'(6)
                JpT1 = (Jt[0][6 + 3 * (iJoint - 1)],
                        Jt[1][6 + 3 * (iJoint - 1)],
                        Jt[2][6 + 3 * (iJoint - 1)])
                JpT2 = (Jt[0][6 + 3 * (iJoint - 1) + 1],
                        Jt[1][6 + 3 * (iJoint - 1) + 1],
                        Jt[2][6 + 3 * (iJoint - 1) + 1])
                JpT3 = (Jt[0][6 + 3 * (iJoint - 1) + 2],
                        Jt[1][6 + 3 * (iJoint - 1) + 2],
                        Jt[2][6 + 3 * (iJoint - 1) + 2])
                Tfi = (np.dot(JpT1, fCom), np.dot(JpT2,
                                                  fCom), np.dot(JpT3, fCom))
                currentT = controlModel.getJointAngAccelerationLocal(iJoint)
                controlModel.setJointAngAccelerationLocal(
                    iJoint, currentT + Tfi)

            currentT = controlModel.getJointAngAccelerationLocal(0)
            #print(currentT)
            #JpT = ( Jt[0][0], Jt[1][0], Jt[2][0])
            #Tfi = JpT*fCom
            #controlModel.setJointAngAccelerationLocal(0, currentT+Tfi)
            '''
            if (len(contactForces) != 0) :
                for iJoint in range(1, 7): # from 'LeftUpLeg'(1) to 'RightFoot'(6)
                    JpT = ( Jt[0][6+3*(iJoint-1)], Jt[1][6+3*(iJoint-1)], Jt[2][6+3*(iJoint-1)])
                    Tfi = JpT*fCom
                    currentT = controlModel.getJointAngAccelerationLocal(iJoint)
                    controlModel.setJointAngAccelerationLocal(iJoint, currentT+Tfi)
            else:
                print("No Contact force!!")
            '''

            controlModel.solveHybridDynamics()

            vpWorld.step()

        # rendering

        rd_CM[0] = CM

        rd_CM_plane[0] = CM.copy()
        rd_CM_plane[0][1] = 0.

        if CP != None and dCP != None:
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des

        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des

        rd_grf_des[0] = dL_des_plane - totalMass * mm.s2v(wcfg.gravity)
        rd_vf[0] = fCom

    viewer.setSimulateCallback(simulateCallback)

    viewer.startTimer(1 / 30.)
    viewer.show()

    Fl.run()
Ejemplo n.º 14
0
def create_biped():

    # motion
    #motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        motionName = 'wd2_stand.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'

    #motionName = 'ww13_41_V001.bvh'
    motion = yf.readBvhFile(motionName, .01)

    yme.removeJoint(motion, HEAD, False)
    yme.removeJoint(motion, RIGHT_SHOULDER, False)
    yme.removeJoint(motion, LEFT_SHOULDER, False)
    #yme.removeJoint(motion, RIGHT_TOES_END, False)
    #yme.removeJoint(motion, LEFT_TOES_END, False)
    yme.removeJoint(motion, RIGHT_HAND_END, False)
    yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1, 0, 0), .01), False)
    yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(2.5, -0.0, .3), -.5),
                         False)
    yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(2.5, 0.0, -.3), -.5),
                         False)

    if MOTION == FORWARD_JUMP:
        yme.rotateJointLocal(motion, LEFT_UP_LEG,
                             mm.exp(mm.v3(0.0, .0, 1.), .08), False)
        yme.rotateJointLocal(motion, LEFT_LEG, mm.exp(mm.v3(0.0, 1.0, 0.),
                                                      -.2), False)

    #yme.offsetJointLocal(motion, LEFT_TOES, (.03,-.05,0), False)
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCA)
    yme.addJoint(motion, RIGHT_CALCA, 'RIGHT_Dummy')

    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCA)
    yme.addJoint(motion, LEFT_CALCA, 'LEFT_Dummy')

    if 0:
        yme.rotateJointLocal(motion, LEFT_TOES, mm.exp(mm.v3(1., 0.0, 0.0),
                                                       .2), False)
        yme.rotateJointLocal(motion, RIGHT_TOES,
                             mm.exp(mm.v3(1., 0.0, 0.0), .2), False)
        yme.rotateJointLocal(motion, LEFT_CALCA,
                             mm.exp(mm.v3(1., 0.0, 0.0), .7), False)
        yme.rotateJointLocal(motion, RIGHT_CALCA,
                             mm.exp(mm.v3(1., 0.0, 0.0), .7), False)
    else:
        yme.rotateJointLocal(motion, LEFT_TOES, mm.exp(mm.v3(1., 0.0, 0.0),
                                                       .45), False)
        yme.rotateJointLocal(motion, RIGHT_TOES,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_CALCA,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)
        yme.rotateJointLocal(motion, RIGHT_CALCA,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    ## Taekwondo turning-kick
    #motion = motion[100:-1]

    motion[0:0] = [motion[0]] * 100
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    #node.length = .2 ####

    node = mcfg.getNode(RIGHT_FOOT)
    node.length = .1
    node.width = .2
    node.mass = 1.5

    node = mcfg.getNode(LEFT_FOOT)
    node.length = .1
    node.width = .2
    node.mass = 1.5

    node = mcfg.getNode(LEFT_TOES)
    node.length = .1
    node.width = .2
    node.mass = 1.5
    node.offset = (0, 0.0, -0.02)

    node = mcfg.getNode(RIGHT_TOES)
    node.length = .1
    node.width = .2
    node.mass = 1.5
    node.offset = (0, 0.0, -0.02)

    node = mcfg.getNode(LEFT_CALCA)
    node.length = .1
    node.width = .2
    node.mass = 1.5
    node.offset = (0, 0.0, -0.08)

    node = mcfg.getNode(RIGHT_CALCA)
    node.length = .1
    node.width = .2
    node.mass = 1.5
    node.offset = (0, 0.0, -0.08)

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 30
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    '''
    config['Kt'] = 200;      config['Dt'] = 2*(config['Kt']**.5) # tracking gain
    config['Kl'] = 2.5;       config['Dl'] = 2*(config['Kl']**.5) # linear balance gain
    config['Kh'] = 1;       config['Dh'] = 2*(config['Kh']**.5) # angular balance gain
    config['Ks'] = 20000;   config['Ds'] = 2*(config['Ks']**.5) # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 2.5
    config['Bh'] = 1.
    '''
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    config['weightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2,\
                         SPINE:.3, SPINE1:.3, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.5,\
                         RIGHT_UP_LEG:.1, RIGHT_LEG:.3, LEFT_UP_LEG:.1, LEFT_LEG:.3, LEFT_TOES:.1, RIGHT_TOES:.1, LEFT_CALCA:.3, RIGHT_CALCA:.3}

    config['IKweightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2,\
                         SPINE:.3, SPINE1:.3, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.5,\
                         RIGHT_UP_LEG:.1, RIGHT_LEG:.3, LEFT_UP_LEG:.1, LEFT_LEG:.3}
    '''
    config['IKweightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2,\
                         SPINE:0.5, SPINE1:0.5, RIGHT_FOOT:1.2, LEFT_FOOT:1.2, HIP:1.2,\
                         RIGHT_UP_LEG:.9, RIGHT_LEG:.9, LEFT_UP_LEG:.9, LEFT_LEG:.9}
    '''

    config['weightMap2']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2,\
                         SPINE:1.5, LEFT_FOOT:1., HIP:1.5,\
                         RIGHT_UP_LEG:1., RIGHT_LEG:1., LEFT_UP_LEG:1., LEFT_LEG:1., LEFT_TOES:.1, RIGHT_TOES:.1, LEFT_CALCA:.1, RIGHT_CALCA:.1}

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    #config['end'] = 'HIP'
    config['end'] = SPINE1
    config['const'] = HIP
    config['root'] = HIP

    config['leftForeFoot'] = LEFT_TOES
    config['rightForeFoot'] = RIGHT_TOES
    config['leftRearFoot'] = LEFT_CALCA
    config['rightRearFoot'] = RIGHT_CALCA

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 15
0
def create_biped():
    # motion
    #motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        motionName = 'wd2_stand.bvh'
    elif MOTION == STAND2:
        motionName = 'ww13_41_V001.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == TAEKWONDO2:
        motionName = './MotionFile/wd2_098_V002.bvh'

    #motionName = 'ww13_41_V001.bvh'
    motion = yf.readBvhFile(motionName, .01)

    yme.removeJoint(motion, HEAD, False)
    yme.removeJoint(motion, RIGHT_SHOULDER, False)
    yme.removeJoint(motion, LEFT_SHOULDER, False)

    if FOOT_PART_NUM == 1 or FOOT_PART_NUM == 5 or FOOT_PART_NUM == 7:
        yme.removeJoint(motion, RIGHT_TOES, False)
        yme.removeJoint(motion, RIGHT_TOES_END, False)
        yme.removeJoint(motion, LEFT_TOES_END, False)

    yme.removeJoint(motion, RIGHT_HAND_END, False)
    yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1, 0, 0), .01), False)

    #yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(2.5,-0.0,.3), -.5), False)
    #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(2.5,0.0,-.3), -.5), False)
    yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(2.5, -0.0, .3), -.5),
                         False)
    #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(2.5,0.0,-.3), -.5), False)

    if MOTION == FORWARD_JUMP:
        yme.rotateJointLocal(motion, LEFT_UP_LEG,
                             mm.exp(mm.v3(0.0, .0, 1.), .08), False)
        yme.rotateJointLocal(motion, LEFT_LEG, mm.exp(mm.v3(0.0, 1.0, 0.),
                                                      -.2), False)

    if FOOT_PART_NUM > 1 and FOOT_PART_NUM < 5:
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_TARSUS)
        yme.addJoint(motion, RIGHT_TARSUS, 'RIGHT_Dummy1')
        yme.addJoint(motion, LEFT_FOOT, LEFT_TARSUS)
        yme.addJoint(motion, LEFT_TARSUS, 'LEFT_Dummy1')
        yme.rotateJointLocal(motion, LEFT_TOES, mm.exp(mm.v3(1., 0.0, 0.0),
                                                       .45), False)
        yme.rotateJointLocal(motion, RIGHT_TOES,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_TARSUS,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)
        yme.rotateJointLocal(motion, RIGHT_TARSUS,
                             mm.exp(mm.v3(1., 0.0, 0.0), .52), False)

    if FOOT_PART_NUM == 4:
        yme.addJoint(motion, LEFT_FOOT, LEFT_TOES_SIDE_R)
        yme.addJoint(motion, LEFT_TOES_SIDE_R, 'LEFT_Dummy2')
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_TOES_SIDE_R)
        yme.addJoint(motion, RIGHT_TOES_SIDE_R, 'RIGHT_Dummy2')
        yme.rotateJointLocal(motion, LEFT_TOES_SIDE_R,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, RIGHT_TOES_SIDE_R,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
    elif FOOT_PART_NUM == 5:
        sibIndex = motion[0].skeleton.getElementIndex(RIGHT_FOOT)
        skeleton = motion[0].skeleton
        sibJoint = skeleton.getElement(sibIndex)
        newOffset = sibJoint.offset.copy()

        yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS, (0.0, 0., -.1))
        yme.addJoint(motion, RIGHT_CALCANEUS, 'RIGHT_Dummy3')
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_METATARSAL_3, (-0.1, 0., 0.0))

        yme.addJoint(motion, RIGHT_FOOT, RIGHT_PHALANGE_1, (0.1, 0., .2))
        yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_Dummy4', (0., 0., .1))
        yme.addJoint(motion, RIGHT_METATARSAL_3, RIGHT_PHALANGE_3)
        #yme.addJoint(motion, RIGHT_PHALANGE_3, 'RIGHT_Dummy6')

        sibIndex = motion[0].skeleton.getElementIndex(LEFT_FOOT)
        skeleton = motion[0].skeleton
        sibJoint = skeleton.getElement(sibIndex)
        newOffset = sibJoint.offset.copy()
        yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS)
        yme.addJoint(motion, LEFT_CALCANEUS, 'LEFT_Dummy3')
        yme.addJoint(motion, LEFT_FOOT, LEFT_METATARSAL_3)

        yme.addJoint(motion, LEFT_FOOT, LEFT_PHALANGE_1)
        yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_Dummy4')
        yme.addJoint(motion, LEFT_METATARSAL_3, LEFT_PHALANGE_3)
        yme.addJoint(motion, LEFT_PHALANGE_3, 'LEFT_Dummy6')
        '''
        yme.addJoint(motion, RIGHT_LEG, RIGHT_CALCANEUS, (0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, RIGHT_CALCANEUS, 'RIGHT_Dummy3')
        yme.addJoint(motion, RIGHT_LEG, RIGHT_METATARSAL_3, (0.0025, -0.4209, -0.0146))
        
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_PHALANGE_1)
        yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_Dummy4')      
        yme.addJoint(motion, RIGHT_METATARSAL_3, RIGHT_PHALANGE_3)
        yme.addJoint(motion, RIGHT_PHALANGE_3, 'RIGHT_Dummy6')              
        
        sibIndex = motion[0].skeleton.getElementIndex(LEFT_FOOT)        
        skeleton = motion[0].skeleton    
        sibJoint = skeleton.getElement(sibIndex)
        newOffset = sibJoint.offset.copy()
        yme.addJoint(motion, LEFT_LEG, LEFT_CALCANEUS, (-0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, LEFT_CALCANEUS, 'LEFT_Dummy3')    
        yme.addJoint(motion, LEFT_LEG, LEFT_METATARSAL_3, (-0.0025, -0.4209, -0.0146))
        
        yme.addJoint(motion, LEFT_FOOT, LEFT_PHALANGE_1)
        yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_Dummy4') 
        yme.addJoint(motion, LEFT_METATARSAL_3, LEFT_PHALANGE_3)
        yme.addJoint(motion, LEFT_PHALANGE_3, 'LEFT_Dummy6')                   
        '''
        '''
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3, mm.exp(mm.v3(1.,0.0,0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_METATARSAL_3, mm.exp(mm.v3(1.,0.0,0.0), .45), False)

        yme.rotateJointLocal(motion, RIGHT_PHALANGE_1, mm.exp(mm.v3(1.,0.0,0.0), .0), False)
        yme.rotateJointLocal(motion, LEFT_PHALANGE_1, mm.exp(mm.v3(1.,0.0,0.0), .45), False)
        
        yme.rotateJointLocal(motion, LEFT_CALCANEUS, mm.exp(mm.v3(1.,0.0,0.0), .45), False)
        yme.rotateJointLocal(motion, RIGHT_CALCANEUS, mm.exp(mm.v3(1.,0.0,0.0), .45), False)
        '''

    elif FOOT_PART_NUM == 7:
        sibIndex = motion[0].skeleton.getElementIndex(RIGHT_FOOT)
        skeleton = motion[0].skeleton
        sibJoint = skeleton.getElement(sibIndex)
        newOffset = sibJoint.offset.copy()
        print(newOffset)
        yme.addJoint(motion, RIGHT_LEG, RIGHT_CALCANEUS,
                     (0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, RIGHT_CALCANEUS, 'RIGHT_Dummy3')
        yme.addJoint(motion, RIGHT_LEG, RIGHT_METATARSAL_2,
                     (0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, RIGHT_LEG, RIGHT_METATARSAL_3,
                     (0.0025, -0.4209, -0.0146))

        yme.addJoint(motion, RIGHT_FOOT, RIGHT_PHALANGE_1)
        yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_Dummy4')
        yme.addJoint(motion, RIGHT_METATARSAL_2, RIGHT_PHALANGE_2)
        yme.addJoint(motion, RIGHT_PHALANGE_2, 'RIGHT_Dummy5')
        yme.addJoint(motion, RIGHT_METATARSAL_3, RIGHT_PHALANGE_3)
        yme.addJoint(motion, RIGHT_PHALANGE_3, 'RIGHT_Dummy6')

        sibIndex = motion[0].skeleton.getElementIndex(LEFT_FOOT)
        skeleton = motion[0].skeleton
        sibJoint = skeleton.getElement(sibIndex)
        newOffset = sibJoint.offset.copy()
        yme.addJoint(motion, LEFT_LEG, LEFT_CALCANEUS,
                     (-0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, LEFT_CALCANEUS, 'LEFT_Dummy3')
        yme.addJoint(motion, LEFT_LEG, LEFT_METATARSAL_2,
                     (-0.0025, -0.4209, -0.0146))
        yme.addJoint(motion, LEFT_LEG, LEFT_METATARSAL_3,
                     (-0.0025, -0.4209, -0.0146))

        yme.addJoint(motion, LEFT_FOOT, LEFT_PHALANGE_1)
        yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_Dummy4')
        yme.addJoint(motion, LEFT_METATARSAL_2, LEFT_PHALANGE_2)
        yme.addJoint(motion, LEFT_PHALANGE_2, 'LEFT_Dummy5')
        yme.addJoint(motion, LEFT_METATARSAL_3, LEFT_PHALANGE_3)
        yme.addJoint(motion, LEFT_PHALANGE_3, 'LEFT_Dummy6')

        #yme.offsetJointLocal(motion, RIGHT_CALCANEUS, (0.0,-1.55,0), False)
        #yme.offsetJointLocal(motion, RIGHT_METATARSAL_2, (.0,-1.55,0), False)
        #yme.offsetJointLocal(motion, RIGHT_METATARSAL_3, (.0,-1.55,0), False)

        yme.rotateJointLocal(motion, RIGHT_METATARSAL_2,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .3), False)
        yme.rotateJointLocal(motion, LEFT_METATARSAL_2,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .3), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .3), False)
        yme.rotateJointLocal(motion, LEFT_METATARSAL_3,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .3), False)

        yme.rotateJointLocal(motion, RIGHT_PHALANGE_1,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)
        yme.rotateJointLocal(motion, LEFT_PHALANGE_1,
                             mm.exp(mm.v3(1., 0.0, 0.0), .45), False)

        yme.rotateJointLocal(motion, LEFT_CALCANEUS,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .20), False)
        yme.rotateJointLocal(motion, RIGHT_CALCANEUS,
                             mm.exp(mm.v3(-1., 0.0, 0.0), .20), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    elif MOTION == TAEKWONDO2:
        ## Taekwondo base-step
        motion = motion[0:31 + 40]
    ## Taekwondo turning-kick
    #motion = motion[108:-1]
    #motion = motion[108:109]

    motion[0:0] = [motion[0]] * 100
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    #node.length = .2 ####

    if FOOT_PART_NUM == 1:
        length1 = .25
        width1 = .2
        mass1 = 4.
    elif FOOT_PART_NUM == 3:
        length1 = .1
        width1 = .2
        mass1 = 1.5
        length2 = .1
        width2 = .2
        mass2 = 1.5
    elif FOOT_PART_NUM == 4:
        length1 = .1
        width1 = .2
        mass1 = 1.5
        length2 = .1
        width2 = .095
        mass2 = .75
    elif FOOT_PART_NUM == 5:
        mass0 = .4
        width0 = 0.028

        #Metatarsal1
        length1 = .18
        width1 = width0 * 3
        mass1 = mass0 * 2.8
        #Metatarsal3
        length3 = .17
        width3 = width0 * 3
        mass3 = mass0 * 2.7
        #Calcaneus
        length4 = .08
        width4 = 0.15
        mass4 = mass0 * 2.3
        #Phalange1
        length5 = .06
        width5 = width1
        mass5 = mass0 * 0.9
        #Phalange3
        length7 = .05
        width7 = width3
        mass7 = mass0 * 0.7

    elif FOOT_PART_NUM == 7:
        mass0 = .4
        width0 = 0.028

        #Metatarsal1
        length1 = .2
        width1 = width0 * 2
        mass1 = mass0 * 2
        #Metatarsal2
        length2 = .2
        width2 = width0
        mass2 = mass0
        #Metatarsal3
        length3 = .19
        width3 = width0 * 3
        mass3 = mass0 * 2.8
        #Calcaneus
        length4 = .08
        width4 = 0.15
        mass4 = mass0 * 2
        #Phalange1
        length5 = .06
        width5 = width1
        mass5 = mass0 / 2.
        #Phalange2
        length6 = .06
        width6 = width2
        mass6 = mass0 / 4.
        #Phalange3
        length7 = .05
        width7 = width3
        mass7 = mass6 * 2.8

    if FOOT_PART_NUM == 7:
        node = mcfg.getNode(RIGHT_FOOT)
        node.offset = (0.055, -0.03, 0.04)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node = mcfg.getNode(RIGHT_METATARSAL_2)
        node.offset = (0.01, -0.03, 0.065)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node = mcfg.getNode(RIGHT_METATARSAL_3)
        node.offset = (-.05, -0.03, 0.055)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(RIGHT_CALCANEUS)
        node.offset = (.0, -0.03, -0.07)
        node.length = length4
        node.width = width4
        node.mass = mass4

        node = mcfg.getNode(RIGHT_PHALANGE_1)
        node.offset = (0.055, -0.03, 0.19)
        node.length = length5
        node.width = width5
        node.mass = mass5
        node = mcfg.getNode(RIGHT_PHALANGE_2)
        node.offset = (0.01, -0.03, 0.19)
        node.length = length6
        node.width = width6
        node.mass = mass6
        node = mcfg.getNode(RIGHT_PHALANGE_3)
        node.offset = (-.05, -0.03, 0.18)
        node.length = length7
        node.width = width7
        node.mass = mass7

        node = mcfg.getNode(LEFT_FOOT)
        node.offset = (-0.055, -0.03, 0.04)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node = mcfg.getNode(LEFT_METATARSAL_2)
        node.offset = (-0.01, -0.03, 0.065)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node = mcfg.getNode(LEFT_METATARSAL_3)
        node.offset = (.05, -0.03, 0.055)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(LEFT_CALCANEUS)
        node.offset = (.0, -0.03, -0.07)
        node.length = length4
        node.width = width4
        node.mass = mass4

        node = mcfg.getNode(LEFT_PHALANGE_1)
        node.offset = (-0.055, -0.03, 0.19)
        node.length = length5
        node.width = width5
        node.mass = mass5
        node = mcfg.getNode(LEFT_PHALANGE_2)
        node.offset = (-0.01, -0.03, 0.19)
        node.length = length6
        node.width = width6
        node.mass = mass6
        node = mcfg.getNode(LEFT_PHALANGE_3)
        node.offset = (.05, -0.03, 0.18)
        node.length = length7
        node.width = width7
        node.mass = mass7

    elif FOOT_PART_NUM == 5:
        '''
        node = mcfg.getNode(RIGHT_FOOT)
        node.offset = (0.05,-0.03,0.06)
        node.length = length1
        node.width = width1
        node.mass = mass1
        '''
        node = mcfg.getNode(RIGHT_METATARSAL_3)
        node.offset = (-.04, -0.03, 0.075)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(RIGHT_CALCANEUS)
        node.offset = (.0, -0.03, -0.05)
        node.length = length4
        node.width = width4
        node.mass = mass4

        #node = mcfg.getNode(RIGHT_PHALANGE_1)
        #node.offset = (0.05,-0.03,0.19)
        #node.length = length5
        #node.width = width5
        #node.mass = mass5
        node = mcfg.getNode(RIGHT_PHALANGE_3)
        node.offset = (-.04, -0.03, 0.18)
        node.length = length7
        node.width = width7
        node.mass = mass7

        node = mcfg.getNode(LEFT_FOOT)
        node.offset = (-0.05, -0.03, 0.06)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node = mcfg.getNode(LEFT_METATARSAL_3)
        node.offset = (.04, -0.03, 0.075)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(LEFT_CALCANEUS)
        node.offset = (.0, -0.03, -0.05)
        node.length = length4
        node.width = width4
        node.mass = mass4

        node = mcfg.getNode(LEFT_PHALANGE_1)
        node.offset = (-0.05, -0.03, 0.19)
        node.length = length5
        node.width = width5
        node.mass = mass5
        node = mcfg.getNode(LEFT_PHALANGE_3)
        node.offset = (.04, -0.03, 0.18)
        node.length = length7
        node.width = width7
        node.mass = mass7

    elif FOOT_PART_NUM == 4:
        node = mcfg.getNode(LEFT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (-0.05, 0.0, -0.03)
        node = mcfg.getNode(LEFT_TOES_SIDE_R)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0.08, 0.0, 0.1)

        node = mcfg.getNode(RIGHT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0.05, 0.0, -0.03)
        node = mcfg.getNode(RIGHT_TOES_SIDE_R)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (-0.05, 0.0, 0.12)
    elif FOOT_PART_NUM == 3:
        node = mcfg.getNode(LEFT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.02)

        node = mcfg.getNode(RIGHT_TOES)
        node.length = length2
        node.width = width2
        node.mass = mass2
        node.offset = (0, 0.0, -0.02)
    '''
    elif FOOT_PART_NUM == 5:
        node = mcfg.getNode(LEFT_FOOT_SIDE_L)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0.07,0.0,0.015)
        node = mcfg.getNode(LEFT_FOOT_SIDE_R)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (-0.07,0.0,0.015)
            
        node = mcfg.getNode(RIGHT_FOOT_SIDE_L)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0.07,0.0,0.015)
        node = mcfg.getNode(RIGHT_FOOT_SIDE_R)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (-0.07,0.0,0.015)
    '''
    if FOOT_PART_NUM > 1 and FOOT_PART_NUM < 5:
        node = mcfg.getNode(LEFT_TARSUS)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0, 0.0, -0.08)

        node = mcfg.getNode(RIGHT_TARSUS)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node.offset = (0, 0.0, -0.08)

    if FOOT_PART_NUM < 5:
        node = mcfg.getNode(RIGHT_FOOT)
        node.length = length1
        node.width = width1
        node.mass = mass1

        node = mcfg.getNode(LEFT_FOOT)
        node.length = length1
        node.width = width1
        node.mass = mass1

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 30
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    if FOOT_PART_NUM == 1:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 1.,
            LEFT_FOOT: 1.,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.
        }
    elif FOOT_PART_NUM == 3:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3,
            LEFT_TOES: .3,
            RIGHT_TOES: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.5,
            LEFT_FOOT: 2.5,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_TOES: .3,
            RIGHT_TOES: .3
        }
    elif FOOT_PART_NUM == 4:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3,
            LEFT_TOES: .3,
            RIGHT_TOES: .3,
            LEFT_TOES_SIDE_R: .3,
            RIGHT_TOES_SIDE_R: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.5,
            LEFT_FOOT: 2.5,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_TOES: .3,
            RIGHT_TOES: .3,
            LEFT_TOES_SIDE_R: .3,
            RIGHT_TOES_SIDE_R: .3
        }

    elif FOOT_PART_NUM == 5:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3,
            LEFT_METATARSAL_3: .2,
            RIGHT_METATARSAL_3: .2,
            LEFT_PHALANGE_1: .2,
            LEFT_PHALANGE_3: .1,
            RIGHT_PHALANGE_1: .2,
            RIGHT_PHALANGE_3: .2
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.5,
            LEFT_FOOT: 2.5,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_METATARSAL_3: .3,
            RIGHT_METATARSAL_3: .3,
            LEFT_PHALANGE_1: .3,
            LEFT_PHALANGE_3: .3,
            RIGHT_PHALANGE_1: .3,
            RIGHT_PHALANGE_3: .3
        }
    elif FOOT_PART_NUM == 7:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3,
            LEFT_METATARSAL_2: .2,
            LEFT_METATARSAL_3: .2,
            RIGHT_METATARSAL_2: .2,
            RIGHT_METATARSAL_3: .2,
            LEFT_PHALANGE_1: .2,
            LEFT_PHALANGE_2: .2,
            LEFT_PHALANGE_3: .3,
            RIGHT_PHALANGE_1: .2,
            RIGHT_PHALANGE_2: .2,
            RIGHT_PHALANGE_3: .2
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 2.,
            LEFT_FOOT: 2.,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.,
            LEFT_METATARSAL_2: .3,
            LEFT_METATARSAL_3: .3,
            RIGHT_METATARSAL_2: .3,
            RIGHT_METATARSAL_3: .3,
            LEFT_PHALANGE_1: .3,
            LEFT_PHALANGE_2: .3,
            LEFT_PHALANGE_3: .3,
            RIGHT_PHALANGE_1: .3,
            RIGHT_PHALANGE_2: .3,
            RIGHT_PHALANGE_3: .3
        }
    '''
    elif FOOT_PART_NUM == 5:
        config['weightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.3, SPINE1:.3, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.5,
                        RIGHT_UP_LEG:.1, RIGHT_LEG:.3, LEFT_UP_LEG:.1, LEFT_LEG:.3, LEFT_TOES:.3, RIGHT_TOES:.3, LEFT_TARSUS:.3, RIGHT_TARSUS:.3,
                        LEFT_FOOT_SIDE_L:.3, LEFT_FOOT_SIDE_R:.3, RIGHT_FOOT_SIDE_L:.3, RIGHT_FOOT_SIDE_R:.3}
        config['weightMap2']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:1., SPINE1:.3, RIGHT_FOOT:2.5, LEFT_FOOT:2.5, HIP:1.,
                        RIGHT_UP_LEG:1., RIGHT_LEG:1., LEFT_UP_LEG:1., LEFT_LEG:1., LEFT_TOES:.3, RIGHT_TOES:.3, LEFT_TARSUS:.3, RIGHT_TARSUS:.3,
                        LEFT_FOOT_SIDE_L:.3, LEFT_FOOT_SIDE_R:.3, RIGHT_FOOT_SIDE_L:.3, RIGHT_FOOT_SIDE_R:.3}
    '''

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    #config['end'] = 'HIP'
    config['end'] = SPINE1
    config['const'] = HIP
    config['root'] = HIP

    config['FootPartNum'] = FOOT_PART_NUM

    if FOOT_PART_NUM == 7:
        config['FootLPart'] = [
            LEFT_FOOT, LEFT_METATARSAL_2, LEFT_METATARSAL_3, LEFT_PHALANGE_1,
            LEFT_PHALANGE_2, LEFT_PHALANGE_3, LEFT_CALCANEUS
        ]
        config['FootRPart'] = [
            RIGHT_FOOT, RIGHT_METATARSAL_2, RIGHT_METATARSAL_3,
            RIGHT_PHALANGE_1, RIGHT_PHALANGE_2, RIGHT_PHALANGE_3,
            RIGHT_CALCANEUS
        ]
    elif FOOT_PART_NUM == 5:
        config['FootLPart'] = [
            LEFT_FOOT, LEFT_METATARSAL_3, LEFT_PHALANGE_1, LEFT_PHALANGE_3,
            LEFT_CALCANEUS
        ]
        config['FootRPart'] = [
            RIGHT_FOOT, RIGHT_METATARSAL_3, RIGHT_PHALANGE_1, RIGHT_PHALANGE_3,
            RIGHT_CALCANEUS
        ]
    else:
        config['FootLPart'] = [
            LEFT_FOOT, LEFT_TOES, LEFT_TARSUS, LEFT_TOES_SIDE_R,
            LEFT_FOOT_SIDE_L, LEFT_FOOT_SIDE_R
        ]
        config['FootRPart'] = [
            RIGHT_FOOT, RIGHT_TOES, RIGHT_TARSUS, RIGHT_TOES_SIDE_R,
            RIGHT_FOOT_SIDE_L, RIGHT_FOOT_SIDE_R
        ]

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 16
0
    def simulateCallback(frame):
        # seginfo
        segIndex = seg_index[0]
        curState = seginfo[segIndex]['state']
        curInterval = yma.offsetInterval(acc_offset[0], seginfo[segIndex]['interval'])
        stanceLegs = seginfo[segIndex]['stanceHips']
        swingLegs = seginfo[segIndex]['swingHips']
        stanceFoots = seginfo[segIndex]['stanceFoots']
        swingFoots = seginfo[segIndex]['swingFoots']
        swingKnees = seginfo[segIndex]['swingKnees']
        groundHeight = seginfo[segIndex]['ground_height']
#        maxStfPushFrame = seginfo[segIndex]['max_stf_push_frame']
        
        prev_frame = frame-1 if frame>0 else 0
#        prev_frame = frame
        
        # information
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(frame), bodyMasses, upperMass, uppers)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(frame), bodyMasses, upperMass, uppers)
##        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(frame), bodyMasses, totalMass)
##        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(frame), bodyMasses, totalMass)
#        stf_tar = motion_seg.getJointPositionGlobal(stanceFoots[0], frame)
#        CMr_tar = CM_tar - stf_tar

        dCM_tar = motion_seg.getJointVelocityGlobal(0, prev_frame)
        CM_tar = motion_seg.getJointPositionGlobal(0, prev_frame)
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(prev_frame), bodyMasses, upperMass, uppers)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(prev_frame), bodyMasses, upperMass, uppers)
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(prev_frame), bodyMasses, totalMass)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(prev_frame), bodyMasses, totalMass)
        stf_tar = motion_seg.getJointPositionGlobal(stanceFoots[0], prev_frame)
        CMr_tar = CM_tar - stf_tar
            
        dCM = avg_dCM[0]
        CM = controlModel.getJointPositionGlobal(0)
#        CM = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, upperMass, uppers)
#        CM = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, totalMass)
        CMreal = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, totalMass)
        stf = controlModel.getJointPositionGlobal(stanceFoots[0])
        CMr = CM - stf
        
        diff_dCM = mm.projectionOnPlane(dCM-dCM_tar, (1,0,0), (0,0,1))
        diff_dCM_axis = np.cross((0,1,0), diff_dCM)
        rd_vec1[0] = diff_dCM; rd_vecori1[0] = CM_tar
        
        diff_CMr = mm.projectionOnPlane(CMr-CMr_tar, (1,0,0), (0,0,1))
#        rd_vec1[0] = diff_CMr; rd_vecori1[0] = stf_tar
        diff_CMr_axis = np.cross((0,1,0), diff_CMr)
        
        direction = mm.normalize2(mm.projectionOnPlane(dCM_tar, (1,0,0), (0,0,1)))
#        direction = mm.normalize2(mm.projectionOnPlane(dCM, (1,0,0), (0,0,1)))
        directionAxis = np.cross((0,1,0), direction)
        
        diff_dCM_sag, diff_dCM_cor = mm.projectionOnVector2(diff_dCM, direction)
#        rd_vec1[0] = diff_dCM_sag; rd_vecori1[0] = CM_tar
        diff_dCM_sag_axis = np.cross((0,1,0), diff_dCM_sag)
        diff_dCM_cor_axis = np.cross((0,1,0), diff_dCM_cor)
            
        diff_CMr_sag, diff_CMr_cor = mm.projectionOnVector2(diff_CMr, direction)
        diff_CMr_sag_axis = np.cross((0,1,0), diff_CMr_sag)
        diff_CMr_cor_axis = np.cross((0,1,0), diff_CMr_cor)
            
        t = (frame-curInterval[0])/float(curInterval[1]-curInterval[0])
        t_raw = t
        if t>1.: t=1.
        
        
        p_root = motion_stitch[frame].getJointPositionGlobal(0)
        R_root = motion_stitch[frame].getJointOrientationGlobal(0)

        motion_seg_orig.goToFrame(frame)
        motion_seg.goToFrame(frame)
        motion_stitch.goToFrame(frame)
        
        motion_debug1.append(motion_stitch[frame].copy())
        motion_debug1.goToFrame(frame)
        motion_debug2.append(motion_stitch[frame].copy())
        motion_debug2.goToFrame(frame)
        motion_debug3.append(motion_stitch[frame].copy())
        motion_debug3.goToFrame(frame)
        
        # paper implementation
        M_tc.append(motion_stitch[prev_frame])
        M_tc.goToFrame(frame)
        P_hat.append(M_tc[frame].copy())
        P_hat.goToFrame(frame)
        
        p_temp = ym.JointPosture(skeleton)
        p_temp.rootPos = controlModel.getJointPositionGlobal(0)
        p_temp.setJointOrientationsLocal(controlModel.getJointOrientationsLocal())
        P.append(p_temp)
        P.goToFrame(frame)
        
        # stance foot stabilize
        motion_stf_stabilize.append(motion_stitch[frame].copy())
        motion_stf_stabilize.goToFrame(frame)
        if STANCE_FOOT_STABILIZE:
            for stanceFoot in stanceFoots:
                R_target_foot = motion_seg[frame].getJointOrientationGlobal(stanceFoot)
                R_current_foot = motion_stf_stabilize[frame].getJointOrientationGlobal(stanceFoot)
                motion_stf_stabilize[frame].setJointOrientationGlobal(stanceFoot, cm.slerp(R_current_foot, R_target_foot , stf_stabilize_func(t)))
#                R_target_foot = motion_seg[frame].getJointOrientationLocal(stanceFoot)
#                R_current_foot = motion_stf_stabilize[frame].getJointOrientationLocal(stanceFoot)
#                motion_stf_stabilize[frame].setJointOrientationLocal(stanceFoot, cm.slerp(R_current_foot, R_target_foot , stf_stabilize_func(t)))

        # match stance leg 
        motion_match_stl.append(motion_stf_stabilize[frame].copy())
        motion_match_stl.goToFrame(frame)
        if MATCH_STANCE_LEG:
            if curState!=yba.GaitState.STOP:
                for i in range(len(stanceLegs)):
                    stanceLeg = stanceLegs[i]
                    stanceFoot = stanceFoots[i]
                    
#                    # motion stance leg -> character stance leg as time goes
                    R_motion = motion_match_stl[frame].getJointOrientationGlobal(stanceLeg)
                    R_character = controlModel.getJointOrientationGlobal(stanceLeg)
                    motion_match_stl[frame].setJointOrientationGlobal(stanceLeg, cm.slerp(R_motion, R_character, match_stl_func(t)))

#                    t_y = match_stl_func_y(t)
#                    t_xz = match_stl_func(t)
#                    
#                    R_motion = motion_match_stl[frame].getJointOrientationGlobal(stanceLeg)
#                    R_character = controlModel.getJointOrientationGlobal(stanceLeg)
#                    R = np.dot(R_character, R_motion.T)
#                    R_y, R_xz = mm.projectRotation((0,1,0), R)
#                    motion_match_stl[frame].mulJointOrientationGlobal(stanceLeg, mm.scaleSO3(R_xz, t_xz))
#                    motion_match_stl[frame].mulJointOrientationGlobal(stanceLeg, mm.scaleSO3(R_y, t_y))

        # swing foot placement
        motion_swf_placement.append(motion_match_stl[frame].copy())
        motion_swf_placement.goToFrame(frame)
        if SWING_FOOT_PLACEMENT:
            t_swing_foot_placement = swf_placement_func(t);
            
            if extended[0]:
                R_swp_sag = prev_R_swp[0][0]
                R_swp_cor = prev_R_swp[0][1]
            else:
                R_swp_sag = mm.I_SO3(); R_swp_cor = mm.I_SO3()
                R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement))
                if np.dot(direction, diff_CMr_sag) < 0:
                    R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement))
                    R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement))
                else:
                    R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_swp_vel_sag_faster * -t_swing_foot_placement))
                    R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_CMr_sag_axis * K_swp_pos_sag_faster * -t_swing_foot_placement))
                R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement))

            for i in range(len(swingLegs)):
                swingLeg = swingLegs[i]
                swingFoot = swingFoots[i] 
                
                # save swing foot global orientation
#                R_swf = motion_swf_placement[frame].getJointOrientationGlobal(swingFoot)
                
                # rotate swing leg
                motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_sag)
                motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_cor)
                
                # restore swing foot global orientation
#                motion_swf_placement[frame].setJointOrientationGlobal(swingFoot, R_swf)
                
                prev_R_swp[0] = (R_swp_sag, R_swp_cor)

        # swing foot height
        motion_swf_height.append(motion_swf_placement[frame].copy())
        motion_swf_height.goToFrame(frame)
        if SWING_FOOT_HEIGHT:
            for swingFoot in swingFoots:
                stanceFoot = stanceFoots[0]

                # save foot global orientation
                R_foot = motion_swf_height[frame].getJointOrientationGlobal(swingFoot)
                R_stance_foot = motion_swf_height[frame].getJointOrientationGlobal(stanceFoot)

                if OLD_SWING_HEIGHT:
                    height_tar = motion_swf_height[frame].getJointPositionGlobal(swingFoot)[1] - motion_swf_height[frame].getJointPositionGlobal(stanceFoot)[1]
                else:
                    height_tar = motion_swf_height[prev_frame].getJointPositionGlobal(swingFoot)[1] - groundHeight
                    d_height_tar = motion_swf_height.getJointVelocityGlobal(swingFoot, prev_frame)[1]
#                    height_tar += c_swf_mid_offset * swf_height_sine_func(t)
#                motion_debug1[frame] = motion_swf_height[frame].copy()

                # rotate
                motion_swf_height[frame].rotateByTarget(controlModel.getJointOrientationGlobal(0))
#                motion_debug2[frame] = motion_swf_height[frame].copy()
#                motion_debug2[frame].translateByTarget(controlModel.getJointPositionGlobal(0))

                if OLD_SWING_HEIGHT:
                    height_cur = motion_swf_height[frame].getJointPositionGlobal(swingFoot)[1] - motion_swf_height[frame].getJointPositionGlobal(stanceFoot)[1]
                else:
                    height_cur = controlModel.getJointPositionGlobal(swingFoot)[1] - halfFootHeight - c_swf_offset
                    d_height_cur = controlModel.getJointVelocityGlobal(swingFoot)[1]

                if OLD_SWING_HEIGHT:
                    offset_height = (height_tar - height_cur) * swf_height_func(t) * c5
                else:
                    offset_height = ((height_tar - height_cur) * c5
                                     + (d_height_tar - d_height_cur) * c6) * swf_height_func(t)

                offset_sine = c_swf_mid_offset * swf_height_sine_func(t)
#                offset_sine = 0.
                
                offset = 0.
                offset += offset_height
                offset += offset_sine

                if offset > 0.:
                    newPosition =  motion_swf_height[frame].getJointPositionGlobal(swingFoot)
                    newPosition[1] += offset
                    aik.ik_analytic(motion_swf_height[frame], swingFoot, newPosition)
                else:
                    if HIGHER_OFFSET:
                        newPosition =  motion_swf_height[frame].getJointPositionGlobal(stanceFoot)
                        newPosition[1] -= offset
                        aik.ik_analytic(motion_swf_height[frame], stanceFoot, newPosition)

                # return
#                motion_debug3[frame] = motion_swf_height[frame].copy()
#                motion_debug3[frame].translateByTarget(controlModel.getJointPositionGlobal(0))
                motion_swf_height[frame].rotateByTarget(R_root)
                
                # restore foot global orientation
                motion_swf_height[frame].setJointOrientationGlobal(swingFoot, R_foot)
                motion_swf_height[frame].setJointOrientationGlobal(stanceFoot, R_stance_foot)

                if plot!=None:
                    plot.addDataPoint('debug1', frame, offset_height)
                    plot.addDataPoint('debug2', frame, height_tar - height_cur)
#                    plot.addDataPoint('diff', frame, diff)


        # swing foot orientation
        motion_swf_orientation.append(motion_swf_height[frame].copy())
        motion_swf_orientation.goToFrame(frame)
        if SWING_FOOT_ORIENTATION:
            swf_orientation_func = yfg.concatenate([yfg.zero, yfg.hermite2nd, yfg.one], [.25, .75])
            for swingFoot in swingFoots:
                R_target_foot = motion_seg[curInterval[1]].getJointOrientationGlobal(swingFoot)
                R_current_foot = motion_swf_orientation[frame].getJointOrientationGlobal(swingFoot)
                motion_swf_orientation[frame].setJointOrientationGlobal(swingFoot, cm.slerp(R_current_foot, R_target_foot, swf_orientation_func(t)))
#    swf_stabilize_func = yfg.concatenate([yfg.hermite2nd, yfg.one], [c_taking_duration])
            # push orientation
#            for swingFoot in swingFoots:
#                R_target_foot = motion_seg[frame].getJointOrientationGlobal(swingFoot)
#                R_current_foot = motion_swf_orientation[frame].getJointOrientationGlobal(swingFoot)
#                motion_swf_orientation[frame].setJointOrientationGlobal(swingFoot, cm.slerp(R_current_foot, R_target_foot , swf_stabilize_func(t)))
            
        # stance foot push                
        motion_stf_push.append(motion_swf_orientation[frame].copy())
        motion_stf_push.goToFrame(frame)
        if STANCE_FOOT_PUSH:
            for swingFoot in swingFoots:
#                max_t = (maxStfPushFrame)/float(curInterval[1]-curInterval[0])
#                stf_push_func = yfg.concatenate([yfg.sine, yfg.zero], [max_t*2])
                stf_push_func = yfg.concatenate([yfg.sine, yfg.zero], [c_taking_duration*2])
                
                R_swp_sag = mm.I_SO3()
#                R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_stp_vel * -stf_push_func(t)))
                
#                if step_length_cur[0] < step_length_tar[0]:
#                    ratio = step_length_cur[0] / step_length_tar[0]
#                    R_max = maxmaxStfPushFrame
#                    R_zero = 
                R_swp_sag = np.dot(R_swp_sag, mm.exp((step_length_tar[0] - step_length_cur[0])*step_axis[0] * K_stp_pos * -stf_push_func(t)))
                    
                motion_stf_push[frame].mulJointOrientationGlobal(swingFoot, R_swp_sag)
                
        # stance foot balancing 
        motion_stf_balancing.append(motion_stf_push[frame].copy())
        motion_stf_balancing.goToFrame(frame)
        if STANCE_FOOT_BALANCING:
            R_stb = mm.exp(diff_dCM_axis * K_stb_vel * stf_balancing_func(t))
            R_stb = np.dot(R_stb, mm.exp(diff_CMr_axis * K_stb_pos * stf_balancing_func(t)))
            for stanceFoot in stanceFoots:
                if frame < 5: continue
                motion_stf_balancing[frame].mulJointOrientationGlobal(stanceFoot, R_stb)
                    
        # control trajectory
        motion_control.append(motion_stf_balancing[frame].copy())
        motion_control.goToFrame(frame)
        
        #=======================================================================
        # tracking with inverse dynamics
        #=======================================================================
        th_r = motion_control.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion_control.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion_control.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt)

        #=======================================================================
        # simulation
        #=======================================================================
        CP = mm.v3(0.,0.,0.)
        F = mm.v3(0.,0.,0.)
        avg_dCM[0] = mm.v3(0.,0.,0.)
        
        # external force rendering info
        del rd_forces[:]; del rd_force_points[:]
        for fi in forceInfos:
            if fi.startFrame <= frame and frame < fi.startFrame + fi.duration*(1/frameTime):
                rd_forces.append(fi.force)
                rd_force_points.append(controlModel.getBodyPositionGlobal(fi.targetBody)  + -mm.normalize2(fi.force)*.2)
                    
        for i in range(stepsPerFrame):
            
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals, contactForces)
            
            # apply external force
            for fi in forceInfos:
                if fi.startFrame <= frame and frame < fi.startFrame + fi.duration*(1/frameTime):
                    controlModel.applyBodyForceGlobal(fi.targetBody, fi.force)
                                
            controlModel.setDOFAccelerations(ddth_des)
            controlModel.solveHybridDynamics()
            
#            # apply external force
#            for fi in forceInfos:
#                if fi.startFrame <= frame and frame < fi.startFrame + fi.duration*(1/frameTime):
#                    controlModel.applyBodyForceGlobal(fi.targetBody, fi.force)
            
            vpWorld.step()
#            yvu.align2D(controlModel)

            if len(contactForces) > 0:
                CP += yrp.getCP(contactPositions, contactForces)
                F += sum(contactForces)
            avg_dCM[0] += controlModel.getJointVelocityGlobal(0)
#            avg_dCM[0] += yrp.getCM(controlModel.getJointVelocitiesGlobal(), bodyMasses, upperMass, uppers)
#            avg_dCM[0] += yrp.getCM(controlModel.getJointVelocitiesGlobal(), bodyMasses, totalMass)

#            if len(stanceFoots)>0:
#                avg_stf_v[0] += controlModel.getJointVelocityGlobal(stanceFoots[0])
#                avg_stf_av[0] += controlModel.getJointAngVelocityGlobal(stanceFoots[0])
        
        CP /= stepsPerFrame
        F /= stepsPerFrame
        avg_dCM[0] /= stepsPerFrame
        
#        if len(stanceFoots)>0:
#            avg_stf_v[0] /= stepsPerFrame
#            avg_stf_av[0] /= stepsPerFrame
#            rd_vec1[0] = avg_stf_av[0]; rd_vec1[0][0] = 0.; rd_vec1[0][2] = 0.
#            rd_vecori1[0]= controlModel.getJointPositionGlobal(stanceFoots[0])

        #=======================================================================
        # segment editing
        #=======================================================================
        lastFrame = False
        
        if SEGMENT_EDITING:
            if curState==yba.GaitState.STOP:
                if frame == len(motion_seg)-1:
                    lastFrame = True
                    
            elif (curState==yba.GaitState.LSWING or curState==yba.GaitState.RSWING) and t>c_min_contact_time:
                swingID = lID if curState==yba.GaitState.LSWING else rID

                contact = False
                if swingID in bodyIDs:
                    minContactVel = 1000.
                    for i in range(len(bodyIDs)):
                        if bodyIDs[i]==swingID:
                            vel = controlModel.getBodyVelocityGlobal(swingID, contactPositionLocals[i])
                            vel[1] = 0
                            contactVel = mm.length(vel)
                            if contactVel < minContactVel: minContactVel = contactVel 
                    if minContactVel < c_min_contact_vel: contact = True
                
                extended[0] = False
                
                if contact:
#                    print frame, 'foot touch'
                    lastFrame = True
                    acc_offset[0] += frame - curInterval[1]
                    
                elif frame == len(motion_seg)-1:
                    print frame, 'extend frame', frame+1
                    
                    preserveJoints = []
#                    preserveJoints = [lFoot, rFoot]
#                    preserveJoints = [lFoot, rFoot, lKnee, rKnee]
#                    preserveJoints = [lFoot, rFoot, lKnee, rKnee, lUpLeg, rUpLeg]
                    stanceKnees = [rKnee] if curState==yba.GaitState.LSWING else [lKnee]   
                    preserveJoints = [stanceFoots[0], stanceKnees[0], stanceLegs[0]]
   
                    diff = 3
                    motion_seg_orig.extend([motion_seg_orig[-1]])
                    motion_seg.extend(ymt.extendByIntegration_root(motion_seg, 1, diff))
                    
                    motion_stitch.extend(ymt.extendByIntegration_constant(motion_stitch, 1, preserveJoints, diff))

#                    # extend for swing foot ground speed matching & swing foot height lower
##                    extendedPostures = ymt.extendByIntegration(motion_stitch, 1, preserveJoints, diff)
##                    extendedPostures = [motion_stitch[-1]] 
##
#                    extendFrameNum = frame - curInterval[1] + 1
#                    k = 1.-extendFrameNum/5.
#                    if k<0.: k=0.
#                    extendedPostures = ymt.extendByIntegrationAttenuation(motion_stitch, 1, preserveJoints, diff, k)
#
##                    if len(swingFoots)>0 and np.inner(dCM_tar, dCM)>0.:
##                        print frame, 'speed matching'
##                        R_swf = motion_stitch[-1].getJointOrientationGlobal(swingFoots[0])
##                        
##                        p_swf = motion_stitch[-1].getJointPositionGlobal(swingFoots[0])
##                        v_swf = motion_stitch.getJointVelocityGlobal(swingFoots[0], frame-diff, frame)
##                        a_swf = motion_stitch.getJointAccelerationGlobal(swingFoots[0], frame-diff, frame)
##                        p_swf += v_swf * (frameTime) + a_swf * (frameTime)*(frameTime)
##                        aik.ik_analytic(extendedPostures[0], swingFoots[0], p_swf)
##                        
##                        extendedPostures[0].setJointOrientationGlobal(swingFoots[0], R_swf)
#
#                    motion_stitch.extend(extendedPostures)
                    
                    extended[0] = True
        else:
            if frame == len(motion_seg)-1: lastFrame = True
                    
        if lastFrame:
            if segIndex < len(segments)-1:
                print '%d (%d): end of %dth seg (%s, %s)'%(frame, frame-curInterval[1],segIndex, yba.GaitState.text[curState], curInterval)
                if plot!=None: plot.addDataPoint('diff', frame, (frame-curInterval[1])*.01)
                
                if len(stanceFoots)>0 and len(swingFoots)>0:
#                    step_cur = controlModel.getJointPositionGlobal(swingFoots[0]) - controlModel.getJointPositionGlobal(stanceFoots[0])
#                    step_tar = motion_seg[curInterval[1]].getJointPositionGlobal(swingFoots[0]) - motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
                    step_cur = controlModel.getJointPositionGlobal(0) - controlModel.getJointPositionGlobal(stanceFoots[0])
                    step_tar = motion_seg[curInterval[1]].getJointPositionGlobal(0) - motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
                    
                    step_cur = mm.projectionOnPlane(step_cur, (1,0,0), (0,0,1))
                    step_tar = mm.projectionOnPlane(step_tar, (1,0,0), (0,0,1))
                    
                    step_cur_sag, step_cur_cor = mm.projectionOnVector2(step_cur, direction)
                    step_tar_sag, step_tar_cor = mm.projectionOnVector2(step_tar, direction)
                    
                    step_length_tar[0] = mm.length(step_tar_sag)
                    if np.inner(step_tar_sag, step_cur_sag) > 0:
                        step_length_cur[0] = mm.length(step_cur_sag)
                    else:
                        step_length_cur[0] = -mm.length(step_cur_sag)
                    
                    step_axis[0] = directionAxis
                    
#                    rd_vec1[0] = step_tar_sag
#                    rd_vecori1[0] = motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
#                    rd_vec2[0] = step_cur_sag
#                    rd_vecori2[0] = controlModel.getJointPositionGlobal(stanceFoots[0])

                seg_index[0] += 1
                curSeg = segments[seg_index[0]]
                stl_y_limit_num[0] = 0
                stl_xz_limit_num[0] = 0
                
                del motion_seg_orig[frame+1:]
                motion_seg_orig.extend(ymb.getAttachedNextMotion(curSeg, motion_seg_orig[-1], False, False))
                
                del motion_seg[frame+1:]
                del motion_stitch[frame+1:]
                transitionLength = len(curSeg)-1

#                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, motion_seg[-1], False, False))
#                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, motion_control[-1], transitionLength, stitch_func, True, False))

                d = motion_seg[-1] - curSeg[0]
                d.rootPos[1] = 0.
                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, d, True, False))
                d = motion_control[-1] - curSeg[0]
                d.rootPos[1] = 0.
                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, d, transitionLength, stitch_func, True, False))
                
#                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, motion_seg[-1], False, True))
#                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, motion_control[-1], transitionLength, stitch_func, True, True))
            else:
                motion_seg_orig.append(motion_seg_orig[-1])
                motion_seg.append(motion_seg[-1])
                motion_stitch.append(motion_control[-1])
                
                
        # rendering
        motionModel.update(motion_ori[frame])
#        motionModel.update(motion_seg[frame])
        
        rd_CP[0] = CP
        rd_CMP[0] = (CMreal[0] - (F[0]/F[1])*CMreal[1], 0, CMreal[2] - (F[2]/F[1])*CMreal[1])
        
        if plot!=None:
            plot.addDataPoint('zero', frame, 0)
            plot.updatePoints()
Ejemplo n.º 17
0
def main():

    np.set_printoptions(precision=4, linewidth=200)

    #motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()
    mcfg_motion = mit.normal_mcfg()

    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    motionModel.recordVelByFiniteDiff()
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)

    footPartNum = config['FootPartNum']

    if footPartNum > 1:
        elasticity = 2000
        damping = 2 * (elasticity**.5)

        springBody1 = 5
        springBody2 = 6
        springBody1Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        springBody2Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))

        initialDist = mm.length(springBody1Pos - springBody2Pos) * 1.
        node = mcfg.getNode(mit.LEFT_PHALANGE_1)
        initialDist -= node.width  #0.084
        v1 = (-node.width * 0.5, 0.0, node.length * 0.4)
        v2 = (node.width * 0.5, 0.0, node.length * 0.4)
        controlModel.setSpring(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]),
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]),
            elasticity, damping, v2, v1, initialDist)
        controlModel.setSpring(
            motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]),
            motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]),
            elasticity, damping, v1, v2, initialDist)

        #elasticity = 10
        #damping = 2*(elasticity**.5)
        #springBody1 = 3
        #springBody2 = 4
        #node = mcfg.getNode(mit.LEFT_PHALANGE_1)
        #springBody1Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        #springBody2Pos = motionModel.getBodyPositionGlobal(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))
        #initialDist = mm.length(springBody1Pos - springBody2Pos)*1.
        #initialDist -= node.width#0.084
        #v1 = (-node.width*0.5,0.0,-node.length*0.4)
        #v2 = (node.width*0.5,0.0,-node.length*0.4)
        ##controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
        ##controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)

    vpWorld.initialize()
    controlModel.initializeHybridDynamics()

    #ModelOffset = (1.5, -0.01, 0)
    ModelOffset = (1.5, 0.04, 0)
    controlModel.translateByOffset(ModelOffset)

    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()

    # parameter
    Kt = config['Kt']
    Dt = config['Dt']  # tracking gain
    Kl = config['Kl']
    Dl = config['Dl']  # linear balance gain
    Kh = config['Kh']
    Dh = config['Dh']  # angular balance gain
    Ks = config['Ks']
    Ds = config['Ds']  # penalty force spring gain

    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']

    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w2 = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap2'])
    #w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL = motion[0].skeleton.getJointIndex(config['supLink'])
    supR = motion[0].skeleton.getJointIndex(config['supLink2'])
    rootB = motion[0].skeleton.getJointIndex(config['root'])

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex(config['const'])

    # jacobian
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()

    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    Jcom = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcom = Jcom.copy()

    JcomAng = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcomAng = JcomAng.copy()

    ###############

    indexFootL = [None] * footPartNum
    indexFootR = [None] * footPartNum
    jFootL = [None] * footPartNum
    dJFootL = [None] * footPartNum
    jFootR = [None] * footPartNum
    dJFootR = [None] * footPartNum
    jointMasksFootL = [None] * footPartNum
    jointMasksFootR = [None] * footPartNum

    for i in range(footPartNum):
        jFootL[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootL[i] = jFootL[i].copy()
        jFootR[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootR[i] = jFootR[i].copy()

        indexFootL[i] = motion[0].skeleton.getJointIndex(
            config['FootLPart'][i])
        indexFootR[i] = motion[0].skeleton.getJointIndex(
            config['FootRPart'][i])

        jointMasksFootL[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootL[i])
        ]
        jointMasksFootR[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootR[i])
        ]

    constJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton,
                              [indexFootL[0], indexFootR[0]])
    ]
    #constJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [indexFootL[0]])]
    #constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)

    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks = [
        yjc.getLinkJointMask(motion[0].skeleton, selectedBody)
    ]
    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks[0][0] = 0
    #comUpperJointMasks[0][1] = 1
    #comUpperJointMasks[0][10] = 1
    comUpperJointMasks[0][2] = 1
    comUpperJointMasks[0][11] = 1

    #print(comUpperJointMasks)

    comLowerJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton, [
            motion[0].skeleton.getJointIndex('LeftLeg'),
            motion[0].skeleton.getJointIndex('RightLeg')
        ])
    ]
    '''
    maskArray = [foreSupLJointMasks, foreSupRJointMasks, rearSupLJointMasks, rearSupRJointMasks]
    parentArray = [supL, supR, supL, supR]
    effectorArray = [foreSupL, foreSupR, rearSupL, rearSupR]
    for j in range(4) :
        for i in range(len(foreSupLJointMasks)) :
            if i == parentArray[j] or i == effectorArray[j] :
                maskArray[j][0][i] = 1
            else :
                maskArray[j][0][i] = 0
    '''

    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses)
    dTO = ymt.make_dTO(len(linkMasses))

    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0, 0, 0, 0, 0, 0)  #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0, 0, 0, 0, 0, 0]  #R
    a_sup_2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    CP_old = [mm.v3(0., 0., 0.)]

    # penalty method
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.] * len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)

    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM_ref = [None]
    rd_CM_des = [None]
    rd_CM = [None]
    rd_CM_vec = [None]
    rd_CM_ref_vec = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    rd_footCenter_des = [None]
    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]

    rd_root = [None]

    rd_footL_vec = [None]
    rd_footR_vec = [None]

    rd_CMP = [None]

    rd_DesPosL = [None]
    rd_DesPosR = [None]

    rd_DesForePosL = [None]
    rd_DesForePosR = [None]
    rd_DesRearPosL = [None]
    rd_DesRearPosR = [None]

    rd_Joint = [None]
    rd_Joint2 = [None]
    rd_Joint3 = [None]
    rd_Joint4 = [None]
    rd_desPoints = [None]

    rd_contactForces = [None]
    rd_contactPositions = [None]

    #rd_contactForces = [None]*10000
    #rd_contactPositions = [None]*10000
    rd_virtualForce = [None]

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0, 0, 0]

    normalVector = [[0, 2, 0]]

    if MULTI_VIEWER:
        viewer = ymv.MultiViewer(800, 655)
        #viewer = ymv.MultiViewer(1600, 1255)
        viewer.setRenderers1([
            cvr.VpModelRenderer(motionModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])
        viewer.setRenderers2([
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])

    else:
        viewer = ysv.SimpleViewer()
        #    viewer.record(False)
        #    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
        viewer.doc.addObject('motion', motion)
        viewer.doc.addRenderer(
            'motionModel',
            cvr.VpModelRenderer(motionModel, (100, 100, 100),
                                yr.POLYGON_FILL))  #(150,150,255)
        viewer.doc.addRenderer(
            'controlModel',
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR,
                                yr.POLYGON_FILL))
        #viewer.doc.addRenderer('controlModel', cvr.VpModelRenderer(controlModel, CHARACTER_COLOR, yr.POLYGON_LINE))
        #viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))
        #viewer.doc.addRenderer('rd_footCenter_des', yr.PointsRenderer(rd_footCenter_des, (150,0,150))    )
        #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))
        #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
        viewer.doc.addRenderer('rd_CM_plane',
                               yr.PointsRenderer(rd_CM_plane, (255, 255, 0)))
        viewer.doc.addRenderer('rd_CM',
                               yr.PointsRenderer(rd_CM, (255, 0, 255)))
        viewer.doc.addRenderer('rd_CM_des',
                               yr.PointsRenderer(rd_CM_des, (64, 64, 255)))
        viewer.doc.addRenderer(
            'rd_CM_vec',
            yr.VectorsRenderer(rd_CM_vec, rd_CM_plane, (255, 0, 0), 3))
        #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (0,255,0)))
        viewer.doc.addRenderer('rd_CP_des',
                               yr.PointsRenderer(rd_CP_des, (255, 0, 128)))
        #    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
        #    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
        #viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP, (0,255,255), .001))

        viewer.doc.addRenderer(
            'rd_exf_des',
            yr.ForcesRenderer(rd_exf_des, rd_root_des, (0, 255, 0), .009,
                              0.04))

        #viewer.doc.addRenderer('rd_CMP', yr.PointsRenderer(rd_CMP, (0,0,255)))

        #viewer.doc.addRenderer('rd_DesPosL', yr.PointsRenderer(rd_DesPosL, (0,0,255)))
        #viewer.doc.addRenderer('rd_DesPosR', yr.PointsRenderer(rd_DesPosR, (0,100,255)))

        #viewer.doc.addRenderer('rd_DesForePosL', yr.PointsRenderer(rd_DesForePosL, (150,0,200)))
        #viewer.doc.addRenderer('rd_DesForePosR', yr.PointsRenderer(rd_DesForePosR, (150,0,250)))
        #viewer.doc.addRenderer('rd_DesRearPosL', yr.PointsRenderer(rd_DesRearPosL, (0,150,200)))
        #viewer.doc.addRenderer('rd_DesRearPosR', yr.PointsRenderer(rd_DesRearPosR, (0,150,250)))

        #viewer.doc.addRenderer('softConstraint', yr.VectorsRenderer(rd_soft_const_vec, rd_CMP, (150,100,100), 3))

        #viewer.doc.addRenderer('rd_footLVec', yr.VectorsRenderer(rd_footL_vec, rd_footCenterL, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_footRVec', yr.VectorsRenderer(rd_footR_vec, rd_footCenterR, (255,255,0), 3))

        #viewer.doc.addRenderer('rd_footCenter_ref', yr.PointsRenderer(rd_footCenter_ref))
        #viewer.doc.addRenderer('rd_CM_plane_ref', yr.PointsRenderer(rd_CM_plane_ref, (255,255,0)))

        #viewer.doc.addRenderer('rd_refNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter_ref, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_refCMVec', yr.VectorsRenderer(rd_CM_ref_vec, rd_footCenter_ref, (255,0,255), 3))

        #viewer.doc.addRenderer('rd_curNormalVec', yr.VectorsRenderer(normalVector, rd_footCenter, (255,0,0), 3))
        #viewer.doc.addRenderer('rd_CMVec', yr.VectorsRenderer(rd_CM_vec, rd_footCenter, (255,0,255), 3))

        viewer.doc.addRenderer(
            'rd_contactForces',
            yr.VectorsRenderer(rd_contactForces, rd_contactPositions,
                               (0, 255, 0), .1))

        #viewer.doc.addRenderer('rd_virtualForce', yr.ForcesRenderer(rd_virtualForce, rd_CM, (50,255,0), 0.5, 0.02))

        #viewer.doc.addRenderer('rd_Joint', yr.PointsRenderer(rd_Joint, (255,0,0)))
        #viewer.doc.addRenderer('rd_Joint2', yr.PointsRenderer(rd_Joint2, (0,255,0)))
        #viewer.doc.addRenderer('rd_Joint3', yr.PointsRenderer(rd_Joint3, (0,0,255)))
        #viewer.doc.addRenderer('rd_Joint4', yr.PointsRenderer(rd_Joint4, (255,255,0)))

        #viewer.doc.addRenderer('rd_desPoints', yr.PointsRenderer(rd_desPoints, (255,0,0)))

    stage = STATIC_BALANCING

    contactRendererName = []

    #for i in range (motion[0].skeleton.getJointNum()):
    #    print(i, motion[0].skeleton.getJointName(i))
    print "(index, id, name)"
    for i in range(controlModel.getBodyNum()):
        print(i, controlModel.index2id(i), controlModel.index2name(i))

    desCOMOffset = 0.0

    pt = [0.]

    timeReport = [0.] * 7

    viewer.objectInfoWnd.comOffsetY.value(-0.05)
    viewer.objectInfoWnd.comOffsetZ.value(0.00)

    viewer.objectInfoWnd.begin()
    viewer.objectInfoWnd.Bc = Fl_Value_Input(100, 450, 40, 10, 'Bc')
    viewer.objectInfoWnd.Bc.value(0.1)
    viewer.objectInfoWnd.end()
    viewer.objectInfoWnd.labelKt.value(50)
    viewer.objectInfoWnd.labelKk.value(17)

    def simulateCallback(frame):
        print "main:frame : ", frame

        curTime = time.time()

        if frame % 30 == 1: pt[0] = time.time()

        global g_initFlag
        global forceShowFrame
        global forceApplyFrame
        global JsysPre
        global JsupPreL
        global JsupPreR
        global JsupPre
        global softConstPoint
        global stage
        global contactRendererName
        global desCOMOffset

        motionModel.update(motion[0])

        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, B_CM, B_CMSd, B_Toe = viewer.GetParam(
        )

        Dt = 2 * (Kt**.5)
        Dk = 2 * (Kk**.5)
        Dl = 2 * (Kl**.5)
        Dh = 2 * (Kh**.5)
        Dsc = 2 * (Ksc**.5)

        # tracking
        th_r_ori = motion.getDOFPositions(frame)
        th_r = copy.copy(th_r_ori)

        ############################
        #Reference motion modulation

        dCM_k = 10.
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        dCM_plane = copy.copy(dCM)
        dCM_plane[1] = 0.

        global leftHipTimer
        if viewer.objectInfoWnd.onLeftHip:
            leftHipTimer = 60
            viewer.objectInfoWnd.onLeftHip = False
        if leftHipTimer > 0:
            viewer.objectInfoWnd.comOffsetX.value(
                0.08 * np.sin(2 * 3.14 * leftHipTimer / 60.))
            #viewer.objectInfoWnd.comOffsetZ.value(0.04*np.cos(2*3.14*leftHipTimer/90.))
            #B_Hipd = viewer.objectInfoWnd.labelLeftHip.value()
            #newR1 = mm.exp(mm.v3(0.0,1.0,0.0), 3.14*0.5*B_Hipd/100.)
            #idx = motion[0].skeleton.getJointIndex('LeftUpLeg')
            #th_r[idx] = np.dot(th_r[idx], newR1)
            #idx = motion[0].skeleton.getJointIndex('RightUpLeg')
            #th_r[idx] = np.dot(th_r[idx], newR1)
            leftHipTimer -= 1

        timeReport[0] += time.time() - curTime
        curTime = time.time()

        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r,
                                                  Kt, Dt)
        ddth_c = controlModel.getDOFAccelerations()

        ype.flatten(ddth_des, ddth_des_flat)
        ype.flatten(dth, dth_flat)

        ype.flatten(ddth_c, ddth_c_flat)

        # jacobian
        refFootL = motionModel.getBodyPositionGlobal(supL)
        refFootR = motionModel.getBodyPositionGlobal(supR)

        positionFootL = [None] * footPartNum
        positionFootR = [None] * footPartNum
        for i in range(footPartNum):
            positionFootL[i] = controlModel.getBodyPositionGlobal(
                indexFootL[i])
            positionFootR[i] = controlModel.getBodyPositionGlobal(
                indexFootR[i])

        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()

        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        CM_plane = copy.copy(CM)
        CM_plane[1] = 0.
        dCM_plane = copy.copy(dCM)
        dCM_plane[1] = 0.

        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        linkVelocities_ref = motionModel.getBodyVelocitiesGlobal()
        linkAngVelocities_ref = motionModel.getBodyAngVelocitiesGlobal()
        linkInertias_ref = motionModel.getBodyInertiasGlobal()

        CM_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        CM_plane_ref = copy.copy(CM_ref)
        CM_plane_ref[1] = 0.

        P = ymt.getPureInertiaMatrix(TO, linkMasses, linkPositions, CM,
                                     linkInertias)
        dP = ymt.getPureInertiaMatrixDerivative(dTO, linkMasses,
                                                linkVelocities, dCM,
                                                linkAngVelocities,
                                                linkInertias)

        timeReport[1] += time.time() - curTime
        curTime = time.time()

        yjc.computeJacobian2(Jsys, DOFs, jointPositions, jointAxeses,
                             linkPositions, allLinkJointMasks)
        timeReport[2] += time.time() - curTime
        curTime = time.time()

        # yjc.computeJacobianDerivative2(dJsys, DOFs, jointPositions, jointAxeses, linkAngVelocities, linkPositions, allLinkJointMasks)
        if frame > 0:
            dJsys = (Jsys - JsysPre) * 30.
        else:
            dJsys = (Jsys - Jsys)
        JsysPre = Jsys.copy()

        timeReport[3] += time.time() - curTime
        curTime = time.time()

        lcpBodyIDs, lcpContactPositions, lcpContactPositionLocals, lcpContactForces = hls.calcLCPForces(
            motion, vpWorld, controlModel, bodyIDsToCheck, 1., 4, None)
        # bodyIDs : IDs for Virtual Physics, not VpModel !!!
        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
            bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)
        if (CP is not None):
            CP[1] = 0.

        for i in range(controlModel.getBodyNum()):
            controlModel.SetBodyColor(bodyIDsToCheck[i], 0, 0, 0, 255)

        contactFlagFootL = [0] * footPartNum
        contactFlagFootR = [0] * footPartNum

        for i in range(len(bodyIDs)):
            controlModel.SetBodyColor(bodyIDs[i], 255, 105, 105, 200)
            index = controlModel.id2index(bodyIDs[i])
            for j in range(len(indexFootL)):
                if index == indexFootL[j]:
                    contactFlagFootL[j] = 1
            for j in range(len(indexFootR)):
                if index == indexFootR[j]:
                    contactFlagFootR[j] = 1

        for j in range(0, footPartNum):
            jFootR[j] = Jsys[6 * indexFootR[j]:6 * indexFootR[j] + 6]  #.copy()
            jFootL[j] = Jsys[6 * indexFootL[j]:6 * indexFootL[j] + 6]  #.copy()
            dJFootR[j] = dJsys[6 * indexFootR[j]:6 * indexFootR[j] +
                               6]  #.copy()
            dJFootL[j] = dJsys[6 * indexFootL[j]:6 * indexFootL[j] +
                               6]  #.copy()
        if footPartNum == 1:
            desFCL = (controlModel.getBodyPositionGlobal(supL))
            desFCR = (controlModel.getBodyPositionGlobal(supR))
        else:
            r = .5 + desCOMOffset
            desFCL = (controlModel.getBodyPositionGlobal(indexFootL[0]) * r +
                      controlModel.getBodyPositionGlobal(indexFootL[1]) *
                      (1.0 - r)
                      )  #controlModel.getBodyPositionGlobal(indexFootL[1])
            desFCR = (controlModel.getBodyPositionGlobal(indexFootR[0]) * r +
                      controlModel.getBodyPositionGlobal(indexFootR[1]) *
                      (1.0 - r)
                      )  #controlModel.getBodyPositionGlobal(indexFootR[1])
        desFC = desFCL + (desFCR - desFCL) / 2.0
        desFC[1] = 0
        rd_footCenter_des[0] = desFC.copy()
        curRelCMVec = CM_plane - desFC
        vecRatio = mm.length(curRelCMVec) * 0.
        #print(frame, vecRatio)
        footCenter = desFC - curRelCMVec * (vecRatio)  #/10.0

        footCenter = (
            getBodyGlobalPos(controlModel, motion, 'LeftCalcaneus_1') +
            getBodyGlobalPos(controlModel, motion, 'LeftPhalange_1') +
            getBodyGlobalPos(controlModel, motion, 'RightCalcaneus_1') +
            getBodyGlobalPos(controlModel, motion, 'RightPhalange_1')) / 4.
        #footCenter = (getBodyGlobalPos(controlModel, motion, 'LeftCalcaneus_1') + getBodyGlobalPos(controlModel, motion, 'LeftTalus_1') + getBodyGlobalPos(controlModel, motion, 'RightCalcaneus_1') + getBodyGlobalPos(controlModel, motion, 'RightTalus_1'))/4.

        footCenter_ref = refFootL + (refFootR - refFootL) / 2.0
        #footCenter_ref[1] = 0.
        footCenter[1] = 0.
        footCenterOffset = np.array([
            viewer.objectInfoWnd.comOffsetX.value(), 0,
            viewer.objectInfoWnd.comOffsetZ.value()
        ])
        #footCenter += footCenterOffset

        vecRatio = mm.length(curRelCMVec) * 0.
        softConstPointOffset = -curRelCMVec * (vecRatio)  #/10.0
        #print(frame, vecRatio, softConstPointOffset)

        desForeSupLAcc = [0, 0, 0]
        desForeSupRAcc = [0, 0, 0]

        totalNormalForce = [0, 0, 0]

        for i in range(len(contactForces)):
            totalNormalForce[0] += contactForces[i][0]
            totalNormalForce[1] += contactForces[i][1]
            totalNormalForce[2] += contactForces[i][2]

        #print((totalMass*mm.s2v(wcfg.gravity))[1])

        footCenterOffset = np.array([
            viewer.objectInfoWnd.comOffsetX.value(),
            viewer.objectInfoWnd.comOffsetY.value(),
            viewer.objectInfoWnd.comOffsetZ.value()
        ])

        ######################
        # optimization terms
        ######################

        # linear momentum
        CM_ref_plane = footCenter + footCenterOffset
        dL_des_plane = Kl * totalMass * (CM_ref_plane -
                                         CM_plane) - Dl * totalMass * dCM_plane
        dL_des_plane[1] = Kl * totalMass * (CM_ref[1] + footCenterOffset[1] -
                                            CM[1]) - Dl * totalMass * dCM[1]
        #dL_des_plane[1] = 0.
        #print 'dL_des_plane', dL_des_plane

        # angular momentum
        CP_ref = footCenter + footCenterOffset
        CP_ref[1] = 0.

        timeStep = 30.
        if (CP_old[0] is None) or (CP is None):
            dCP = None
        else:
            dCP = (CP - CP_old[0]) * timeStep
        CP_old[0] = CP

        if (CP is not None) and (dCP is not None):
            ddCP_des = Kh * (CP_ref - CP) - Dh * (dCP)
            CP_des = CP + dCP * (1 / timeStep) + .5 * ddCP_des * (
                (1 / timeStep)**2)
            #print 'dCP: ', dCP
            #print 'ddCP_des: ', ddCP_des
            #print 'CP_des: ', CP_des
            #dH_des = np.cross((CP_des - CM), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))
            dH_des = np.cross(
                (CP_des - CM_plane),
                (dL_des_plane + totalMass * mm.s2v(wcfg.gravity)))
        else:
            dH_des = None

        # momentum matrix
        RS = np.dot(P, Jsys)
        R, S = np.vsplit(RS, 2)

        rs = np.dot((np.dot(dP, Jsys) + np.dot(P, dJsys)), dth_flat)
        r_bias, s_bias = np.hsplit(rs, 2)

        flagContact = True
        if (dH_des is None) or np.any(np.isnan(dH_des)) == True:
            flagContact = False
            #viewer.doc.showRenderer('rd_grf_des', False)
            #viewer.motionViewWnd.update(1, viewer.doc)
        #else:
        #viewer.doc.showRenderer('rd_grf_des', True)
        #viewer.motionViewWnd.update(1, viewer.doc)
        '''
        0 : initial
        1 : contact
        2 : fly
        3 : landing
        '''

        #MOTION = FORWARD_JUMP
        if mit.MOTION == mit.FORWARD_JUMP:
            frame_index = [136, 100]
            #frame_index = [100000, 100000]
        elif mit.MOTION == mit.TAEKWONDO:
            frame_index = [130, 100]
            #frame_index = [100000, 100000]
        elif mit.MOTION == mit.TAEKWONDO2:
            frame_index = [130 + 40, 100]
        elif mit.MOTION == mit.WALK:
            frame_index = [10000, 60]
        elif mit.MOTION == mit.TIPTOE:
            frame_index = [1000000, 1000000]
            #frame_index = [10000, 165]
        else:
            frame_index = [1000000, 1000000]

        #MOTION = TAEKWONDO
        #frame_index = [135, 100]

        if frame > frame_index[0]:
            if stage != POWERFUL_BALANCING:
                print("#", frame, "-POWERFUL_BALANCING")
            stage = POWERFUL_BALANCING
            Kk = Kk * 2
            Dk = 2 * (Kk**.5)
        elif frame > frame_index[1]:
            if stage != MOTION_TRACKING:
                print("#", frame, "-MOTION_TRACKING")
            stage = MOTION_TRACKING

        trackingW = w

        #if checkAll(contactFlagFootR, 0) != 1 :
        if 0:  #stage == MOTION_TRACKING:
            trackingW = w2
            #stage = POWERFUL_BALANCING
            Bt = Bt * 2

        # optimization

        mot.addTrackingTerms(problem, totalDOF, Bt, trackingW, ddth_des_flat)

        #mot.addSoftPointConstraintTerms(problem, totalDOF, Bsc, ddP_des1, Q1, q_bias1)

        if flagContact == True:
            if stage != MOTION_TRACKING + 10:
                mot.addLinearTerms(problem, totalDOF, Bl, dL_des_plane, R,
                                   r_bias)
                #mot.addAngularTerms(problem, totalDOF, Bh, dH_des, S, s_bias)
                # using || dH ||^2 instead
                mot.addAnotherTerms(problem, totalDOF, Bh, S,
                                    -(s_bias + Kh * np.dot(S, dth_flat)))

        a_sup_2 = None
        Jsup_2 = None
        dJsup_2 = None

        ##############################
        # Hard constraint

        Kk2 = Kk * 4.0
        Dk2 = 2 * (Kk2**.5)

        ankleW = 0
        ankleOffset = ankleW * curRelCMVec[2]
        metatarW = 0
        metatarOffset = metatarW * curRelCMVec[2]

        ##############################

        ##############################
        # Additional constraint

        if stage != MOTION_TRACKING and frame > 5:
            # ankle strategy
            idx = 0  #LEFT/RIGHT_TOES
            if mit.FOOT_PART_NUM == 1:
                yOffset = 0.03
            else:
                yOffset = 0.069
                #yOffset = 0.06
            # ankleOffset = (footCenter - CM_plane)*4.
            ankleOffset = footCenterOffset * 10.

            ankleOffset[1] = 0.
            #ankleOffset[2] = 0.
            ankleOffset[2] = ankleOffset[2] * 20.
            ankleOffsetL = ankleOffset.copy()
            ankleOffsetR = ankleOffset.copy()

            #ankleOffset= np.array((0,0,0))

            if footCenterOffset[0] > 0.0:
                ankleOffsetL[0] = 0.
            else:
                ankleOffsetR[0] = 0.

            # print 'ankleOffset=', ankleOffset

            desLinearAccL, desPosL = getDesFootLinearAcc(
                motionModel, controlModel, indexFootL[idx], ModelOffset,
                CM_ref, CM, Kk, Dk, yOffset)  #0.076) #0.14)
            desLinearAccR, desPosR = getDesFootLinearAcc(
                motionModel, controlModel, indexFootR[idx], ModelOffset,
                CM_ref, CM, Kk, Dk, yOffset)

            ax = [0, 0, -1]
            aaa = getBodyGlobalOri(controlModel, motion, 'RightFoot')
            #print np.dot(aaa, ax)
            if mit.FOOT_PART_NUM == 1:
                ax = [0, 1, 0]

            desAngularAccL = getDesFootAngularAcc(
                motionModel, controlModel, indexFootL[idx], Kk, Dk, ax,
                mm.normalize([0, 1, 0] + ankleOffsetL))
            desAngularAccR = getDesFootAngularAcc(
                motionModel, controlModel, indexFootR[idx], Kk, Dk, ax,
                mm.normalize([0, 1, 0] + ankleOffsetR))

            a_sup_2 = np.hstack((np.hstack((desLinearAccL, desAngularAccL)),
                                 np.hstack((desLinearAccR, desAngularAccR))))
            Jsup_2 = np.vstack((jFootL[idx], jFootR[idx]))
            dJsup_2 = np.vstack((dJFootL[idx], dJFootR[idx]))
            #mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)
            #mot.addConstraint(problem, totalDOF, Jsup_2[:1], dJsup_2[:1], dth_flat, a_sup_2[:1])
            #mot.addConstraint(problem, totalDOF, Jsup_2[2:], dJsup_2[2:], dth_flat, a_sup_2[2:])
            #mot.addConstraint(problem, totalDOF, Jsup_2[3:], dJsup_2[3:], dth_flat, a_sup_2[3:])
            mot.addAnotherTerms(problem, totalDOF,
                                viewer.objectInfoWnd.Bc.value(), Jsup_2[3:],
                                a_sup_2[3:] - np.dot(dJsup_2[3:], dth_flat))
            #mot.addAnotherTerms(problem, totalDOF, viewer.objectInfoWnd.Bc.value(), Jsup_2, a_sup_2 - np.dot(dJsup_2, dth_flat))
            #mot.addAnotherTerms(problem, totalDOF, 1.*viewer.objectInfoWnd.Bc.value(), Jsup_2[0:1], a_sup_2[0:1] - np.dot(dJsup_2[0:1] , dth_flat))
            #mot.addAnotherTerms(problem, totalDOF, 1.*viewer.objectInfoWnd.Bc.value(), Jsup_2[2:], a_sup_2[2:] - np.dot(dJsup_2[2:] , dth_flat))

            desCOMOffset = 0.0

            rd_DesPosL[0] = desPosL.copy()
            rd_DesPosR[0] = desPosR.copy()

        if stage == STATIC_BALANCING and frame > 10:  # and False:
            del rd_desPoints[:]
            # foot strategy
            #Kk2 = Kk * 2.5
            #Kk2 = Kk * .2
            #Dk2 = 2*(Kk2**.5)
            desForePosL = [0, 0, 0]
            desForePosR = [0, 0, 0]
            desRearPosL = [0, 0, 0]
            desRearPosR = [0, 0, 0]
            footPartPos = []
            footPartPos.append(
                controlModel.getBodyPositionGlobal(
                    motion[0].skeleton.getJointIndex('LeftCalcaneus_1')))
            footPartPos.append(
                controlModel.getBodyPositionGlobal(
                    motion[0].skeleton.getJointIndex('LeftPhalange_1')))
            footPartPos.append(
                controlModel.getBodyPositionGlobal(
                    motion[0].skeleton.getJointIndex('RightCalcaneus_1')))
            footPartPos.append(
                controlModel.getBodyPositionGlobal(
                    motion[0].skeleton.getJointIndex('RightPhalange_1')))

            for i in range(1, footPartNum):
                contactFlagFootL[i] = 1
                contactFlagFootR[i] = 1
            SupPts = np.vstack(
                (np.array((footPartPos[0][0], footPartPos[1][0],
                           footPartPos[2][0], footPartPos[3][0])),
                 np.array(
                     (footPartPos[0][2], footPartPos[1][2], footPartPos[2][2],
                      footPartPos[3][2])), np.array((1., 1., 1., 1.))))

            coordWidthLen = 2.
            coordLengthLen = 1.5
            SupUV = np.vstack(
                (np.array((-coordWidthLen, -coordWidthLen, coordWidthLen,
                           coordWidthLen)),
                 np.array((-coordLengthLen, coordLengthLen, -coordLengthLen,
                           coordLengthLen)), np.array((1., 1., 1., 1.))))
            SupMap = np.dot(np.dot(SupUV, SupUV.T),
                            np.linalg.inv(np.dot(SupPts, SupUV.T)))
            #print SupMap
            desFootCenter = footCenter + footCenterOffset
            footCenterPts = np.array((desFootCenter[0], desFootCenter[2], 1))

            #print np.dot(SupMap, footCenterPts)
            #print np.dot(getBodyGlobalOri(controlModel, motion, 'LeftMetatarsal_1'), np.array((0,1,0)))

            CM_plane_2D = np.array((CM[0], CM[2], 1))
            # CM_plane_UV = np.dot(SupMap, CM_plane_2D)
            CM_plane_UV = np.dot(SupMap, footCenterPts)
            # print CM_plane_UV
            # for i in range(1, footPartNum):
            if CM_plane_UV[1] > .5:
                # com is in front
                for i in range(1, 5):
                    contactFlagFootL[i] = 0
                    contactFlagFootR[i] = 0
            elif CM_plane_UV[1] < -.5:
                # com is back
                for i in range(3, footPartNum):
                    contactFlagFootL[i] = 0
                    contactFlagFootR[i] = 0
            else:
                # com is in middle position
                for i in range(3, 5):
                    contactFlagFootL[i] = 0
                    contactFlagFootR[i] = 0

            contactFlagFoot = contactFlagFootL
            if CM_plane_UV[0] < 0.:
                contactFlagFoot = contactFlagFootR
                # CM_plane_UV[0] = -CM_plane_UV[0]

            if abs(CM_plane_UV[0]) > 1.:
                for j in range(0, 3):
                    contactFlagFoot[2 * j + 2] = 0

            # print 'footL : ',contactFlagFootL
            # print 'footR : ',contactFlagFootR

            for i in range(1, footPartNum):

                axis = [0, 0, 1]
                if i == 1 or i == 2:
                    axis = [0, 0, -1]

                desAng = [0, 0, 1]
                if i == 1 or i == 2:
                    desAng = [0, 0, -1]

                desY = 0.029
                if contactFlagFootL[i] == 1:
                    desLinearAccL, desForePosL = getDesFootLinearAcc(
                        motionModel, controlModel, indexFootL[i], ModelOffset,
                        CM_ref, CM, Kk2, Dk2, desY)
                    desAngularAccL = getDesFootAngularAcc(
                        motionModel, controlModel, indexFootL[i], Kk2, Dk2,
                        axis, desAng)
                    a_sup_2 = np.hstack((desLinearAccL, desAngularAccL))
                    Jsup_2 = jFootL[i].copy()
                    dJsup_2 = dJFootL[i].copy()
                    mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2,
                                      dth_flat, a_sup_2)
                    #mot.addAnotherTerms(problem, totalDOF, viewer.objectInfoWnd.Bc.value(), Jsup_2, a_sup_2 - np.dot(dJsup_2, dth_flat))
                    #mot.addAnotherTerms(problem, totalDOF, viewer.objectInfoWnd.Bc.value(), Jsup_2[3:], a_sup_2[3:] - np.dot(dJsup_2[3:] , dth_flat))
                    rd_desPoints.append(desForePosL.copy())

                if contactFlagFootR[i] == 1:
                    desLinearAccR, desForePosR = getDesFootLinearAcc(
                        motionModel, controlModel, indexFootR[i], ModelOffset,
                        CM_ref, CM, Kk2, Dk2, desY)
                    desAngularAccR = getDesFootAngularAcc(
                        motionModel, controlModel, indexFootR[i], Kk2, Dk2,
                        axis, desAng)
                    a_sup_2 = np.hstack((desLinearAccR, desAngularAccR))
                    Jsup_2 = jFootR[i].copy()
                    dJsup_2 = dJFootR[i].copy()
                    mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2,
                                      dth_flat, a_sup_2)
                    #mot.addAnotherTerms(problem, totalDOF, viewer.objectInfoWnd.Bc.value(), Jsup_2, a_sup_2 - np.dot(dJsup_2, dth_flat))
                    #mot.addAnotherTerms(problem, totalDOF, viewer.objectInfoWnd.Bc.value(), Jsup_2[3:], a_sup_2[3:] - np.dot(dJsup_2[3:], dth_flat))
                    rd_desPoints.append(desForePosR.copy())

            rd_DesForePosL[0] = desForePosL
            rd_DesForePosR[0] = desForePosR
            rd_DesRearPosL[0] = desRearPosL
            rd_DesRearPosR[0] = desRearPosR

        ##############################

        #if Jsup_2 is not None:
        #    mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)

        timeReport[4] += time.time() - curTime
        curTime = time.time()

        r = problem.solve()
        #print frame
        #Ashape = np.shape(problem.A)
        #if len(Ashape) >0 :
        #    for i in range(0, Ashape[0]):
        #        print problem.A[i]
        #print problem.A[]
        #print problem.b
        #print r
        problem.clear()
        #print r['x']
        ype.nested(r['x'], ddth_sol)

        #print ddth_sol

        rootPos[0] = controlModel.getBodyPositionGlobal(selectedBody)
        localPos = [[0, 0, 0]]

        ###########################################
        ##Jacobian Transpose control

        # COM Position control
        #fCom = Wcp*(pHatComDes - pHatCom) + Wcv*(vComDes - vCom) + Wcm*(footCenter_plane - CM_plane)

        w1 = 10  #10.1
        w2 = 1  #1#2*(w1**.5)

        if frame > 100:
            w1 = 10.1  #10.1
            w2 = 1

        footToCMVec = CM - footCenter
        desCMPos = [footCenter[0], mm.length(footToCMVec), footCenter[2]]
        #print("desCMPos", desCMPos)
        #print("CM", CM)
        fCom = w1 * (desCMPos - CM) + w2 * (-dCM)
        #print("fCom", fCom)
        #fCom[0] = 0.
        #fCom[1] = 0
        #fCom[2] = 0
        rd_virtualForce[0] = fCom.copy()

        #hipPos = controlModel.getBodyPositionGlobal(rootB)
        headPos = controlModel.getBodyPositionGlobal(selectedBody)
        hipPos = controlModel.getBodyPositionGlobal(rootB)
        yjc.computeJacobian2(Jcom, DOFs, jointPositions, jointAxeses,
                             [headPos], comUpperJointMasks)
        #yjc.computeJacobianDerivative2(dJcom, DOFs, jointPositions, jointAxeses, linkAngVelocities, [CM], comUpperJointMasks, False)
        JcomT = Jcom.T
        TauJT = np.dot(JcomT, fCom)

        # Angular Momentum
        Hc = ymt.getAngularMomentum(CM, linkInertias, linkAngVelocities,
                                    linkPositions, linkMasses, linkVelocities)
        Href = ymt.getAngularMomentum(CM_ref, linkInertias_ref,
                                      linkAngVelocities_ref, linkPositions_ref,
                                      linkMasses, linkVelocities_ref)

        Wam = .05
        Tam = Wam * (Href - Hc)
        #print("Tam", Tam)

        yjc.computeAngJacobian2(JcomAng, DOFs, jointPositions, jointAxeses,
                                [headPos], comUpperJointMasks)
        TauAM = np.dot(JcomAng.T, Tam)

        timeReport[5] += time.time() - curTime
        curTime = time.time()

        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
                bodyIDsToCheck, mus, Ks, Ds)
            #print frame, bodyIDs, contactPositions, contactPositionLocals, contactForces
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals,
                                      contactForces)

            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0
                    or extraForce[0][2] != 0):
                forceApplyFrame += 1
                #vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                controlModel.applyBodyForceGlobal(selectedBody, extraForce[0])
                applyedExtraForce[0] = extraForce[0]

            if forceApplyFrame * wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0
            #print ddth_sol
            controlModel.setDOFAccelerations(ddth_sol)

            controlModel.solveHybridDynamics()
            vpWorld.step()

        #if frame%30==0: print 'elapsed time for 30 frames:', time.time()-pt[0]
        # rendering

        rd_footCenter[0] = footCenter

        rd_CM[0] = CM.copy()

        rd_CM_plane[0] = CM_plane.copy()

        rd_footCenter_ref[0] = footCenter_ref
        rd_CM_plane_ref[0] = CM_ref.copy()
        rd_CM_ref[0] = CM_ref.copy()
        rd_CM_ref_vec[0] = (CM_ref - footCenter_ref) * 3.
        rd_CM_vec[0] = (CM - CM_plane)
        rd_CM_des[0] = CM_ref_plane.copy()
        rd_CM_des[0][1] = .01

        #rd_CM_plane[0][1] = 0.

        if (CP is not None) and (dCP is not None):
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des

        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des

        rd_grf_des[
            0] = totalNormalForce  # - totalMass*mm.s2v(wcfg.gravity)#dL_des_plane - totalMass*mm.s2v(wcfg.gravity)

        rd_exf_des[0] = applyedExtraForce[0]
        rd_root_des[0] = rootPos[0]

        rd_CMP[0] = softConstPoint

        rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(
            constBody) - softConstPoint

        del rd_contactForces[:]
        del rd_contactPositions[:]
        if CP is not None:
            for i in range(len(lcpBodyIDs)):
                rd_contactForces.append(lcpContactForces[i].copy() / 200.)
                rd_contactPositions.append(lcpContactPositions[i].copy())

        timeReport[6] += time.time() - curTime
        # print timeReport

    viewer.setSimulateCallback(simulateCallback)

    viewer.startTimer(1 / 30.)
    viewer.show()

    Fl.run()
Ejemplo n.º 18
0
def create_biped():

    # motion
    #motionName = 'wd2_n_kick.bvh'
    #motionName = 'wd2_jump_ori.bvh'
    if 1:
        #motionName = 'wd2_stand.bvh'
        motionName = 'woddy2_jump0.bvh'
        motion = yf.readBvhFile(motionName, .01)

        yme.removeJoint(motion, 'HEad', False)
        yme.removeJoint(motion, 'RightShoulder', False)
        yme.removeJoint(motion, 'LeftShoulder1', False)
        yme.removeJoint(motion, 'RightToes_Effector', False)
        yme.removeJoint(motion, 'LeftToes_Effector', False)
        yme.removeJoint(motion, 'RightHand_Effector', False)
        yme.removeJoint(motion, 'LeftHand_Effector', False)
        yme.offsetJointLocal(motion, 'RightArm', (.03, -.05, 0), False)
        yme.offsetJointLocal(motion, 'LeftArm', (-.03, -.05, 0), False)
        yme.rotateJointLocal(motion, 'Hips', mm.exp(mm.v3(1, 0, 0), .01),
                             False)
        yme.rotateJointLocal(motion, 'LeftFoot',
                             mm.exp(mm.v3(2.5, -0.0, .3), -.5), False)
        yme.rotateJointLocal(motion, 'RightFoot',
                             mm.exp(mm.v3(2.5, 0.0, -.3), -.5), False)
        #yme.rotateJointLocal(motion, 'LeftFoot', mm.exp(mm.v3(1,-0.0,.2), -.5), False)
        #yme.rotateJointLocal(motion, 'RightFoot', mm.exp(mm.v3(1,0.0,-.2), -.5), False)

        yme.rotateJointLocal(motion, 'LeftUpLeg',
                             mm.exp(mm.v3(0.0, .0, 1.), .08), False)
        yme.rotateJointLocal(motion, 'LeftLeg', mm.exp(mm.v3(0.0, 1.0, 0.),
                                                       -.2), False)

        #yme.rotateJointLocal(motion, 'RightLeg', mm.exp(mm.v3(1.0,0.0,0.), -.1), False)
        yme.updateGlobalT(motion)
    else:
        motionName = 'ww13_41.bvh'
        motion = yf.readBvhFile(motionName, 0.056444)
        yme.removeJoint(motion, 'LHipJoint', False)
        yme.removeJoint(motion, 'RHipJoint', False)
        yme.removeJoint(motion, 'Neck', False)
        yme.removeJoint(motion, 'Neck1', False)
        yme.removeJoint(motion, 'Head', False)
        yme.removeJoint(motion, 'RightShoulder', False)
        yme.removeJoint(motion, 'LeftShoulder', False)
        yme.removeJoint(motion, 'RightToeBase_Effector', False)
        yme.removeJoint(motion, 'LeftToeBase_Effector', False)
        yme.removeJoint(motion, 'LeftHand', False)
        yme.removeJoint(motion, 'LeftFingerBase', False)
        yme.removeJoint(motion, 'LeftHandIndex1_Effector', False)
        yme.removeJoint(motion, 'LThumb', False)
        yme.removeJoint(motion, 'RightHand', False)
        yme.removeJoint(motion, 'RightFingerBase', False)
        yme.removeJoint(motion, 'RightHandIndex1_Effector', False)
        yme.removeJoint(motion, 'RThumb', False)
        yme.removeJoint(motion, 'LowerBack', False)

        yme.offsetJointLocal(motion, 'RightArm', (-.03, -.05, 0), False)
        yme.offsetJointLocal(motion, 'LeftArm', (.03, -.05, 0), False)
        #yme.rotateJointLocal(motion, 'Hips', mm.exp(mm.v3(1,0,0), .01), False)
        yme.rotateJointLocal(motion, 'LeftFoot', mm.exp(mm.v3(-1.5, 0, 1), .4),
                             False)
        yme.rotateJointLocal(motion, 'RightFoot',
                             mm.exp(mm.v3(1.5, 0, 1), -.4), False)
        yme.updateGlobalT(motion)
        #motion = motion[50:-1]
        motion = motion[240:-1]

    #motion = motion[40:-58]
    #motion = motion[56:-248]
    #motion = motion[-249:-248]

    #motion = motion[62:65]
    #motion = motion[216:217]
    #motion = motion[515:555]

    ################
    motion = motion[515:555]

    #motion = motion[96:97]
    motion[0:0] = [motion[0]] * 100
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode('Hips')
    node.length = .2
    node.width = .25

    node = mcfg.getNode('Spine1')
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode('Spine')
    node.width = .22
    #node.length = .2 ####

    node = mcfg.getNode('RightFoot')
    node.length = .25
    node.width = .2
    node.mass = 4.

    node = mcfg.getNode('LeftFoot')
    node.length = .25
    node.width = .2
    node.mass = 4.

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 30
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    '''
    config['Kt'] = 200;      config['Dt'] = 2*(config['Kt']**.5) # tracking gain
    config['Kl'] = 2.5;       config['Dl'] = 2*(config['Kl']**.5) # linear balance gain
    config['Kh'] = 1;       config['Dh'] = 2*(config['Kh']**.5) # angular balance gain
    config['Ks'] = 20000;   config['Ds'] = 2*(config['Ks']**.5) # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 2.5
    config['Bh'] = 1.
    '''
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    config['weightMap']={'RightArm':.2, 'RightForeArm':.2, 'LeftArm':.2, 'LeftForeArm':.2,\
                         'Spine':.3, 'Spine1':.3, 'RightFoot':.3, 'LeftFoot':.3, 'Hips':.5,\
                         'RightUpLeg':.1, 'RightLeg':.3, 'LeftUpLeg':.1, 'LeftLeg':.3}

    config['IKweightMap']={'RightArm':.2, 'RightForeArm':.2, 'LeftArm':.2, 'LeftForeArm':.2,\
                         'Spine':.3, 'Spine1':.3, 'RightFoot':.3, 'LeftFoot':.3, 'Hips':.5,\
                         'RightUpLeg':.1, 'RightLeg':.3, 'LeftUpLeg':.1, 'LeftLeg':.3}
    '''
    config['IKweightMap']={'RightArm':.2, 'RightForeArm':.2, 'LeftArm':.2, 'LeftForeArm':.2,\
                         'Spine':0.5, 'Spine1':0.5, 'RightFoot':1.2, 'LeftFoot':1.2, 'Hips':1.2,\
                         'RightUpLeg':.9, 'RightLeg':.9, 'LeftUpLeg':.9, 'LeftLeg':.9}
    '''

    config['weightMap']={'RightArm':.2, 'RightForeArm':.2, 'LeftArm':.2, 'LeftForeArm':.2,\
                         'Spine':1.5, 'LeftFoot':1., 'Hips':1.5,\
                         'RightUpLeg':1., 'RightLeg':1., 'LeftUpLeg':1.5, 'LeftLeg':1.5}

    config['supLink'] = 'LeftFoot'
    config['supLink2'] = 'RightFoot'
    #config['end'] = 'Hips'
    config['end'] = 'Spine1'

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 19
0
def create_biped():
    # motion
    #motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        #motionName = 'wd2_stand.bvh'
        motionName = 'wd2_stand2.bvh'
    elif MOTION == STAND2:
        motionName = 'ww13_41_V001.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == TAEKWONDO2:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == KICK:
        motionName = 'wd2_n_kick.bvh'
    elif MOTION == WALK:
        motionName = 'wd2_WalkForwardNormal00.bvh'
    elif MOTION == TIPTOE:
        motionName = './MotionFile/cmu/15_07_15_07.bvh'

    #motionName = 'ww13_41_V001.bvh'
    scale = 0.01
    if MOTION == WALK:
        scale = 1.0
    elif MOTION == TIPTOE:
        scale = 0.01

    motion = yf.readBvhFile(motionName, scale)

    yme.removeJoint(motion, HEAD, False)
    yme.removeJoint(motion, RIGHT_SHOULDER, False)
    yme.removeJoint(motion, LEFT_SHOULDER, False)

    yme.removeJoint(motion, RIGHT_TOES, False)
    yme.removeJoint(motion, RIGHT_TOES_END, False)
    yme.removeJoint(motion, LEFT_TOES, False)
    yme.removeJoint(motion, LEFT_TOES_END, False)

    yme.removeJoint(motion, RIGHT_HAND_END, False)
    yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1, 0, 0), .01), False)

    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(0, 0, 1), -.01), False)

    #addFootSegment
    yme.addJoint(motion, LEFT_FOOT, LEFT_TALUS_1, (-0.045, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_TALUS_2, (0.0, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_TALUS_3,
                 (0.045, -0.06, -0.05))  #-0.0037

    yme.addJoint(motion, LEFT_TALUS_1, LEFT_METATARSAL_1, (0.0, 0.0, 0.1))
    yme.addJoint(motion, LEFT_TALUS_3, LEFT_METATARSAL_3,
                 (0.0, 0.0, 0.1))  #-0.0037
    yme.addJoint(motion, LEFT_TALUS_2, LEFT_METATARSAL_2, (0.0, 0.0, 0.1))

    yme.addJoint(motion, LEFT_METATARSAL_1, LEFT_PHALANGE_1, (0.0, 0.0, 0.07))
    yme.addJoint(motion, LEFT_METATARSAL_3, LEFT_PHALANGE_3, (0.0, 0.0, 0.07))
    yme.addJoint(motion, LEFT_METATARSAL_2, LEFT_PHALANGE_2, (0.0, 0.0, 0.07))

    yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_PHALANGE_Effector1',
                 (0.0, 0.0, 0.06))
    yme.addJoint(motion, LEFT_PHALANGE_3, 'LEFT_PHALANGE_Effector3',
                 (0.0, 0.0, 0.06))
    yme.addJoint(motion, LEFT_PHALANGE_2, 'LEFT_PHALANGE_Effector2',
                 (0.0, 0.0, 0.06))

    #yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_1, (-0.045, -0.06, -0.04))
    #yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_2, (0.0, -0.06, -0.04))
    #yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_3, (0.045, -0.06, -0.04))
    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_1, (-0.045, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_2, (0.0, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_3, (0.045, -0.06, -0.05))

    yme.addJoint(motion, LEFT_CALCANEUS_1, 'LEFT_CALCANEUS_Effector1',
                 (0., 0.0, -0.07))
    yme.addJoint(motion, LEFT_CALCANEUS_2, 'LEFT_CALCANEUS_Effector2',
                 (0., 0.0, -0.07))
    yme.addJoint(motion, LEFT_CALCANEUS_3, 'LEFT_CALCANEUS_Effector3',
                 (0., 0.0, -0.07))

    yme.addJoint(motion, RIGHT_FOOT, RIGHT_TALUS_1, (0.045, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_TALUS_2, (0.0, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_TALUS_3, (-0.045, -0.06, -0.05))

    yme.addJoint(motion, RIGHT_TALUS_1, RIGHT_METATARSAL_1, (0.0, 0.0, 0.1))
    yme.addJoint(motion, RIGHT_TALUS_2, RIGHT_METATARSAL_2, (0.0, 0.0, 0.1))
    yme.addJoint(motion, RIGHT_TALUS_3, RIGHT_METATARSAL_3, (0.0, 0.0, 0.1))

    yme.addJoint(motion, RIGHT_METATARSAL_1, RIGHT_PHALANGE_1,
                 (0.0, 0.0, 0.07))
    yme.addJoint(motion, RIGHT_METATARSAL_2, RIGHT_PHALANGE_2,
                 (0.0, 0.0, 0.07))
    yme.addJoint(motion, RIGHT_METATARSAL_3, RIGHT_PHALANGE_3,
                 (0.0, 0.0, 0.07))

    yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_PHALANGE_Effector1',
                 (0.0, 0.0, 0.06))
    yme.addJoint(motion, RIGHT_PHALANGE_2, 'RIGHT_PHALANGE_Effector2',
                 (0.0, 0.0, 0.06))
    yme.addJoint(motion, RIGHT_PHALANGE_3, 'RIGHT_PHALANGE_Effector3',
                 (0.0, 0.0, 0.06))

    #yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_1, (0.045, -0.06, -0.04))
    #yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_2, (0.0, -0.06, -0.04))
    #yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_3, (-0.045, -0.06, -0.04))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_1, (0.045, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_2, (0.0, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_3, (-0.045, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_CALCANEUS_1, 'RIGHT_CALCANEUS_Effector1',
                 (0.0, 0.0, -0.07))
    yme.addJoint(motion, RIGHT_CALCANEUS_2, 'RIGHT_CALCANEUS_Effector2',
                 (0.0, 0.0, -0.07))
    yme.addJoint(motion, RIGHT_CALCANEUS_3, 'RIGHT_CALCANEUS_Effector3',
                 (0.0, 0.0, -0.07))

    yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0, 0.0, 0.0), -.5),
                         False)
    yme.rotateJointLocal(motion, RIGHT_TALUS_1, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                       .5), False)
    yme.rotateJointLocal(motion, RIGHT_TALUS_2, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                       .5), False)
    yme.rotateJointLocal(motion, RIGHT_TALUS_3, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                       .5), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_2,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_3,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_2,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_3,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)

    yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0, 0.0, 0.0), -.5),
                         False)
    yme.rotateJointLocal(motion, LEFT_TALUS_1, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                      .5), False)
    yme.rotateJointLocal(motion, LEFT_TALUS_3, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                      .5), False)
    yme.rotateJointLocal(motion, LEFT_TALUS_2, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                      .5), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_2,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_3,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_2,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_3,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    #yme.rotateJointLocal(motion, LEFT_CALCANEUS_1, mm.exp(mm.v3(0.0,-1.0,0.0), 1.57), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    elif MOTION == TAEKWONDO2:
        ## Taekwondo base-step
        #motion = motion[0:31+40]
        ## Taekwondo turning-kick
        motion = motion[108:-1]
        #motion = motion[108:109]
    elif MOTION == KICK:
        #motion = motion[141:-1]
        #motion = motion[100:-1]
        #motion = motion[58:-1]
        motion = motion[82:-1]
        #motion = motion[0:-1]
    elif MOTION == STAND2:
        motion = motion[1:-1]
    elif MOTION == TIPTOE:
        #motion = motion[183:440]
        #motion = motion[350:410]
        motion = motion[350:550]

    motion[0:0] = [motion[0]] * 40
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    #node.length = .2 ####

    node = mcfg.getNode('RightFoot')
    node.length = .1
    node.width = .1

    node = mcfg.getNode('LeftFoot')
    node.length = .1
    node.width = .1

    #return mcfg
    #
    #mass0 = .4
    #width0 = 0.028
    #length0 = 0.1
    #
    ##Metatarsal1
    #length1 = .12
    #width1 = 0.03
    #mass1 = 0.4
    #
    #length2 = .1
    #width2 = 0.026
    #mass2 = 0.4
    #
    ##Metatarsal3
    #length3 = .08
    #width3 = 0.024
    #mass3 = 0.4
    #
    ##Calcaneus1
    #length4 = .1
    #width4 = 0.032
    #mass4 = 0.4
    #
    ##Phalange1
    #length5 = .08
    #width5 = 0.01
    #mass5 = 0.4
    ##Phalange3
    #length7 = length5
    #width7 = width5
    #mass7 = mass5
    #
    ##Talus
    ##length8 = .13
    ##width8 = width0*3
    ##mass8 = mass0*2.
    #
    #length8 = .1
    #width8 = width0*3
    #mass8 = mass0*1.5

    width0 = 0.028
    length0 = 0.1
    mass0 = .4

    #Metatarsal1
    length1 = .1
    width1 = 0.03
    mass1 = 0.4

    length2 = length1
    width2 = width1
    mass2 = 0.4

    #Metatarsal3
    length3 = length1
    width3 = width1
    mass3 = 0.4

    #Calcaneus1
    length4 = length1
    width4 = width1
    mass4 = 0.4

    #Phalange1
    length5 = length1
    width5 = width1
    mass5 = 0.4
    #Phalange3
    length7 = length1
    width7 = width1
    mass7 = 0.4

    #Talus
    #length8 = .13
    #width8 = width0*3
    #mass8 = mass0*2.

    length8 = .1
    width8 = width0 * 3
    mass8 = mass0 * 1.5

    node = mcfg.getNode(RIGHT_FOOT)
    node.length = length8
    node.width = width8
    node.mass = mass8

    node = mcfg.getNode(RIGHT_TALUS_1)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(RIGHT_TALUS_3)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(RIGHT_TALUS_2)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(RIGHT_METATARSAL_1)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(RIGHT_METATARSAL_3)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(RIGHT_METATARSAL_2)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(RIGHT_PHALANGE_1)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(RIGHT_PHALANGE_2)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(RIGHT_PHALANGE_3)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(RIGHT_CALCANEUS_1)
    node.length = length4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(RIGHT_CALCANEUS_2)
    node.length = length4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(RIGHT_CALCANEUS_3)
    node.length = length4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(LEFT_FOOT)
    node.length = length8
    node.width = width8
    node.mass = mass8

    node = mcfg.getNode(LEFT_TALUS_1)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_TALUS_3)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_TALUS_2)
    node.length = length1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_METATARSAL_1)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(LEFT_METATARSAL_3)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(LEFT_METATARSAL_2)
    node.length = length2
    node.width = width2
    node.mass = mass2

    node = mcfg.getNode(LEFT_PHALANGE_1)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(LEFT_PHALANGE_2)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(LEFT_PHALANGE_3)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(LEFT_CALCANEUS_1)
    node.length = length4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(LEFT_CALCANEUS_2)
    node.length = length4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(LEFT_CALCANEUS_3)
    node.length = length4
    node.width = width4
    node.mass = mass4

    #node.offset = (0.0, -0.025, 0.0)

    node = mcfg.getNode('LeftFoot')

    node = mcfg.getNode(RIGHT_TALUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_TALUS_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_TALUS_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(LEFT_TALUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_TALUS_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_TALUS_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(RIGHT_METATARSAL_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_METATARSAL_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_METATARSAL_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_METATARSAL_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_METATARSAL_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_METATARSAL_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(RIGHT_PHALANGE_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_PHALANGE_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_PHALANGE_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_PHALANGE_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_PHALANGE_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_PHALANGE_3)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(RIGHT_CALCANEUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_CALCANEUS_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_CALCANEUS_3)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_CALCANEUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_CALCANEUS_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_CALCANEUS_3)
    node.geom = 'MyFoot3'

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 60
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    config['weightMap2'] = {
        RIGHT_ARM: .2,
        RIGHT_FORE_ARM: .2,
        LEFT_ARM: .2,
        LEFT_FORE_ARM: .2,
        SPINE: .5,
        SPINE1: .3,
        RIGHT_FOOT: .7,
        LEFT_FOOT: .7,
        HIP: .5,
        RIGHT_UP_LEG: .7,
        RIGHT_LEG: .7,
        LEFT_UP_LEG: .7,
        LEFT_LEG: .7,
        LEFT_TALUS_1: .7,
        RIGHT_TALUS_1: .7,
        LEFT_TALUS_2: .7,
        RIGHT_TALUS_2: .7,
        LEFT_TALUS_3: .7,
        RIGHT_TALUS_3: .7,
        LEFT_METATARSAL_1: .7,
        RIGHT_METATARSAL_1: .7,
        LEFT_METATARSAL_2: .7,
        RIGHT_METATARSAL_2: .7,
        LEFT_METATARSAL_3: .7,
        RIGHT_METATARSAL_3: .7,
        RIGHT_CALCANEUS_1: .7,
        LEFT_CALCANEUS_1: .7,
        RIGHT_CALCANEUS_2: .7,
        LEFT_CALCANEUS_2: .7,
        RIGHT_CALCANEUS_3: .7,
        LEFT_CALCANEUS_3: .7,
        LEFT_PHALANGE_1: .4,
        LEFT_PHALANGE_2: .4,
        LEFT_PHALANGE_3: .4,
        RIGHT_PHALANGE_1: .4,
        RIGHT_PHALANGE_2: .4,
        RIGHT_PHALANGE_3: .4
    }

    config['weightMap'] = {
        RIGHT_ARM: .2,
        RIGHT_FORE_ARM: .2,
        LEFT_ARM: .2,
        LEFT_FORE_ARM: .2,
        SPINE: .3,
        SPINE1: .2,
        RIGHT_FOOT: .3,
        LEFT_FOOT: .3,
        HIP: .3,
        RIGHT_UP_LEG: .1,
        RIGHT_LEG: .2,
        LEFT_UP_LEG: .1,
        LEFT_LEG: .2,
        LEFT_TALUS_1: .1,
        RIGHT_TALUS_1: .1,
        LEFT_TALUS_2: .1,
        RIGHT_TALUS_2: .1,
        LEFT_TALUS_3: .1,
        RIGHT_TALUS_3: .1,
        LEFT_METATARSAL_1: .1,
        RIGHT_METATARSAL_1: .1,
        LEFT_METATARSAL_2: .1,
        RIGHT_METATARSAL_2: .1,
        LEFT_METATARSAL_3: .1,
        RIGHT_METATARSAL_3: .1,
        RIGHT_CALCANEUS_1: .2,
        LEFT_CALCANEUS_1: .2,
        RIGHT_CALCANEUS_2: .2,
        LEFT_CALCANEUS_2: .2,
        RIGHT_CALCANEUS_3: .2,
        LEFT_CALCANEUS_3: .2,
        LEFT_PHALANGE_1: .1,
        LEFT_PHALANGE_2: .1,
        LEFT_PHALANGE_3: .1,
        RIGHT_PHALANGE_1: .1,
        RIGHT_PHALANGE_2: .1,
        RIGHT_PHALANGE_3: .1
    }
    '''
    config['weightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.3, SPINE1:.2, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.3,
                    RIGHT_UP_LEG:.1, RIGHT_LEG:.2, LEFT_UP_LEG:.1, LEFT_LEG:.2, 
                    LEFT_TALUS_1:.01, RIGHT_TALUS_1:.01, LEFT_TALUS_2:.01, RIGHT_TALUS_2:.01, LEFT_TALUS_3:.01, RIGHT_TALUS_3:.01, 
                    LEFT_METATARSAL_1:.01, RIGHT_METATARSAL_1:.01, LEFT_METATARSAL_2:.01, RIGHT_METATARSAL_2:.01, LEFT_METATARSAL_3:.01, RIGHT_METATARSAL_3:.01, 
                    RIGHT_CALCANEUS_1:.01, LEFT_CALCANEUS_1:.01, RIGHT_CALCANEUS_2:.01, LEFT_CALCANEUS_2:.01, RIGHT_CALCANEUS_3:.01, LEFT_CALCANEUS_3:.01, 
                    LEFT_PHALANGE_1:.01, LEFT_PHALANGE_2:.01, LEFT_PHALANGE_3:.01, RIGHT_PHALANGE_1:.01, RIGHT_PHALANGE_2:.01, RIGHT_PHALANGE_3:.01}
    '''

    #config['weightMap']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.3, SPINE1:.2, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.3,
    #                RIGHT_UP_LEG:.1, RIGHT_LEG:.2, LEFT_UP_LEG:.1, LEFT_LEG:.2,
    #                LEFT_TALUS_1:.1, RIGHT_TALUS_1:.1, LEFT_TALUS_3:.1, RIGHT_TALUS_3:.1,
    #                LEFT_METATARSAL_1:.1, RIGHT_METATARSAL_1:.1, LEFT_METATARSAL_3:.1, RIGHT_METATARSAL_3:.1,
    #                RIGHT_CALCANEUS_1:.2, LEFT_CALCANEUS_1:.2, RIGHT_CALCANEUS_3:.2, LEFT_CALCANEUS_3:.2,
    #                LEFT_PHALANGE_1:.1, LEFT_PHALANGE_3:.1, RIGHT_PHALANGE_1:.1, RIGHT_PHALANGE_3:.1}
    #
    #config['weightMap2']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.5, SPINE1:.3, RIGHT_FOOT:.7, LEFT_FOOT:.7, HIP:.5,
    #                RIGHT_UP_LEG:.7, RIGHT_LEG:.7, LEFT_UP_LEG:.7, LEFT_LEG:.7,
    #                LEFT_TALUS_1:.7, RIGHT_TALUS_1:.7, LEFT_TALUS_3:.7, RIGHT_TALUS_3:.7,
    #                LEFT_METATARSAL_1:.7, RIGHT_METATARSAL_1:.7, LEFT_METATARSAL_3:.7, RIGHT_METATARSAL_3:.7,
    #                RIGHT_CALCANEUS_1:.7, LEFT_CALCANEUS_1:.7, RIGHT_CALCANEUS_3:.7, LEFT_CALCANEUS_3:.7,
    #                LEFT_PHALANGE_1:.4, LEFT_PHALANGE_3:.4, RIGHT_PHALANGE_1:.4, RIGHT_PHALANGE_3:.4}

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    #config['end'] = HIP
    config['end'] = SPINE1
    config['const'] = HIP
    config['root'] = HIP

    config['FootPartNum'] = FOOT_PART_NUM

    config['FootLPart'] = [
        LEFT_FOOT, LEFT_CALCANEUS_1, LEFT_CALCANEUS_2, LEFT_CALCANEUS_3,
        LEFT_TALUS_1, LEFT_TALUS_2, LEFT_TALUS_3, LEFT_METATARSAL_1,
        LEFT_METATARSAL_2, LEFT_METATARSAL_3, LEFT_PHALANGE_1, LEFT_PHALANGE_2,
        LEFT_PHALANGE_3
    ]
    config['FootRPart'] = [
        RIGHT_FOOT, RIGHT_CALCANEUS_1, RIGHT_CALCANEUS_2, RIGHT_CALCANEUS_3,
        RIGHT_TALUS_1, RIGHT_TALUS_2, RIGHT_TALUS_3, RIGHT_METATARSAL_1,
        RIGHT_METATARSAL_2, RIGHT_METATARSAL_3, RIGHT_PHALANGE_1,
        RIGHT_PHALANGE_2, RIGHT_PHALANGE_3
    ]
    #config['FootLPart'] = [LEFT_FOOT, LEFT_CALCANEUS_1, LEFT_METATARSAL_1, LEFT_METATARSAL_3, LEFT_PHALANGE_1, LEFT_PHALANGE_3]
    #config['FootRPart'] = [RIGHT_FOOT, RIGHT_CALCANEUS_1, RIGHT_METATARSAL_1, RIGHT_METATARSAL_3, RIGHT_PHALANGE_1, RIGHT_PHALANGE_3]

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 20
0
def main():

    np.set_printoptions(precision=4, linewidth=200)
    
#    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()
        
    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    vpWorld.initialize()
    controlModel.initializeHybridDynamics()
    
    ModelOffset = (1.5, -0.02, 0)
    #ModelOffset = (1.5, 1.02, 0)
    #ModelOffset = (1.5, 0.02, 0)
    controlModel.translateByOffset(ModelOffset)
    #controlModel.translateByOffset((1.5,-0.0328,0))#(1.5,-0.02,0))
    
    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()
        
    # parameter 
    Kt = config['Kt']; Dt = config['Dt'] # tracking gain
    Kl = config['Kl']; Dl = config['Dl'] # linear balance gain
    Kh = config['Kh']; Dh = config['Dh'] # angular balance gain
    Ks = config['Ks']; Ds = config['Ds']  # penalty force spring gain
    
    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']
    
    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL =  motion[0].skeleton.getJointIndex(config['supLink'])
    supR =  motion[0].skeleton.getJointIndex(config['supLink2'])

    #controlModel.SetGround(supL, True)
    #controlModel.SetGround(supR, True)

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex('Hips')
    
    # jacobian 
    JsupL = yjc.makeEmptyJacobian(DOFs, 1)
    dJsupL = JsupL.copy()
    JsupPreL = JsupL.copy()

    JsupR = yjc.makeEmptyJacobian(DOFs, 1)
    dJsupR = JsupR.copy()
    JsupPreR = JsupR.copy()

    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()
        
    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    supLJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, supL)]
    supRJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, supR)]
    constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)
    
    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses) 
    dTO = ymt.make_dTO(len(linkMasses))
    
    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0,0,0, 0,0,0) #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0,0,0, 0,0,0]#R
    a_sup_2 = [0,0,0, 0,0,0, 0,0,0, 0,0,0]
    CP_old = [mm.v3(0.,0.,0.)]
        
    # penalty method 
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.]*len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)


    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    
    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]
        
    rd_CMP = [None]
    rd_DesPosL = [None]
    rd_DesPosR = [None]

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0,0,0]
    
    viewer = ysv.SimpleViewer()
#    viewer.record(False)
#    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer('motionModel', cvr.VpModelRenderer(motionModel, (150,150,255), yr.POLYGON_FILL))
    viewer.doc.addRenderer('controlModel', cvr.VpModelRenderer(controlModel, (255,240,255), yr.POLYGON_FILL))
    viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))    
    #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))  
    #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
    viewer.doc.addRenderer('rd_CM_plane', yr.PointsRenderer(rd_CM_plane, (255,255,0)))
    viewer.doc.addRenderer('rd_CP', yr.PointsRenderer(rd_CP, (0,255,0)))
    #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (255,0,255)))
#    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
#    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
    viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP_des, (0,255,255), .001))

    viewer.doc.addRenderer('rd_exf_des', yr.ForcesRenderer(rd_exf_des, rd_root_des, (0,255,0), .009, 0.05))
        
    #viewer.doc.addRenderer('rd_CMP', yr.PointsRenderer(rd_CMP, (0,0,255)))
    
    viewer.doc.addRenderer('rd_DesPosL', yr.PointsRenderer(rd_DesPosL, (0,0,255)))
    viewer.doc.addRenderer('rd_DesPosR', yr.PointsRenderer(rd_DesPosR, (0,100,255)))

    #viewer.doc.addRenderer('softConstraint', yr.VectorsRenderer(rd_soft_const_vec, rd_CMP, (255,0,0), 3))

    
    viewer.doc.addRenderer('rd_footCenter_ref', yr.PointsRenderer(rd_footCenter_ref))    
    viewer.doc.addRenderer('rd_CM_plane_ref', yr.PointsRenderer(rd_CM_plane_ref, (255,255,0)))
        
    stage = 0

    def simulateCallback(frame):
        global g_initFlag
        global preFootCenterL, preFootCenterR
        global preFootOrientationL, preFootOrientationR
        global forceShowFrame
        global forceApplyFrame

        global JsysPre
        global JsupPreL
        global JsupPreR
        global JsupPre

        global softConstPoint

        global stage

        motionModel.update(motion[frame])

        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, Bsc = viewer.GetParam()
        
        if stage == 3:
            Bsc = 0
            #Kl *= 1.5

        Dt = 2*(Kt**.5)
        Dk = 2*(Kk**.5)
        Dl = 2*(Kl**.5)
        Dh = 2*(Kh**.5)
        Dsc = 2*(Ksc**.5)
                
        if Bsc == 0.0 :
            viewer.doc.showRenderer('softConstraint', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('softConstraint', True)
            renderer1 = viewer.doc.getRenderer('softConstraint')
            renderer1.rc.setLineWidth(0.1+Bsc*3)
            viewer.motionViewWnd.update(1, viewer.doc)
                        
        # tracking
        th_r = motion.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt)
        ddth_c = controlModel.getDOFAccelerations()

        ype.flatten(ddth_des, ddth_des_flat)
        ype.flatten(dth, dth_flat)

        ype.flatten(ddth_c, ddth_c_flat)
        
        # jacobian 
        footCenterL = controlModel.getBodyPositionGlobal(supL)        
        footCenterR = controlModel.getBodyPositionGlobal(supR)
                        
        refFootL = motionModel.getBodyPositionGlobal(supL)        
        refFootR = motionModel.getBodyPositionGlobal(supR)
        
        footCenter = footCenterL + (footCenterR - footCenterL)/2.0
        footCenter[1] = 0.        
        
        footCenter_ref = refFootL + (refFootR - refFootL)/2.0
        footCenter_ref[1] = 0.      
        
        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()
        
        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        CM_plane = copy.copy(CM); CM_plane[1]=0.
        dCM_plane = copy.copy(dCM); dCM_plane[1]=0.
                
        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        CM_plane_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        CM_plane_ref[1] = 0.
        
        P = ymt.getPureInertiaMatrix(TO, linkMasses, linkPositions, CM, linkInertias)
        dP = ymt.getPureInertiaMatrixDerivative(dTO, linkMasses, linkVelocities, dCM, linkAngVelocities, linkInertias)

        yjc.computeJacobian2(Jsys, DOFs, jointPositions, jointAxeses, linkPositions, allLinkJointMasks)
        dJsys = (Jsys - JsysPre)/(1/30.)
        JsysPre = Jsys
        #yjc.computeJacobianDerivative2(dJsys, DOFs, jointPositions, jointAxeses, linkAngVelocities, linkPositions, allLinkJointMasks)
        
        
        if g_initFlag == 0:
            preFootCenterL = footCenterL
            preFootCenterR = footCenterR
            preFootCenterL[1] -= 0.02
            preFootCenterR[1] -= 0.02
            preFootOrientationL = controlModel.getBodyOrientationGlobal(supL)
            preFootOrientationR = controlModel.getBodyOrientationGlobal(supR)
            softConstPoint = controlModel.getBodyPositionGlobal(constBody)
            #softConstPoint[2] += 0.3
            #softConstPoint[1] -= 1.1
            #softConstPoint[0] += 0.1

            softConstPoint[1] -= .3            
            #softConstPoint[0] -= .1
            #softConstPoint[1] -= 1.
            #softConstPoint[0] -= .5
            g_initFlag = 1

        yjc.computeJacobian2(JsupL, DOFs, jointPositions, jointAxeses, [footCenterL], supLJointMasks)
        dJsupL = (JsupL - JsupPreL)/(1/30.)
        JsupPreL = JsupL
        #yjc.computeJacobianDerivative2(dJsupL, DOFs, jointPositions, jointAxeses, linkAngVelocities, [footCenterL], supLJointMasks, False)
        
        yjc.computeJacobian2(JsupR, DOFs, jointPositions, jointAxeses, [footCenterR], supRJointMasks)
        dJsupR = (JsupR - JsupPreR)/(1/30.)
        JsupPreR = JsupR
        #yjc.computeJacobianDerivative2(dJsupR, DOFs, jointPositions, jointAxeses, linkAngVelocities, [footCenterR], supRJointMasks, False)
        
        preFootCenter = preFootCenterL + (preFootCenterR - preFootCenterL)/2.0
        preFootCenter[1] = 0

        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)
                                   
        # linear momentum
        CM_ref_plane = footCenter
        #CM_ref_plane = preFootCenter
        dL_des_plane = Kl*totalMass*(CM_ref_plane - CM_plane) - Dl*totalMass*dCM_plane
        #print("dL_des_plane ", dL_des_plane )
        #dL_des_plane[1] = 0.
    
        # angular momentum
        CP_ref = footCenter

        timeStep = 30.
        if CP_old[0]==None or CP==None:
            dCP = None
        else:
            dCP = (CP - CP_old[0])/(1/timeStep)
        CP_old[0] = CP            
        
        if CP!=None and dCP!=None:
            ddCP_des = Kh*(CP_ref - CP) - Dh*(dCP)
            CP_des = CP + dCP*(1/timeStep) + .5*ddCP_des*((1/timeStep)**2)
            dH_des = np.cross((CP_des - CM), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))            
            #dH_des = np.cross((CP_des - CM_plane), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))
            #dH_des = [0, 0, 0]
        else:
            dH_des = None
 
        CMP = yrp.getCMP(contactForces, CM)
        r = [0,0,0]
        if CP!= None and np.any(np.isnan(CMP))!=True :
            r = CP - CMP
        #print("r.l", mm.length(r))
        #Bba = Bh*(mm.length(r))
        Bba = Bh

        # momentum matrix
        RS = np.dot(P, Jsys)
        R, S = np.vsplit(RS, 2)
        
        rs = np.dot((np.dot(dP, Jsys) + np.dot(P, dJsys)), dth_flat)
        r_bias, s_bias = np.hsplit(rs, 2)

        ##############################
        # soft point constraint

        '''
        cmDiff = footCenter - CM_plane
        print("cmDiff", cmDiff)
        if stage == 3:
            softConstPoint +=
        '''
        
        P_des = softConstPoint
        P_cur = controlModel.getBodyPositionGlobal(constBody)
        dP_des = [0, 0, 0]
        dP_cur = controlModel.getBodyVelocityGlobal(constBody)
        ddP_des1 = Ksc*(P_des - P_cur) - Dsc*(dP_cur - dP_des)

        r = P_des - P_cur
        I = np.vstack(([1,0,0],[0,1,0],[0,0,1]))
        Z = np.hstack((I, mm.getCrossMatrixForm(-r)))
          
        yjc.computeJacobian2(Jconst, DOFs, jointPositions, jointAxeses, [softConstPoint], constJointMasks)
        JL, JA = np.vsplit(Jconst, 2)
        Q1 = np.dot(Z, Jconst)
                  
        q1 = np.dot(JA, dth_flat)
        q2 = np.dot(mm.getCrossMatrixForm(q1), np.dot(mm.getCrossMatrixForm(q1), r))
        
        yjc.computeJacobianDerivative2(dJconst, DOFs, jointPositions, jointAxeses, linkAngVelocities, [softConstPoint], constJointMasks, False)
        q_bias1 = np.dot(np.dot(Z, dJconst), dth_flat) + q2
        
        '''
        P_des = preFootCenterR
        P_cur = controlModel.getBodyPositionGlobal(supR)
        P_cur[1] = 0
        dP_des = [0, 0, 0]
        dP_cur = controlModel.getBodyVelocityGlobal(supR)
        ddP_des2 = Kp*(P_des - P_cur) - Dp*(dP_cur - dP_des)
        
        r = P_des - P_cur
        #print("r2", r)
        I = np.vstack(([1,0,0],[0,1,0],[0,0,1]))
        Z = np.hstack((I, mm.getCrossMatrixForm(-r)))
            
        JL, JA = np.vsplit(JsupR, 2)
        Q2 = np.dot(Z, JsupR)
        
        q1 = np.dot(JA, dth_flat)
        q2 = np.dot(mm.getCrossMatrixForm(q1), np.dot(mm.getCrossMatrixForm(q1), r))
        q_bias2 = np.dot(np.dot(Z, dJsupR), dth_flat) + q2
        '''      
        #print("Q1", Q1)
        '''
        print("ddP_des1", ddP_des1)
        q_ddth1 = np.dot(Q1, ddth_c_flat)
        print("q_ddth1", q_ddth1)
        print("q_bias1", q_bias1)
        ddp1 = q_ddth1+q_bias1
        print("ddp1", ddp1)
        print("diff1", ddP_des1-ddp1)
        '''

        '''
        print("ddP_des2", ddP_des2)
        q_ddth2 = np.dot(Q2, ddth_c_flat)
        print("q_ddth2", q_ddth2)
        print("q_bias2", q_bias2)
        ddp2 = q_ddth2+q_bias2
        print("ddp2", ddp2)
        print("diff2", ddP_des2-ddp2)
        '''

        ##############################
        
        
        ############################
        # IK
        '''
        P_des = preFootCenterL
        P_cur = controlModel.getJointPositionGlobal(supL)
        r = P_des - P_cur
        
        Q_des = preFootOrientationL 
        Q_cur = controlModel.getJointOrientationGlobal(supL)
        rv = mm.logSO3(np.dot(Q_cur.transpose(), Q_des))
        #print("rv", rv)

        des_v_sup = (r[0],r[1],r[2], rv[0], rv[1], rv[2])
        A_large = np.dot(JsupL.T, JsupL)
        b_large = np.dot(JsupL.T, des_v_sup)

        des_d_th = npl.lstsq(A_large, b_large)

        ype.nested(des_d_th[0], d_th_IK_L)
                                        
        P_des2 = preFootCenterR
        P_cur2 = controlModel.getJointPositionGlobal(supR)
        r2 = P_des2 - P_cur2
                
        Q_des2 = preFootOrientationR
        Q_cur2 = controlModel.getJointOrientationGlobal(supR)
        rv2 = mm.logSO3(np.dot(Q_cur2.transpose(), Q_des2))
        #print("Q_des2", Q_des2)
        #print("Q_cur2", Q_cur2)
        #print("rv2", rv2)

        des_v_sup2 = (r2[0],r2[1],r2[2], rv2[0], rv2[1], rv[2])
        A_large = np.dot(JsupR.T, JsupR)
        b_large = np.dot(JsupR.T, des_v_sup2)

        des_d_th = npl.lstsq(A_large, b_large)

        ype.nested(des_d_th[0], d_th_IK_R)
        for i in range(len(d_th_IK_L)):
            for j in range(len(d_th_IK_L[i])):
                d_th_IK[i][j] = d_th_IK_L[i][j] + d_th_IK_R[i][j]
                    
        th_IK = yct.getIntegralDOF(th, d_th_IK, 1/timeStep)
        dd_th_IK = yct.getDesiredDOFAccelerations(th_IK, th, d_th_IK, dth, ddth_r, Kk, Dk)
                        
        ype.flatten(d_th_IK, d_th_IK_flat)
        ype.flatten(dd_th_IK, dd_th_IK_flat)
        '''
        ############################
        
        flagContact = True
        if dH_des==None or np.any(np.isnan(dH_des)) == True:
            flagContact = False 
        '''
        0 : initial
        1 : contact
        2 : fly
        3 : landing
        '''
        if flagContact == False :
            if stage == 1:
                stage = 2
                print("fly")
        else:
            if stage == 0:
                stage = 1
                print("contact")
            elif stage == 2:
                stage = 3 
                print("landing")


        if stage == 3:
            Bt = Bt*0.8
            Bl = Bl*1

        # optimization
                
        mot.addTrackingTerms(problem, totalDOF, Bt, w, ddth_des_flat)
        
        #mot.addTrackingTerms(problem, totalDOF, Bk, w_IK, dd_th_IK_flat)       
                
        mot.addSoftPointConstraintTerms(problem, totalDOF, Bsc, ddP_des1, Q1, q_bias1)

        #mot.addSoftPointConstraintTerms(problem, totalDOF, Bp, ddP_des2, Q2, q_bias2)

        #mot.addConstraint(problem, totalDOF, JsupL, dJsupL, dth_flat, a_sup)
        #mot.addConstraint(problem, totalDOF, JsupR, dJsupR, dth_flat, a_sup2)
        
       

        desLinearAccL = [0,0,0]
        desAngularAccL = [0,0,0]
        desLinearAccR = [0,0,0]
        desAngularAccR = [0,0,0]

        refPos = motionModel.getBodyPositionGlobal(supL)
        refPos[0] += ModelOffset[0]
        refPos[1] = 0
                        
        refVel = motionModel.getBodyVelocityGlobal(supL)        
        curPos = controlModel.getBodyPositionGlobal(supL)
        #curPos[1] = 0
        curVel = controlModel.getBodyVelocityGlobal(supL)
        refAcc = (0,0,0)
                
        if stage == 3:
            refPos = curPos
            refPos[1] = 0
            if curPos[1] < 0.0:
                curPos[1] = 0
        else :
            curPos[1] = 0
        rd_DesPosL[0] = refPos

        #(p_r, p, v_r, v, a_r, Kt, Dt)
        desLinearAccL = yct.getDesiredAcceleration(refPos, curPos, refVel, curVel, refAcc, Kk, Dk)
        #desLinearAccL[1] = 0
         
        refPos = motionModel.getBodyPositionGlobal(supR)
        refPos[0] += ModelOffset[0]
        refPos[1] = 0    

        refVel = motionModel.getBodyVelocityGlobal(supR)        
        curPos = controlModel.getBodyPositionGlobal(supR)
        #curPos[1] = 0
        curVel = controlModel.getBodyVelocityGlobal(supR)
        
        if stage == 3:
            refPos = curPos
            refPos[1] = 0
            if curPos[1] < 0.0:
                curPos[1] = 0
        else :
            curPos[1] = 0
        rd_DesPosR[0] = refPos

        desLinearAccR = yct.getDesiredAcceleration(refPos, curPos, refVel, curVel, refAcc, Kk, Dk)
        #desLinearAccR[1] = 0
                
        #(th_r, th, dth_r, dth, ddth_r, Kt, Dt)
        refAng = [preFootOrientationL]
        curAng = [controlModel.getBodyOrientationGlobal(supL)]
        refAngVel = motionModel.getBodyAngVelocityGlobal(supL)
        curAngVel = controlModel.getBodyAngVelocityGlobal(supL)
        refAngAcc = (0,0,0)
                        
        #desAngularAccL = yct.getDesiredAngAccelerations(refAng, curAng, refAngVel, curAngVel, refAngAcc, Kk, Dk)
        curAngY = np.dot(curAng, np.array([0,1,0]))
        aL = mm.logSO3(mm.getSO3FromVectors(curAngY[0], np.array([0,1,0])))
        print("curAngYL=",curAngY, "aL=", aL)
        desAngularAccL = [Kk*aL + Dk*(refAngVel-curAngVel)]

        refAng = [preFootOrientationR]
        curAng = [controlModel.getBodyOrientationGlobal(supR)]
        refAngVel = motionModel.getBodyAngVelocityGlobal(supR)
        curAngVel = controlModel.getBodyAngVelocityGlobal(supR)
        refAngAcc = (0,0,0)
        
        #desAngularAccR = yct.getDesiredAngAccelerations(refAng, curAng, refAngVel, curAngVel, refAngAcc, Kk, Dk)   
        curAngY = np.dot(curAng, np.array([0,1,0]))
        aL = mm.logSO3(mm.getSO3FromVectors(curAngY[0], np.array([0,1,0])))
        desAngularAccR = [Kk*aL + Dk*(refAngVel-curAngVel)]
            
        print("curAngYR=",curAngY, "aL=", aL)

        a_sup_2 = [desLinearAccL[0], desLinearAccL[1], desLinearAccL[2], desAngularAccL[0][0], desAngularAccL[0][1], desAngularAccL[0][2], 
                   desLinearAccR[0], desLinearAccR[1], desLinearAccR[2], desAngularAccR[0][0], desAngularAccR[0][1], desAngularAccR[0][2]]

        if stage == 2 :#or stage == 3:
            refAccL = motionModel.getBodyAccelerationGlobal(supL)
            refAndAccL = motionModel.getBodyAngAccelerationGlobal(supL)
            refAccR = motionModel.getBodyAccelerationGlobal(supR)
            refAndAccR = motionModel.getBodyAngAccelerationGlobal(supR)
            a_sup_2 = [refAccL[0], refAccL[1], refAccL[2], refAndAccL[0], refAndAccL[1], refAndAccL[2],
                       refAccR[0], refAccR[1], refAccR[2], refAndAccR[0], refAndAccR[1], refAndAccR[2]]
            '''
            a_sup_2 = [0,0,0, desAngularAccL[0][0], desAngularAccL[0][1], desAngularAccL[0][2], 
                       0,0,0, desAngularAccR[0][0], desAngularAccR[0][1], desAngularAccR[0][2]]
            '''
                    
        Jsup_2 = np.vstack((JsupL, JsupR))
        dJsup_2 = np.vstack((dJsupL, dJsupR))
        
        if flagContact == True:
            mot.addLinearTerms(problem, totalDOF, Bl, dL_des_plane, R, r_bias) 
            mot.addAngularTerms(problem, totalDOF, Bh, dH_des, S, s_bias)
                   
        mot.setConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)
        #mot.setConstraint(problem, totalDOF, JsupR, dJsupR, dth_flat, a_sup2)
        #mot.setConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)
        #mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2, d_th_IK_flat, a_sup_2)

        '''
        jZ = np.dot(dJsup_2.T, dJsup_2)

        lamda = 0.001

        for i in range(len(jZ)):
            for j in range(len(jZ[0])):
                if i == j :
                    jZ[i][j] += lamda

        jZInv = npl.pinv(jZ)
        jA = np.dot(Jsup_2, np.dot(jZInv, np.dot(dJsup_2.T, -Jsup_2)))
        mot.addConstraint2(problem, totalDOF, jA, a_sup_2)
        '''
        
        r = problem.solve()
        problem.clear()
        ype.nested(r['x'], ddth_sol)
                      
        rootPos[0] = controlModel.getBodyPositionGlobal(selectedBody)
        localPos = [[0, 0, 0]]   
                
        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
     
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals, contactForces)
                        
            controlModel.setDOFAccelerations(ddth_sol)
            controlModel.solveHybridDynamics()
            
            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0 or extraForce[0][2] != 0) :
                forceApplyFrame += 1
                vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                applyedExtraForce[0] = extraForce[0]
            
            if forceApplyFrame*wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0
            
            vpWorld.step()                    
            
        # rendering
        rd_footCenter[0] = footCenter
        rd_footCenterL[0] = preFootCenterL
        rd_footCenterR[0] = preFootCenterR
        
        rd_CM[0] = CM
        
        rd_CM_plane[0] = CM_plane.copy()
        
        rd_footCenter_ref[0] = footCenter_ref
        rd_CM_plane_ref[0] = CM_plane_ref.copy()

        #rd_CM_plane[0][1] = 0.
        
        if CP!=None and dCP!=None:
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des
        
        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des
        
        rd_grf_des[0] = dL_des_plane - totalMass*mm.s2v(wcfg.gravity)
                
        rd_exf_des[0] = applyedExtraForce[0]
        #print("rd_exf_des", rd_exf_des[0])
        rd_root_des[0] = rootPos[0]

        rd_CMP[0] = softConstPoint

        rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(constBody)-softConstPoint
        
        #if (applyedExtraForce[0][0] != 0 or applyedExtraForce[0][1] != 0 or applyedExtraForce[0][2] != 0) :
        if (forceApplyFrame == 0) :
            applyedExtraForce[0] = [0, 0, 0]

    viewer.setSimulateCallback(simulateCallback)
    
    viewer.startTimer(1/60.)
    viewer.show()
    
    Fl.run()
Ejemplo n.º 21
0
def create_biped():
    # motion
    #motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        motionName = 'wd2_stand.bvh'
    elif MOTION == STAND2:
        motionName = 'ww13_41_V001.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == TAEKWONDO2:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == KICK:
        motionName = 'wd2_n_kick.bvh'
    elif MOTION == WALK:
        motionName = 'wd2_WalkForwardNormal00.bvh'
    elif MOTION == TIPTOE:
        motionName = './MotionFile/cmu/15_07_15_07.bvh'

    #motionName = 'ww13_41_V001.bvh'
    scale = 0.01
    if MOTION == WALK:
        scale = 1.0
    elif MOTION == TIPTOE:
        scale = 0.01

    motion = yf.readBvhFile(motionName, scale)

    if MOTION != WALK:
        yme.removeJoint(motion, HEAD, False)
        yme.removeJoint(motion, RIGHT_SHOULDER, False)
        yme.removeJoint(motion, LEFT_SHOULDER, False)

    if FOOT_PART_NUM == 1 and MOTION != WALK:
        yme.removeJoint(motion, RIGHT_TOES_END, False)
        yme.removeJoint(motion, LEFT_TOES_END, False)
    elif (FOOT_PART_NUM == 5 or FOOT_PART_NUM == 6) and MOTION != WALK:
        yme.removeJoint(motion, RIGHT_TOES, False)
        yme.removeJoint(motion, RIGHT_TOES_END, False)
        yme.removeJoint(motion, LEFT_TOES, False)
        yme.removeJoint(motion, LEFT_TOES_END, False)

    if MOTION != WALK:
        yme.removeJoint(motion, RIGHT_HAND_END, False)
        yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1, 0, 0), .01), False)

    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(0, 0, 1), -.01), False)

    if FOOT_PART_NUM == 1:
        yme.rotateJointLocal(motion, LEFT_FOOT,
                             mm.exp(mm.v3(2.5, -0.0, .3), -.5), False)
        yme.rotateJointLocal(motion, RIGHT_FOOT,
                             mm.exp(mm.v3(2.5, 0.0, -.3), -.5), False)

    if MOTION == WALK:
        yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1., -0.0, .0),
                                                       .4), False)
        yme.rotateJointLocal(motion, RIGHT_FOOT,
                             mm.exp(mm.v3(1., 0.0, -.0), .4), False)
        #yme.rotateJointLocal(motion, SPINE1, mm.exp(mm.v3(1.,0.0,0.0), -.8), False)

    if MOTION == FORWARD_JUMP:
        yme.rotateJointLocal(motion, LEFT_UP_LEG,
                             mm.exp(mm.v3(0.0, .0, 1.), .08), False)
        yme.rotateJointLocal(motion, LEFT_LEG, mm.exp(mm.v3(0.0, 1.0, 0.),
                                                      -.2), False)

    if FOOT_PART_NUM == 6:

        yme.addJoint(motion, LEFT_FOOT, LEFT_METATARSAL_1,
                     (-0.045, -0.06, 0.03))
        yme.addJoint(motion, LEFT_FOOT, LEFT_METATARSAL_3,
                     (0.045, -0.06, 0.03))  #-0.0037

        yme.addJoint(motion, LEFT_METATARSAL_1, LEFT_PHALANGE_1,
                     (0.0, 0.0, 0.0715))
        yme.addJoint(motion, LEFT_METATARSAL_3, LEFT_PHALANGE_3,
                     (0.0, 0.0, 0.0715))
        yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_PHALANGE_Dummy1',
                     (0.0, 0.0, 0.1))
        yme.addJoint(motion, LEFT_PHALANGE_3, 'LEFT_PHALANGE_Dummy2',
                     (0.0, 0.0, 0.1))

        yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_1, (0.0, -0.06, -0.02))
        yme.addJoint(motion, LEFT_CALCANEUS_1, 'LEFT_CALCANEUS_Dummy1',
                     (0.0, 0.0, -0.1))

        yme.addJoint(motion, RIGHT_FOOT, RIGHT_METATARSAL_1,
                     (0.045, -0.06, 0.03))
        yme.addJoint(motion, RIGHT_FOOT, RIGHT_METATARSAL_3,
                     (-0.045, -0.06 - 0.0062, 0.03 + 0.0035))

        yme.addJoint(motion, RIGHT_METATARSAL_1, RIGHT_PHALANGE_1,
                     (0.0, 0.0, 0.0715))
        yme.addJoint(motion, RIGHT_METATARSAL_3, RIGHT_PHALANGE_3,
                     (0.0, 0.0, 0.0715))
        yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_PHALANGE_Dummy1',
                     (0.0, 0.0, 0.1))
        yme.addJoint(motion, RIGHT_PHALANGE_3, 'RIGHT_PHALANGE_Dummy2',
                     (0.0, 0.0, 0.1))

        yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_1,
                     (0.0, -0.06, -0.02))
        yme.addJoint(motion, RIGHT_CALCANEUS_1, 'RIGHT_CALCANEUS_Dummy1',
                     (0.0, 0.0, -0.1))

        yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                             mm.exp(mm.v3(.0, 0.0, 1.0), 3.14), False)
        yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                             mm.exp(mm.v3(.0, 0.0, 1.0), 3.14), False)
        ''' 
        yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0,0.0), 3.14*0.3), False)
        yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0,0.0, 0.0), 3.14*0.3), False)
        
        yme.rotateJointLocal(motion, RIGHT_PHALANGE_1, mm.exp(mm.v3(1.0,0.0,0.0), -3.14*0.3), False)
        yme.rotateJointLocal(motion, RIGHT_PHALANGE_3, mm.exp(mm.v3(1.0,0.0, 0.0), -3.14*0.3), False)
        yme.rotateJointLocal(motion, LEFT_PHALANGE_1, mm.exp(mm.v3(1.0,0.0,0.0), -3.14*0.3), False)
        yme.rotateJointLocal(motion, LEFT_PHALANGE_3, mm.exp(mm.v3(1.0,0.0, 0.0), -3.14*0.3), False)
        '''

        yme.rotateJointLocal(motion, LEFT_FOOT,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), 0.2012), False)
        yme.rotateJointLocal(motion, LEFT_METATARSAL_1,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), -0.2172), False)
        yme.rotateJointLocal(motion, LEFT_METATARSAL_3,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), -0.2172), False)
        yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), 0.2172), False)

        yme.rotateJointLocal(motion, RIGHT_FOOT,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), 0.2283), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_1,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), -0.2171), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), -0.2171), False)
        yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                             mm.exp(mm.v3(1.0, 0.0, 0.0), 0.2171), False)

        yme.rotateJointLocal(motion, RIGHT_METATARSAL_1,
                             mm.exp(mm.v3(0.0, 0.0, 1.0), 0.0747), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3,
                             mm.exp(mm.v3(0.0, 0.0, 1.0), 0.0747), False)
        '''
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_1, mm.exp(mm.v3(1.0,0.0,0.0), -0.1), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3, mm.exp(mm.v3(1.0,0.0,0.0), -0.1), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_1, mm.exp(mm.v3(0.0,0.0,1.0), 0.06), False)
        yme.rotateJointLocal(motion, RIGHT_METATARSAL_3, mm.exp(mm.v3(0.0,0.0,1.0), 0.06), False)
        yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0,0.0,0.0), -0.05), False) 
        '''

        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(0.0,0.0,1.0), 0.0656), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0,0.0), 0.0871), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(0.0,0.0,1.0), 0.0087), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0,0.0), 0.0933), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(0.0,0.0,1.0), 0.0746), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0,0.0), -6.3773e-03), False)

        #yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0,0.0, 0.0), math.pi*0.25), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0, 0.0), math.pi*0.25), False)
        #yme.rotateJointLocal(motion, LEFT_PHALANGE_1, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.25), False)
        #yme.rotateJointLocal(motion, RIGHT_PHALANGE_1, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.25), False)
        #yme.rotateJointLocal(motion, LEFT_PHALANGE_3, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.25), False)
        #yme.rotateJointLocal(motion, RIGHT_PHALANGE_3, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.25), False)

        #yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0,0.0, 0.0), -math.pi*0.16), False)
        #yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0,0.0, 0.0), -math.pi*0.16), False)
        #yme.rotateJointLocal(motion, LEFT_CALCANEUS_1, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.16), False)
        #yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.16), False)

        #yme.rotateJointLocal(motion, LEFT_METATARSAL_3, mm.exp(mm.v3(1.0,0.0,0.0), -math.pi*0.5), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    elif MOTION == TAEKWONDO2:
        ## Taekwondo base-step
        #motion = motion[0:31+40]
        ## Taekwondo turning-kick
        motion = motion[108:-1]
        #motion = motion[108:109]
    elif MOTION == KICK:
        #motion = motion[141:-1]
        #motion = motion[100:-1]
        #motion = motion[58:-1]
        motion = motion[82:-1]
        #motion = motion[0:-1]
    elif MOTION == STAND2:
        motion = motion[1:-1]
    elif MOTION == TIPTOE:
        #motion = motion[183:440]
        #motion = motion[350:410]
        motion = motion[350:550]

    motion[0:0] = [motion[0]] * 40
    motion.extend([motion[-1]] * 5000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .9

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    #node.length = .2 ####

    if FOOT_PART_NUM == 1:
        length1 = .35
        width1 = .2
        mass1 = 4.3
    elif FOOT_PART_NUM == 6:
        mass0 = .4
        width0 = 0.028
        length0 = 0.1

        #Metatarsal1
        length1 = .15
        width1 = width0 * 3
        mass1 = mass0 * 1.8
        #Metatarsal3
        length3 = .11
        width3 = width0 * 3
        mass3 = mass0 * 1.86
        #Calcaneus1
        length4 = .08
        width4 = 0.15 * 1
        mass4 = mass0 * 1.2 * 2.
        #Phalange1
        length5 = .08
        width5 = width1
        mass5 = mass0 * 1.355
        #Phalange3
        length7 = length5
        width7 = width5
        mass7 = mass5

        #Talus
        length8 = .13
        width8 = width0 * 3
        mass8 = mass0 * 2.

    if FOOT_PART_NUM == 6:
        node = mcfg.getNode(RIGHT_FOOT)
        node.length = length8
        node.width = width8
        node.mass = mass8

        node = mcfg.getNode(RIGHT_METATARSAL_1)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node = mcfg.getNode(RIGHT_METATARSAL_3)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(RIGHT_PHALANGE_1)
        node.length = length5
        node.width = width5
        node.mass = mass5
        node.offset = (0.0, 0.0, 0.03)
        node = mcfg.getNode(RIGHT_PHALANGE_3)
        node.length = length7
        node.width = width7
        node.mass = mass7
        node.offset = (0.0, 0.0, 0.01)

        node = mcfg.getNode(RIGHT_CALCANEUS_1)
        node.length = length4
        node.width = width4
        node.mass = mass4

        node = mcfg.getNode(LEFT_FOOT)
        node.length = length8
        node.width = width8
        node.mass = mass8

        node = mcfg.getNode(LEFT_METATARSAL_1)
        node.length = length1
        node.width = width1
        node.mass = mass1
        node = mcfg.getNode(LEFT_METATARSAL_3)
        node.length = length3
        node.width = width3
        node.mass = mass3
        node = mcfg.getNode(LEFT_PHALANGE_1)
        node.length = length5
        node.width = width5
        node.mass = mass5
        node.offset = (0.0, 0.0, 0.03)
        node = mcfg.getNode(LEFT_PHALANGE_3)
        node.length = length7
        node.width = width7
        node.mass = mass7
        node.offset = (0.0, 0.0, 0.01)

        node = mcfg.getNode(LEFT_CALCANEUS_1)
        node.length = length4
        node.width = width4
        node.mass = mass4

    if FOOT_PART_NUM < 5:
        node = mcfg.getNode(RIGHT_FOOT)
        node.length = length1
        node.width = width1
        node.mass = mass1

        node = mcfg.getNode(LEFT_FOOT)
        node.length = length1
        node.width = width1
        node.mass = mass1

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 30
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    if FOOT_PART_NUM == 1:
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .3,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .5,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .3,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .3
        }
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: 1.,
            SPINE1: .3,
            RIGHT_FOOT: 1.,
            LEFT_FOOT: 1.,
            HIP: 1.,
            RIGHT_UP_LEG: 1.,
            RIGHT_LEG: 1.,
            LEFT_UP_LEG: 1.,
            LEFT_LEG: 1.
        }
    elif FOOT_PART_NUM == 6:
        config['weightMap2'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .5,
            SPINE1: .3,
            RIGHT_FOOT: .7,
            LEFT_FOOT: .7,
            HIP: .5,
            RIGHT_UP_LEG: .7,
            RIGHT_LEG: .7,
            LEFT_UP_LEG: .7,
            LEFT_LEG: .7,
            LEFT_METATARSAL_1: .7,
            RIGHT_METATARSAL_1: .7,
            LEFT_METATARSAL_3: .7,
            RIGHT_METATARSAL_3: .7,
            RIGHT_CALCANEUS_1: .7,
            LEFT_CALCANEUS_1: .7,
            LEFT_PHALANGE_1: .4,
            LEFT_PHALANGE_3: .4,
            RIGHT_PHALANGE_1: .4,
            RIGHT_PHALANGE_3: .4
        }
        config['weightMap'] = {
            RIGHT_ARM: .2,
            RIGHT_FORE_ARM: .2,
            LEFT_ARM: .2,
            LEFT_FORE_ARM: .2,
            SPINE: .3,
            SPINE1: .2,
            RIGHT_FOOT: .3,
            LEFT_FOOT: .3,
            HIP: .3,
            RIGHT_UP_LEG: .1,
            RIGHT_LEG: .2,
            LEFT_UP_LEG: .1,
            LEFT_LEG: .2,
            LEFT_METATARSAL_1: .1,
            RIGHT_METATARSAL_1: .1,
            LEFT_METATARSAL_3: .1,
            RIGHT_METATARSAL_3: .1,
            RIGHT_CALCANEUS_1: .2,
            LEFT_CALCANEUS_1: .2,
            LEFT_PHALANGE_1: .1,
            LEFT_PHALANGE_3: .1,
            RIGHT_PHALANGE_1: .1,
            RIGHT_PHALANGE_3: .1
        }
        '''
        config['weightMap2']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.3, SPINE1:.3, RIGHT_FOOT:.3, LEFT_FOOT:.3, HIP:.5,
                        RIGHT_UP_LEG:.1, RIGHT_LEG:.3, LEFT_UP_LEG:.1, LEFT_LEG:.3, 
                        LEFT_METATARSAL_3:.2, RIGHT_METATARSAL_3:.2, RIGHT_CALCANEUS:1.2, LEFT_CALCANEUS:1.2,
                        LEFT_PHALANGE_1:.2, LEFT_PHALANGE_3:.1, RIGHT_PHALANGE_1:.2, RIGHT_PHALANGE_3:.2}
        
        config['weightMap2']={RIGHT_ARM:.2, RIGHT_FORE_ARM:.2, LEFT_ARM:.2, LEFT_FORE_ARM:.2, SPINE:.8, SPINE1:.3, RIGHT_FOOT:1., LEFT_FOOT:1., HIP:1.,
                        RIGHT_UP_LEG:1., RIGHT_LEG:1., LEFT_UP_LEG:1., LEFT_LEG:1.,                         
                        LEFT_METATARSAL_3:1., RIGHT_METATARSAL_3:1., RIGHT_CALCANEUS:.3, LEFT_CALCANEUS:.3,
                        LEFT_PHALANGE_1:.3, LEFT_PHALANGE_3:.3, RIGHT_PHALANGE_1:.3, RIGHT_PHALANGE_3:.3}
        '''

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    #config['end'] = HIP
    config['end'] = SPINE1
    config['const'] = HIP
    config['root'] = HIP

    config['FootPartNum'] = FOOT_PART_NUM

    if FOOT_PART_NUM == 6:
        config['FootLPart'] = [
            LEFT_FOOT, LEFT_METATARSAL_1, LEFT_METATARSAL_3, LEFT_PHALANGE_1,
            LEFT_PHALANGE_3, LEFT_CALCANEUS_1
        ]
        config['FootRPart'] = [
            RIGHT_FOOT, RIGHT_METATARSAL_1, RIGHT_METATARSAL_3,
            RIGHT_PHALANGE_1, RIGHT_PHALANGE_3, RIGHT_CALCANEUS_1
        ]
    else:
        config['FootLPart'] = [
            LEFT_FOOT, LEFT_TOES, LEFT_TARSUS, LEFT_TOES_SIDE_R,
            LEFT_FOOT_SIDE_L, LEFT_FOOT_SIDE_R
        ]
        config['FootRPart'] = [
            RIGHT_FOOT, RIGHT_TOES, RIGHT_TARSUS, RIGHT_TOES_SIDE_R,
            RIGHT_FOOT_SIDE_L, RIGHT_FOOT_SIDE_R
        ]

    return motion, mcfg, wcfg, stepsPerFrame, config
Ejemplo n.º 22
0
    hRef = .1
    vRef = .5
    clHeel = yma.getElementContactStates(motion, LFOOT, hRef, vRef)
    crHeel = yma.getElementContactStates(motion, RFOOT, hRef, vRef)
    clToe = yma.getElementContactStates(motion, LTOE, hRef, vRef)
    crToe = yma.getElementContactStates(motion, RTOE, hRef, vRef)
    clFoot = map(op.or_, clHeel, clToe)
    crFoot = map(op.or_, crHeel, crToe)

    lFootStates = yma.getFootStates(clHeel, clToe)
    rFootStates = yma.getFootStates(crHeel, crToe)
    lIntervals, lStates = yma.states2intervals(lFootStates)
    rIntervals, rStates = yma.states2intervals(rFootStates)

    footNames = [LFOOT, RFOOT]
    horizontalDirection = mm.v3(-1, 0, 0)
    horizontalRight = np.cross(horizontalDirection, (0, 1, 0))
    horizontalLeft = -horizontalRight

    sagittalAxis = horizontalRight
    lateralAxisMap = {LFOOT: horizontalDirection, RFOOT: -horizontalDirection}

    size_sagittals_map = {
        LFOOT: [None] * len(motion),
        RFOOT: [None] * len(motion)
    }
    size_laterals_map = {
        LFOOT: [None] * len(motion),
        RFOOT: [None] * len(motion)
    }
    for i in range(len(motion)):
Ejemplo n.º 23
0
def main():

    np.set_printoptions(precision=4, linewidth=200)

    #    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()
    mcfg_motion = mit.normal_mcfg()

    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    motionModel.recordVelByFiniteDiff()
    IKModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)

    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)

    footPartNum = config['FootPartNum']

    if footPartNum > 1:
        elasticity = 2000
        damping = 2 * (elasticity**.5)

        springBody1 = 1
        springBody2 = 2
        springBody1Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        springBody2Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))

        initialDist = mm.length(springBody1Pos - springBody2Pos) * 1.
        node = mcfg.getNode(mit.LEFT_METATARSAL_1)
        initialDist -= node.width  #0.084
        v1 = (-node.width * 0.5, 0.0, node.length * 0.4)
        v2 = (node.width * 0.5, 0.0, node.length * 0.4)
        #controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
        #controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)

        elasticity = 10
        damping = 2 * (elasticity**.5)
        springBody1 = 3
        springBody2 = 4
        node = mcfg.getNode(mit.LEFT_PHALANGE_1)
        springBody1Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]))
        springBody2Pos = motionModel.getBodyPositionGlobal(
            motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]))
        initialDist = mm.length(springBody1Pos - springBody2Pos) * 1.
        initialDist -= node.width  #0.084
        v1 = (-node.width * 0.5, 0.0, -node.length * 0.4)
        v2 = (node.width * 0.5, 0.0, -node.length * 0.4)
        #controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootLPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootLPart'][springBody2]), elasticity, damping, v2, v1, initialDist)
        #controlModel.setSpring(motion[0].skeleton.getJointIndex(config['FootRPart'][springBody1]), motion[0].skeleton.getJointIndex(config['FootRPart'][springBody2]), elasticity, damping, v1, v2, initialDist)

    vpWorld.initialize()
    controlModel.initializeHybridDynamics()

    #ModelOffset = (1.5, -0.01, 0)
    ModelOffset = (1.5, 0.04, 0)
    controlModel.translateByOffset(ModelOffset)

    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()

    # parameter
    Kt = config['Kt']
    Dt = config['Dt']  # tracking gain
    Kl = config['Kl']
    Dl = config['Dl']  # linear balance gain
    Kh = config['Kh']
    Dh = config['Dh']  # angular balance gain
    Ks = config['Ks']
    Ds = config['Ds']  # penalty force spring gain

    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']

    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w2 = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap2'])
    #w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL = motion[0].skeleton.getJointIndex(config['supLink'])
    supR = motion[0].skeleton.getJointIndex(config['supLink2'])
    rootB = motion[0].skeleton.getJointIndex(config['root'])

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex(config['const'])

    # jacobian
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys_IK = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()

    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    Jcom = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcom = Jcom.copy()

    JcomAng = yjc.makeEmptyJacobian(DOFs, 1, False)
    dJcomAng = JcomAng.copy()

    ###############

    jFootL_IK = [None] * footPartNum
    jFootR_IK = [None] * footPartNum

    indexFootL = [None] * footPartNum
    indexFootR = [None] * footPartNum
    jFootL = [None] * footPartNum
    dJFootL = [None] * footPartNum
    jFootR = [None] * footPartNum
    dJFootR = [None] * footPartNum
    jointMasksFootL = [None] * footPartNum
    jointMasksFootR = [None] * footPartNum

    jAngFootL = [None] * footPartNum
    dJAngFootL = [None] * footPartNum
    jAngFootR = [None] * footPartNum
    dJAngFootR = [None] * footPartNum

    for i in range(footPartNum):

        jFootL_IK[i] = yjc.makeEmptyJacobian(DOFs, 1)
        jFootR_IK[i] = yjc.makeEmptyJacobian(DOFs, 1)

        jFootL[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootL[i] = jFootL[i].copy()
        jFootR[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootR[i] = jFootR[i].copy()

        jAngFootL[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootL[i] = jAngFootL[i].copy()
        jAngFootR[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootR[i] = jAngFootR[i].copy()

        indexFootL[i] = motion[0].skeleton.getJointIndex(
            config['FootLPart'][i])
        indexFootR[i] = motion[0].skeleton.getJointIndex(
            config['FootRPart'][i])

        jointMasksFootL[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootL[i])
        ]
        jointMasksFootR[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootR[i])
        ]

    constJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton,
                              [indexFootL[0], indexFootR[0]])
    ]
    #constJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [indexFootL[0]])]
    #constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)

    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks = [
        yjc.getLinkJointMask(motion[0].skeleton, selectedBody)
    ]
    #comLowerJointMasks = [yjc.getLinksJointMask(motion[0].skeleton, [motion[0].skeleton.getJointIndex('LeftLeg'), motion[0].skeleton.getJointIndex('RightLeg')])]
    comUpperJointMasks[0][0] = 0
    #comUpperJointMasks[0][1] = 1
    #comUpperJointMasks[0][10] = 1
    comUpperJointMasks[0][2] = 1
    comUpperJointMasks[0][11] = 1

    #print(comUpperJointMasks)

    comLowerJointMasks = [
        yjc.getLinksJointMask(motion[0].skeleton, [
            motion[0].skeleton.getJointIndex('LeftLeg'),
            motion[0].skeleton.getJointIndex('RightLeg')
        ])
    ]
    '''
    maskArray = [foreSupLJointMasks, foreSupRJointMasks, rearSupLJointMasks, rearSupRJointMasks]
    parentArray = [supL, supR, supL, supR]
    effectorArray = [foreSupL, foreSupR, rearSupL, rearSupR]
    for j in range(4) :
        for i in range(len(foreSupLJointMasks)) :
            if i == parentArray[j] or i == effectorArray[j] :
                maskArray[j][0][i] = 1
            else :
                maskArray[j][0][i] = 0
    '''
    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses)
    dTO = ymt.make_dTO(len(linkMasses))

    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0, 0, 0, 0, 0, 0)  #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0, 0, 0, 0, 0, 0]  #R
    a_sup_2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    CP_old = [mm.v3(0., 0., 0.)]

    # penalty method
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.] * len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    dth_IK = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)

    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM_ref = [None]
    rd_CM_des = [None]
    rd_CM = [None]
    rd_CM_vec = [None]
    rd_CM_ref_vec = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]
    rd_footCenter_des = [None]
    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]

    rd_root = [None]

    rd_footL_vec = [None]
    rd_footR_vec = [None]

    rd_CMP = [None]

    rd_DesPosL = [None]
    rd_DesPosR = [None]

    rd_DesForePosL = [None]
    rd_DesForePosR = [None]
    rd_DesRearPosL = [None]
    rd_DesRearPosR = [None]

    rd_Joint = [None]
    rd_Joint2 = [None]
    rd_Joint3 = [None]
    rd_Joint4 = [None]

    #rd_contactForces = [None]*10000
    #rd_contactPositions = [None]*10000
    rd_virtualForce = [None]

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0, 0, 0]

    normalVector = [[0, 2, 0]]

    if MULTI_VIEWER:
        viewer = ymv.MultiViewer(800, 655)
        #viewer = ymv.MultiViewer(1600, 1255)
        viewer.setRenderers1([
            cvr.VpModelRenderer(motionModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])
        viewer.setRenderers2([
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR, yr.POLYGON_FILL)
        ])

    else:
        viewer = ysv.SimpleViewer()
        #    viewer.record(False)
        #    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
        viewer.doc.addObject('motion', motion)
        viewer.doc.addRenderer(
            'motionModel',
            cvr.VpModelRenderer(motionModel, (100, 100, 100),
                                yr.POLYGON_FILL))  #(150,150,255)
        viewer.doc.addRenderer(
            'IKModel',
            cvr.VpModelRenderer(IKModel, (180, 180, 180), yr.POLYGON_FILL))
        viewer.doc.addRenderer(
            'controlModel',
            cvr.VpModelRenderer(controlModel, CHARACTER_COLOR,
                                yr.POLYGON_FILL))
        #viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))
        #viewer.doc.addRenderer('rd_footCenter_des', yr.PointsRenderer(rd_footCenter_des, (150,0,150))    )
        #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))
        #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
        viewer.doc.addRenderer('rd_CM_plane',
                               yr.PointsRenderer(rd_CM_plane, (255, 255, 0)))
        viewer.doc.addRenderer('rd_CM',
                               yr.PointsRenderer(rd_CM, (255, 0, 255)))
        viewer.doc.addRenderer('rd_CM_des',
                               yr.PointsRenderer(rd_CM_des, (64, 64, 255)))
        viewer.doc.addRenderer(
            'rd_CM_vec',
            yr.VectorsRenderer(rd_CM_vec, rd_CM_plane, (255, 0, 0), 3))
        #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (0,255,0)))
        #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (255,0,255)))
        #    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
        #    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
        #viewer.doc.addRenderer('rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP, (0,255,255), .001))

        viewer.doc.addRenderer(
            'rd_exf_des',
            yr.ForcesRenderer(rd_exf_des, rd_root_des, (0, 255, 0), .009,
                              0.04))

        viewer.doc.addRenderer('rd_Joint',
                               yr.PointsRenderer(rd_Joint, (255, 0, 0)))
        viewer.doc.addRenderer('rd_Joint2',
                               yr.PointsRenderer(rd_Joint2, (0, 255, 0)))
        viewer.doc.addRenderer('rd_Joint3',
                               yr.PointsRenderer(rd_Joint3, (0, 0, 255)))
        viewer.doc.addRenderer('rd_Joint4',
                               yr.PointsRenderer(rd_Joint4, (255, 255, 0)))

    stage = STATIC_BALANCING

    contactRendererName = []

    for i in range(motion[0].skeleton.getJointNum()):
        print(i, motion[0].skeleton.getJointName(i))

    desCOMOffset = 0.0

    pt = [0.]

    timeReport = [0.] * 7

    viewer.objectInfoWnd.comOffsetY.value(-0.05)
    viewer.objectInfoWnd.comOffsetZ.value(0.00)

    viewer.objectInfoWnd.begin()
    viewer.objectInfoWnd.Bc = Fl_Value_Input(100, 450, 40, 10, 'Bc')
    viewer.objectInfoWnd.Bc.value(0.1)
    viewer.objectInfoWnd.end()
    viewer.objectInfoWnd.labelKt.value(50)
    viewer.objectInfoWnd.labelKk.value(17)


    config['Phalange'] = [  motion[0].skeleton.getJointIndex('LeftPhalange_1'),\
                            motion[0].skeleton.getJointIndex('LeftPhalange_2'),\
                            motion[0].skeleton.getJointIndex('LeftPhalange_3'),\
                            motion[0].skeleton.getJointIndex('RightPhalange_1'),\
                            motion[0].skeleton.getJointIndex('RightPhalange_2'),\
                            motion[0].skeleton.getJointIndex('RightPhalange_3')]
    config['Metatarsal'] = [motion[0].skeleton.getJointIndex('LeftMetatarsal_1'),\
                            motion[0].skeleton.getJointIndex('LeftMetatarsal_2'),\
                            motion[0].skeleton.getJointIndex('LeftMetatarsal_3'),\
                            motion[0].skeleton.getJointIndex('RightMetatarsal_1'),\
                            motion[0].skeleton.getJointIndex('RightMetatarsal_2'),\
                            motion[0].skeleton.getJointIndex('RightMetatarsal_3')]
    config['Talus'] = [ motion[0].skeleton.getJointIndex('LeftTalus_1'),\
                        motion[0].skeleton.getJointIndex('LeftTalus_2'),\
                        motion[0].skeleton.getJointIndex('LeftTalus_3'),\
                        motion[0].skeleton.getJointIndex('RightTalus_1'),\
                        motion[0].skeleton.getJointIndex('RightTalus_2'),\
                        motion[0].skeleton.getJointIndex('RightTalus_3')]
    config['Calcaneus'] = [ motion[0].skeleton.getJointIndex('LeftCalcaneus_1'),\
                            motion[0].skeleton.getJointIndex('LeftCalcaneus_2'),\
                            motion[0].skeleton.getJointIndex('LeftCalcaneus_3'),\
                            motion[0].skeleton.getJointIndex('RightCalcaneus_1'),\
                            motion[0].skeleton.getJointIndex('RightCalcaneus_2'),\
                            motion[0].skeleton.getJointIndex('RightCalcaneus_3')]

    def simulateCallback(frame):

        curTime = time.time()

        if frame % 30 == 1: pt[0] = time.time()

        global g_initFlag
        global forceShowFrame
        global forceApplyFrame
        global JsysPre
        global JsupPreL
        global JsupPreR
        global JsupPre
        global softConstPoint
        global stage
        global contactRendererName
        global desCOMOffset

        #motionModel.update(motion[0])

        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, B_CM, B_CMSd, B_Toe = viewer.GetParam(
        )

        Dt = 2 * (Kt**.5)
        Dk = 2 * (Kk**.5)
        Dl = 2 * (Kl**.5)
        Dh = 2 * (Kh**.5)
        Dsc = 2 * (Ksc**.5)
        '''
        if Bsc == 0.0 :
            viewer.doc.showRenderer('softConstraint', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('softConstraint', True)
            renderer1 = viewer.doc.getRenderer('softConstraint')
            renderer1.rc.setLineWidth(0.1+Bsc*3)
            viewer.motionViewWnd.update(1, viewer.doc)
        '''
        pose = motion[0].copy()

        def solveIK(desComPos,
                    desIdxs,
                    desPos,
                    desOri,
                    cmW=10.,
                    posW=1.,
                    oriW=1.):
            numItr = 100
            dt = .5
            threshold = 0.1
            for i in range(0, numItr):
                jPart_IK = []
                print '----iter num', i
                IKModel.update(pose)

                th_r_IK = pose.getDOFPositions()
                jointPositions_IK = pose.getJointPositionsGlobal()
                jointAxeses_IK = pose.getDOFAxeses()
                linkPositions_IK = IKModel.getBodyPositionsGlobal()
                linkInertias_IK = IKModel.getBodyInertiasGlobal()

                CM_IK = yrp.getCM(linkPositions_IK, linkMasses, totalMass)
                print CM_IK
                P_IK = ymt.getPureInertiaMatrix(TO, linkMasses,
                                                linkPositions_IK, CM_IK,
                                                linkInertias_IK)

                yjc.computeJacobian2(Jsys_IK, DOFs, jointPositions_IK,
                                     jointAxeses_IK, linkPositions_IK,
                                     allLinkJointMasks)

                for j in range(0, len(desIdxs)):
                    jPart_IK.append(Jsys_IK[6 * desIdxs[j]:6 * desIdxs[j] + 6])

                J_IK, JAngCom_IK = np.vsplit(np.dot(P_IK, Jsys_IK), 2)
                dv_IK = cmW * (desComPos - CM_IK)

                for j in range(0, len(desIdxs)):
                    J_IK = np.vstack((J_IK, jPart_IK[j]))
                    pos_IK = IKModel.getBodyPositionGlobal(desIdxs[j])
                    dv_IK = np.append(dv_IK, posW * (desPos[j] - pos_IK))
                    ori_IK = IKModel.getBodyOrientationGlobal(desIdxs[j])
                    dv_IK = np.append(dv_IK,
                                      oriW * mm.logSO3(desOri[j] * ori_IK.T))
                #print dv_IK[0:3]
                dth_IK_solve = npl.lstsq(J_IK, dv_IK)
                dth_IK_x = dth_IK_solve[0][:totalDOF]
                ype.nested(dth_IK_x, dth_IK)
                #print dth_IK[0][0:3]
                th_IK = yct.getIntegralDOF(th_r_IK, dth_IK, dt)
                pose.setDOFPositions(th_IK)

                if np.dot(dv_IK, dv_IK) < threshold:
                    break

        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        CM_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        footCenterOffset = np.array([
            viewer.objectInfoWnd.comOffsetX.value(),
            viewer.objectInfoWnd.comOffsetY.value(),
            viewer.objectInfoWnd.comOffsetZ.value()
        ])
        #CM_IK_ref = footCenter + footCenterOffset
        CM_IK_ref = CM_ref + footCenterOffset
        #CM_IK_ref[1] = CM_ref[1] + footCenterOffset[1]

        motion[0].skeleton.getJointIndex(config['supLink'])

        #IKidxs = [indexFootL[0], indexFootR[0]]
        #IKdesPos = [motionModel.getBodyPositionGlobal(indexFootL[0]), motionModel.getBodyPositionGlobal(indexFootR[0])]
        #for i in range(0, 2):
        #    #IKdesPos[i] += ModelOffset
        #    IKdesPos[i][1] = 0.069
        #IKori = [motionModel.getBodyOrientationGlobal(indexFootL[0]), motionModel.getBodyOrientationGlobal(indexFootR[0])]
        #IKdesOri = [None]*2
        #for i in range(0, 2):
        #    IKdesOri[i] = mm.I_SO3()

        IKidxs = config['Phalange'][0:1] + config['Phalange'][3:4]
        print IKidxs
        IKdesPos = [None] * len(IKidxs)
        IKdesOri = [None] * len(IKidxs)
        for i in range(0, len(IKidxs)):
            #print i
            IKdesPos[i] = motionModel.getBodyPositionGlobal(IKidxs[i])
            IKdesPos[i][1] = 0.03
            IKdesOri[i] = mm.I_SO3()
        print IKdesPos

        solveIK(CM_IK_ref, IKidxs, IKdesPos, IKdesOri)

        # tracking
        th_r_ori = motion.getDOFPositions(frame)
        th_r = copy.copy(th_r_ori)

        global leftHipTimer
        if viewer.objectInfoWnd.onLeftHip:
            leftHipTimer = 60
            viewer.objectInfoWnd.onLeftHip = False
        if leftHipTimer > 0:
            viewer.objectInfoWnd.comOffsetX.value(
                0.14 * np.sin(2 * 3.14 * leftHipTimer / 60.))
            #viewer.objectInfoWnd.comOffsetZ.value(0.04*np.cos(2*3.14*leftHipTimer/90.))
            #B_Hipd = viewer.objectInfoWnd.labelLeftHip.value()
            #newR1 = mm.exp(mm.v3(0.0,1.0,0.0), 3.14*0.5*B_Hipd/100.)
            #idx = motion[0].skeleton.getJointIndex('LeftUpLeg')
            #th_r[idx] = np.dot(th_r[idx], newR1)
            #idx = motion[0].skeleton.getJointIndex('RightUpLeg')
            #th_r[idx] = np.dot(th_r[idx], newR1)
            leftHipTimer -= 1

        timeReport[0] += time.time() - curTime
        curTime = time.time()

        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r,
                                                  Kt, Dt)
        ddth_c = controlModel.getDOFAccelerations()

        ype.flatten(ddth_des, ddth_des_flat)
        ype.flatten(dth, dth_flat)

        ype.flatten(ddth_c, ddth_c_flat)

        # jacobian
        refFootL = motionModel.getBodyPositionGlobal(supL)
        refFootR = motionModel.getBodyPositionGlobal(supR)

        positionFootL = [None] * footPartNum
        positionFootR = [None] * footPartNum
        for i in range(footPartNum):
            positionFootL[i] = controlModel.getBodyPositionGlobal(
                indexFootL[i])
            positionFootR[i] = controlModel.getBodyPositionGlobal(
                indexFootR[i])

        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()

        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        CM_plane = copy.copy(CM)
        CM_plane[1] = 0.
        dCM_plane = copy.copy(dCM)
        dCM_plane[1] = 0.

        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        linkVelocities_ref = motionModel.getBodyVelocitiesGlobal()
        linkAngVelocities_ref = motionModel.getBodyAngVelocitiesGlobal()
        linkInertias_ref = motionModel.getBodyInertiasGlobal()

        CM_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        CM_plane_ref = copy.copy(CM_ref)
        CM_plane_ref[1] = 0.

        P = ymt.getPureInertiaMatrix(TO, linkMasses, linkPositions, CM,
                                     linkInertias)
        dP = ymt.getPureInertiaMatrixDerivative(dTO, linkMasses,
                                                linkVelocities, dCM,
                                                linkAngVelocities,
                                                linkInertias)

        timeReport[1] += time.time() - curTime
        curTime = time.time()

        yjc.computeJacobian2(Jsys, DOFs, jointPositions, jointAxeses,
                             linkPositions, allLinkJointMasks)
        timeReport[2] += time.time() - curTime
        curTime = time.time()

        # yjc.computeJacobianDerivative2(dJsys, DOFs, jointPositions, jointAxeses, linkAngVelocities, linkPositions, allLinkJointMasks)
        if frame > 0:
            dJsys = (Jsys - JsysPre) * 30.
        else:
            dJsys = (Jsys - Jsys)
        JsysPre = Jsys.copy()

        timeReport[3] += time.time() - curTime
        curTime = time.time()

        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
            bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)

        for i in range(len(bodyIDsToCheck)):
            controlModel.SetBodyColor(bodyIDsToCheck[i], 0, 0, 0, 255)

        contactFlagFootL = [0] * footPartNum
        contactFlagFootR = [0] * footPartNum
        partialDOFIndex = [22, 22]

        for i in range(len(bodyIDs)):
            controlModel.SetBodyColor(bodyIDs[i], 255, 105, 105, 200)
            index = controlModel.id2index(bodyIDs[i])
            for j in range(len(indexFootL)):
                if index == indexFootL[j]:
                    contactFlagFootL[j] = 1
            for j in range(len(indexFootR)):
                if index == indexFootR[j]:
                    contactFlagFootR[j] = 1

        for j in range(0, footPartNum):
            jAngFootR[j] = Jsys[6 * indexFootR[j]:6 * indexFootR[j] +
                                6][3:]  #.copy()
            jAngFootL[j] = Jsys[6 * indexFootL[j]:6 * indexFootL[j] +
                                6][3:]  #.copy()
            dJAngFootR[j] = dJsys[6 * indexFootR[j]:6 * indexFootR[j] +
                                  6][3:]  #.copy()
            dJAngFootL[j] = dJsys[6 * indexFootL[j]:6 * indexFootL[j] +
                                  6][3:]  #.copy()
            jFootR[j] = Jsys[6 * indexFootR[j]:6 * indexFootR[j] + 6]  #.copy()
            jFootL[j] = Jsys[6 * indexFootL[j]:6 * indexFootL[j] + 6]  #.copy()
            dJFootR[j] = dJsys[6 * indexFootR[j]:6 * indexFootR[j] +
                               6]  #.copy()
            dJFootL[j] = dJsys[6 * indexFootL[j]:6 * indexFootL[j] +
                               6]  #.copy()
        if footPartNum == 1:
            desFCL = (controlModel.getBodyPositionGlobal(supL))
            desFCR = (controlModel.getBodyPositionGlobal(supR))
        else:
            r = .5 + desCOMOffset
            desFCL = (controlModel.getBodyPositionGlobal(indexFootL[0]) * r +
                      controlModel.getBodyPositionGlobal(indexFootL[1]) *
                      (1.0 - r)
                      )  #controlModel.getBodyPositionGlobal(indexFootL[1])
            desFCR = (controlModel.getBodyPositionGlobal(indexFootR[0]) * r +
                      controlModel.getBodyPositionGlobal(indexFootR[1]) *
                      (1.0 - r)
                      )  #controlModel.getBodyPositionGlobal(indexFootR[1])
        desFC = desFCL + (desFCR - desFCL) / 2.0
        desFC[1] = 0
        rd_footCenter_des[0] = desFC.copy()
        curRelCMVec = CM_plane - desFC
        vecRatio = mm.length(curRelCMVec) * 0.
        #print(frame, vecRatio)
        footCenter = desFC - curRelCMVec * (vecRatio)  #/10.0

        footCenter = (
            getBodyGlobalPos(controlModel, motion, 'LeftCalcaneus_1') +
            getBodyGlobalPos(controlModel, motion, 'LeftPhalange_1') +
            getBodyGlobalPos(controlModel, motion, 'RightCalcaneus_1') +
            getBodyGlobalPos(controlModel, motion, 'RightPhalange_1')) / 4.
        #footCenter = (getBodyGlobalPos(controlModel, motion, 'LeftCalcaneus_1') + getBodyGlobalPos(controlModel, motion, 'LeftTalus_1') + getBodyGlobalPos(controlModel, motion, 'RightCalcaneus_1') + getBodyGlobalPos(controlModel, motion, 'RightTalus_1'))/4.

        footCenter_ref = refFootL + (refFootR - refFootL) / 2.0
        #footCenter_ref[1] = 0.
        footCenter[1] = 0.
        footCenterOffset = np.array([
            viewer.objectInfoWnd.comOffsetX.value(), 0,
            viewer.objectInfoWnd.comOffsetZ.value()
        ])
        #footCenter += footCenterOffset

        vecRatio = mm.length(curRelCMVec) * 0.
        softConstPointOffset = -curRelCMVec * (vecRatio)  #/10.0
        #print(frame, vecRatio, softConstPointOffset)

        desForeSupLAcc = [0, 0, 0]
        desForeSupRAcc = [0, 0, 0]

        totalNormalForce = [0, 0, 0]

        for i in range(len(contactForces)):
            totalNormalForce[0] += contactForces[i][0]
            totalNormalForce[1] += contactForces[i][1]
            totalNormalForce[2] += contactForces[i][2]

        #print((totalMass*mm.s2v(wcfg.gravity))[1])

        footCenterOffset = np.array([
            viewer.objectInfoWnd.comOffsetX.value(),
            viewer.objectInfoWnd.comOffsetY.value(),
            viewer.objectInfoWnd.comOffsetZ.value()
        ])

        ######################
        # optimization terms
        ######################

        # linear momentum
        CM_ref_plane = footCenter + footCenterOffset
        dL_des_plane = Kl * totalMass * (CM_ref_plane -
                                         CM_plane) - Dl * totalMass * dCM_plane
        dL_des_plane[1] = Kl * totalMass * (CM_ref[1] + footCenterOffset[1] -
                                            CM[1]) - Dl * totalMass * dCM[1]

        # angular momentum
        CP_ref = footCenter + footCenterOffset

        timeStep = 30.
        if CP_old[0] == None or CP == None:
            dCP = None
        else:
            dCP = (CP - CP_old[0]) / (1 / timeStep)
        CP_old[0] = CP

        if CP != None and dCP != None:
            ddCP_des = Kh * (CP_ref - CP) - Dh * (dCP)
            CP_des = CP + dCP * (1 / timeStep) + .5 * ddCP_des * (
                (1 / timeStep)**2)
            #dH_des = np.cross((CP_des - CM), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))
            dH_des = np.cross(
                (CP_des - CM_plane),
                (dL_des_plane + totalMass * mm.s2v(wcfg.gravity)))
        else:
            dH_des = None

        # momentum matrix
        RS = np.dot(P, Jsys)
        R, S = np.vsplit(RS, 2)

        rs = np.dot((np.dot(dP, Jsys) + np.dot(P, dJsys)), dth_flat)
        r_bias, s_bias = np.hsplit(rs, 2)

        flagContact = True
        if dH_des == None or np.any(np.isnan(dH_des)) == True:
            flagContact = False
            #viewer.doc.showRenderer('rd_grf_des', False)
            #viewer.motionViewWnd.update(1, viewer.doc)
        #else:
        #viewer.doc.showRenderer('rd_grf_des', True)
        #viewer.motionViewWnd.update(1, viewer.doc)
        '''
        0 : initial
        1 : contact
        2 : fly
        3 : landing
        '''

        trackingW = w

        #if checkAll(contactFlagFootR, 0) != 1 :
        if 0:  #stage == MOTION_TRACKING:
            trackingW = w2
            #stage = POWERFUL_BALANCING
            Bt = Bt * 2

        #######################
        # optimization
        #######################

        mot.addTrackingTerms(problem, totalDOF, Bt, trackingW, ddth_des_flat)

        #if flagContact == True:
        #    mot.addLinearTerms(problem, totalDOF, Bl, dL_des_plane, R, r_bias)
        #    mot.addAngularTerms(problem, totalDOF, Bh, dH_des, S, s_bias)

        a_sup_2 = None
        Jsup_2 = None
        dJsup_2 = None

        ##############################

        #if Jsup_2 != None:
        #    mot.addConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat, a_sup_2)

        timeReport[4] += time.time() - curTime
        curTime = time.time()

        r = problem.solve()
        problem.clear()
        ype.nested(r['x'], ddth_sol)

        rootPos[0] = controlModel.getBodyPositionGlobal(selectedBody)
        localPos = [[0, 0, 0]]

        timeReport[5] += time.time() - curTime
        curTime = time.time()

        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
                bodyIDsToCheck, mus, Ks, Ds)

            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals,
                                      contactForces)

            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0
                    or extraForce[0][2] != 0):
                forceApplyFrame += 1
                #vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                controlModel.applyBodyForceGlobal(selectedBody, extraForce[0])
                applyedExtraForce[0] = extraForce[0]

            if forceApplyFrame * wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0

            controlModel.setDOFAccelerations(ddth_sol)

            controlModel.solveHybridDynamics()

            vpWorld.step()

        if frame % 30 == 0:
            print 'elapsed time for 30 frames:', time.time() - pt[0]
        # rendering

        rd_footCenter[0] = footCenter

        rd_CM[0] = CM.copy()

        rd_CM_plane[0] = CM_plane.copy()

        rd_footCenter_ref[0] = footCenter_ref
        rd_CM_plane_ref[0] = CM_ref.copy()
        rd_CM_ref[0] = CM_ref.copy()
        rd_CM_ref_vec[0] = (CM_ref - footCenter_ref) * 3.
        rd_CM_vec[0] = (CM - CM_plane)
        rd_CM_des[0] = CM_ref_plane.copy()
        rd_CM_des[0][1] = .01

        #rd_CM_plane[0][1] = 0.

        if CP != None and dCP != None:
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des

        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des

        rd_grf_des[
            0] = totalNormalForce  # - totalMass*mm.s2v(wcfg.gravity)#dL_des_plane - totalMass*mm.s2v(wcfg.gravity)

        rd_exf_des[0] = applyedExtraForce[0]
        rd_root_des[0] = rootPos[0]

        rd_CMP[0] = softConstPoint

        rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(
            constBody) - softConstPoint

        #indexL = motion[0].skeleton.getJointIndex('Hips')
        #indexR = motion[0].skeleton.getJointIndex('Spine1')
        indexL = indexFootL[0]
        indexR = indexFootR[0]

        curAng = [controlModel.getBodyOrientationGlobal(indexL)]
        curAngY = np.dot(curAng, np.array([0, 0, 1]))

        rd_footL_vec[0] = np.copy(curAngY[0])
        rd_footCenterL[0] = controlModel.getBodyPositionGlobal(indexL)

        curAng = [controlModel.getBodyOrientationGlobal(indexR)]
        curAngY = np.dot(curAng, np.array([0, 0, 1]))

        rd_footR_vec[0] = np.copy(curAngY[0])
        rd_footCenterR[0] = controlModel.getBodyPositionGlobal(indexR)

        if (forceApplyFrame == 0):
            applyedExtraForce[0] = [0, 0, 0]

        timeReport[6] += time.time() - curTime
        # print timeReport

    viewer.setSimulateCallback(simulateCallback)

    viewer.startTimer(1 / 30.)
    viewer.show()

    Fl.run()
Ejemplo n.º 24
0
def main():

    np.set_printoptions(precision=4, linewidth=200)

    #    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_vchain_5()
    motion, mcfg, wcfg, stepsPerFrame, config = mit.create_biped()

    vpWorld = cvw.VpWorld(wcfg)
    motionModel = cvm.VpMotionModel(vpWorld, motion[0], mcfg)
    motionModel.recordVelByFiniteDiff()
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    vpWorld.initialize()
    controlModel.initializeHybridDynamics()

    #ModelOffset = (1.5, -0.01, 0)
    ModelOffset = (1.5, 0.0, 0)
    controlModel.translateByOffset(ModelOffset)

    totalDOF = controlModel.getTotalDOF()
    DOFs = controlModel.getDOFs()

    # parameter
    Kt = config['Kt']
    Dt = config['Dt']  # tracking gain
    Kl = config['Kl']
    Dl = config['Dl']  # linear balance gain
    Kh = config['Kh']
    Dh = config['Dh']  # angular balance gain
    Ks = config['Ks']
    Ds = config['Ds']  # penalty force spring gain

    Bt = config['Bt']
    Bl = config['Bl']
    Bh = config['Bh']

    w = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap'])
    w2 = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['weightMap2'])
    #w_IK = mot.getTrackingWeight(DOFs, motion[0].skeleton, config['IKweightMap'])
    supL = motion[0].skeleton.getJointIndex(config['supLink'])
    supR = motion[0].skeleton.getJointIndex(config['supLink2'])
    rootB = motion[0].skeleton.getJointIndex(config['root'])

    selectedBody = motion[0].skeleton.getJointIndex(config['end'])
    #constBody = motion[0].skeleton.getJointIndex('LeftForeArm')
    constBody = motion[0].skeleton.getJointIndex(config['const'])

    # jacobian
    Jsup = yjc.makeEmptyJacobian(DOFs, 1)
    dJsup = Jsup.copy()
    JsupPre = Jsup.copy()

    Jsys = yjc.makeEmptyJacobian(DOFs, controlModel.getBodyNum())
    dJsys = Jsys.copy()
    JsysPre = Jsys.copy()

    Jconst = yjc.makeEmptyJacobian(DOFs, 1)
    dJconst = Jconst.copy()

    ###############

    footPartNum = config['FootPartNum']

    indexFootL = [None] * footPartNum
    indexFootR = [None] * footPartNum
    jFootL = [None] * footPartNum
    dJFootL = [None] * footPartNum
    jFootR = [None] * footPartNum
    dJFootR = [None] * footPartNum
    jointMasksFootL = [None] * footPartNum
    jointMasksFootR = [None] * footPartNum

    jAngFootL = [None] * footPartNum
    dJAngFootL = [None] * footPartNum
    jAngFootR = [None] * footPartNum
    dJAngFootR = [None] * footPartNum

    for i in range(footPartNum):
        jFootL[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootL[i] = jFootL[i].copy()
        jFootR[i] = yjc.makeEmptyJacobian(DOFs, 1)
        dJFootR[i] = jFootR[i].copy()

        jAngFootL[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootL[i] = jAngFootL[i].copy()
        jAngFootR[i] = yjc.makeEmptyJacobian(DOFs, 1, False)
        dJAngFootR[i] = jAngFootR[i].copy()

        indexFootL[i] = motion[0].skeleton.getJointIndex(
            config['FootLPart'][i])
        indexFootR[i] = motion[0].skeleton.getJointIndex(
            config['FootRPart'][i])
        jointMasksFootL[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootL[i])
        ]
        jointMasksFootR[i] = [
            yjc.getLinkJointMask(motion[0].skeleton, indexFootR[i])
        ]

    constJointMasks = [yjc.getLinkJointMask(motion[0].skeleton, constBody)]
    allLinkJointMasks = yjc.getAllLinkJointMasks(motion[0].skeleton)
    '''
    maskArray = [foreSupLJointMasks, foreSupRJointMasks, rearSupLJointMasks, rearSupRJointMasks]
    parentArray = [supL, supR, supL, supR]
    effectorArray = [foreSupL, foreSupR, rearSupL, rearSupR]
    for j in range(4) :
        for i in range(len(foreSupLJointMasks)) :
            if i == parentArray[j] or i == effectorArray[j] :
                maskArray[j][0][i] = 1
            else :
                maskArray[j][0][i] = 0
    '''
    # momentum matrix
    linkMasses = controlModel.getBodyMasses()
    totalMass = controlModel.getTotalMass()
    TO = ymt.make_TO(linkMasses)
    dTO = ymt.make_dTO(len(linkMasses))

    # optimization
    problem = yac.LSE(totalDOF, 6)
    a_sup = (0, 0, 0, 0, 0, 0)  #L
    #a_sup2 = (0,0,0, 0,0,0)#R
    a_sup2 = [0, 0, 0, 0, 0, 0]  #R
    a_sup_2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    CP_old = [mm.v3(0., 0., 0.)]

    # penalty method
    bodyIDsToCheck = range(vpWorld.getBodyNum())
    mus = [1.] * len(bodyIDsToCheck)

    # flat data structure
    ddth_des_flat = ype.makeFlatList(totalDOF)
    dth_flat = ype.makeFlatList(totalDOF)
    ddth_sol = ype.makeNestedList(DOFs)

    d_th_IK = ype.makeNestedList(DOFs)
    d_th_IK_L = ype.makeNestedList(DOFs)
    d_th_IK_R = ype.makeNestedList(DOFs)
    dd_th_IK = ype.makeNestedList(DOFs)
    dd_th_IK_flat = ype.makeFlatList(totalDOF)
    d_th_IK_flat = ype.makeFlatList(totalDOF)
    ddth_c_flat = ype.makeFlatList(totalDOF)

    # viewer
    rd_footCenter = [None]
    rd_footCenter_ref = [None]
    rd_footCenterL = [None]
    rd_footCenterR = [None]
    rd_CM_plane = [None]
    rd_CM_plane_ref = [None]
    rd_CM_ref = [None]
    rd_CM = [None]
    rd_CM_vec = [None]
    rd_CM_ref_vec = [None]
    rd_CP = [None]
    rd_CP_des = [None]
    rd_dL_des_plane = [None]
    rd_dH_des = [None]
    rd_grf_des = [None]

    rd_exf_des = [None]
    rd_root_des = [None]
    rd_soft_const_vec = [None]

    rd_root = [None]

    rd_footL_vec = [None]
    rd_footR_vec = [None]

    rd_CMP = [None]

    rd_DesPosL = [None]
    rd_DesPosR = [None]

    rd_DesForePosL = [None]
    rd_DesForePosR = [None]
    rd_DesRearPosL = [None]
    rd_DesRearPosR = [None]

    rootPos = [None]
    selectedBodyId = [selectedBody]
    extraForce = [None]
    applyedExtraForce = [None]
    applyedExtraForce[0] = [0, 0, 0]

    normalVector = [[0, 2, 0]]

    viewer = ysv.SimpleViewer()
    #    viewer.record(False)
    #    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,255,255), yr.LINK_BONE))
    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer(
        'motionModel',
        cvr.VpModelRenderer(motionModel, (150, 150, 255), yr.POLYGON_FILL))
    viewer.doc.addRenderer(
        'controlModel',
        cvr.VpModelRenderer(controlModel, (255, 240, 255), yr.POLYGON_FILL))
    viewer.doc.addRenderer('rd_footCenter', yr.PointsRenderer(rd_footCenter))
    #viewer.doc.addRenderer('rd_footCenterL', yr.PointsRenderer(rd_footCenterL))
    #viewer.doc.addRenderer('rd_footCenterR', yr.PointsRenderer(rd_footCenterR))
    #viewer.doc.addRenderer('rd_CM_plane', yr.PointsRenderer(rd_CM_plane, (255,255,0)))
    viewer.doc.addRenderer('rd_CM', yr.PointsRenderer(rd_CM, (255, 255, 0)))
    viewer.doc.addRenderer('rd_CP_des',
                           yr.PointsRenderer(rd_CP_des, (0, 255, 0)))
    #viewer.doc.addRenderer('rd_CP_des', yr.PointsRenderer(rd_CP_des, (255,0,255)))
    #    viewer.doc.addRenderer('rd_dL_des_plane', yr.VectorsRenderer(rd_dL_des_plane, rd_CM, (255,255,0)))
    #    viewer.doc.addRenderer('rd_dH_des', yr.VectorsRenderer(rd_dH_des, rd_CM, (0,255,0)))
    viewer.doc.addRenderer(
        'rd_grf_des', yr.ForcesRenderer(rd_grf_des, rd_CP, (0, 255, 255),
                                        .001))

    viewer.doc.addRenderer(
        'rd_exf_des',
        yr.ForcesRenderer(rd_exf_des, rd_root_des, (0, 255, 0), .009, 0.05))

    #viewer.doc.addRenderer('rd_CMP', yr.PointsRenderer(rd_CMP, (0,0,255)))

    viewer.doc.addRenderer('rd_DesPosL',
                           yr.PointsRenderer(rd_DesPosL, (0, 0, 255)))
    viewer.doc.addRenderer('rd_DesPosR',
                           yr.PointsRenderer(rd_DesPosR, (0, 100, 255)))

    viewer.doc.addRenderer('rd_DesForePosL',
                           yr.PointsRenderer(rd_DesForePosL, (150, 0, 200)))
    viewer.doc.addRenderer('rd_DesForePosR',
                           yr.PointsRenderer(rd_DesForePosR, (150, 0, 250)))
    viewer.doc.addRenderer('rd_DesRearPosL',
                           yr.PointsRenderer(rd_DesRearPosL, (0, 150, 200)))
    viewer.doc.addRenderer('rd_DesRearPosR',
                           yr.PointsRenderer(rd_DesRearPosR, (0, 150, 250)))

    #viewer.doc.addRenderer('softConstraint', yr.VectorsRenderer(rd_soft_const_vec, rd_CMP, (255,0,0), 3))

    viewer.doc.addRenderer(
        'rd_footLVec',
        yr.VectorsRenderer(rd_footL_vec, rd_footCenterL, (255, 0, 0), 3))
    viewer.doc.addRenderer(
        'rd_footRVec',
        yr.VectorsRenderer(rd_footR_vec, rd_footCenterL, (255, 255, 0), 3))

    #viewer.doc.addRenderer('rd_footCenter_ref', yr.PointsRenderer(rd_footCenter_ref))
    viewer.doc.addRenderer('rd_CM_plane_ref',
                           yr.PointsRenderer(rd_CM_plane_ref, (255, 255, 0)))

    viewer.doc.addRenderer(
        'rd_refNormalVec',
        yr.VectorsRenderer(normalVector, rd_footCenter_ref, (255, 0, 0), 3))
    viewer.doc.addRenderer(
        'rd_refCMVec',
        yr.VectorsRenderer(rd_CM_ref_vec, rd_footCenter_ref, (255, 0, 255), 3))

    viewer.doc.addRenderer(
        'rd_curNormalVec',
        yr.VectorsRenderer(normalVector, rd_footCenter, (255, 0, 0), 3))
    viewer.doc.addRenderer(
        'rd_CMVec',
        yr.VectorsRenderer(rd_CM_vec, rd_footCenter, (255, 0, 255), 3))

    stage = STATIC_BALANCING

    def simulateCallback(frame):
        global g_initFlag
        global forceShowFrame
        global forceApplyFrame
        global JsysPre
        global JsupPreL
        global JsupPreR
        global JsupPre
        global softConstPoint
        global stage

        motionModel.update(motion[frame])

        Kt, Kk, Kl, Kh, Ksc, Bt, Bl, Bh, Bsc = viewer.GetParam()

        Dt = 2 * (Kt**.5)
        Dk = 2 * (Kk**.5)
        Dl = 2 * (Kl**.5)
        Dh = 2 * (Kh**.5)
        Dsc = 2 * (Ksc**.5)

        if Bsc == 0.0:
            viewer.doc.showRenderer('softConstraint', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('softConstraint', True)
            renderer1 = viewer.doc.getRenderer('softConstraint')
            renderer1.rc.setLineWidth(0.1 + Bsc * 3)
            viewer.motionViewWnd.update(1, viewer.doc)

        # tracking
        th_r = motion.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r,
                                                  Kt, Dt)
        ddth_c = controlModel.getDOFAccelerations()

        ype.flatten(ddth_des, ddth_des_flat)
        ype.flatten(dth, dth_flat)

        ype.flatten(ddth_c, ddth_c_flat)

        # jacobian
        '''
        if stage == POWERFUL_BALANCING:
        #if stage != MOTION_TRACKING:
            footCenterL = controlModel.getBodyPositionGlobal(supL)        
            footCenterR = controlModel.getBodyPositionGlobal(supR)
        else:
            footCenterL = controlModel.getBodyPositionGlobal(indexFootL[1])        
            footCenterR = controlModel.getBodyPositionGlobal(indexFootR[1])
        '''
        if footPartNum == 1:
            footCenterL = controlModel.getBodyPositionGlobal(supL)
            footCenterR = controlModel.getBodyPositionGlobal(supR)
        else:
            if stage == POWERFUL_BALANCING:
                footCenterL = controlModel.getBodyPositionGlobal(supL)
                footCenterR = controlModel.getBodyPositionGlobal(supR)
            else:
                footCenterL = (
                    controlModel.getBodyPositionGlobal(supL) +
                    controlModel.getBodyPositionGlobal(indexFootL[1])) / 2.0
                footCenterR = (
                    controlModel.getBodyPositionGlobal(supR) +
                    controlModel.getBodyPositionGlobal(indexFootR[1])) / 2.0

        refFootL = motionModel.getBodyPositionGlobal(supL)
        refFootR = motionModel.getBodyPositionGlobal(supR)

        footCenter = footCenterL + (footCenterR - footCenterL) / 2.0
        footCenter[1] = 0.

        footCenter_ref = refFootL + (refFootR - refFootL) / 2.0
        #footCenter_ref[1] = 0.

        positionFootL = [None] * footPartNum
        positionFootR = [None] * footPartNum
        for i in range(footPartNum):
            positionFootL[i] = controlModel.getBodyPositionGlobal(
                indexFootL[i])
            positionFootR[i] = controlModel.getBodyPositionGlobal(
                indexFootR[i])

        linkPositions = controlModel.getBodyPositionsGlobal()
        linkVelocities = controlModel.getBodyVelocitiesGlobal()
        linkAngVelocities = controlModel.getBodyAngVelocitiesGlobal()
        linkInertias = controlModel.getBodyInertiasGlobal()

        jointPositions = controlModel.getJointPositionsGlobal()
        jointAxeses = controlModel.getDOFAxeses()

        CM = yrp.getCM(linkPositions, linkMasses, totalMass)
        dCM = yrp.getCM(linkVelocities, linkMasses, totalMass)
        CM_plane = copy.copy(CM)
        CM_plane[1] = 0.
        dCM_plane = copy.copy(dCM)
        dCM_plane[1] = 0.

        linkPositions_ref = motionModel.getBodyPositionsGlobal()
        CM_ref = yrp.getCM(linkPositions_ref, linkMasses, totalMass)
        CM_plane_ref = copy.copy(CM_ref)
        CM_plane_ref[1] = 0.

        P = ymt.getPureInertiaMatrix(TO, linkMasses, linkPositions, CM,
                                     linkInertias)
        dP = ymt.getPureInertiaMatrixDerivative(dTO, linkMasses,
                                                linkVelocities, dCM,
                                                linkAngVelocities,
                                                linkInertias)

        yjc.computeJacobian2(Jsys, DOFs, jointPositions, jointAxeses,
                             linkPositions, allLinkJointMasks)
        yjc.computeJacobianDerivative2(dJsys, DOFs, jointPositions,
                                       jointAxeses, linkAngVelocities,
                                       linkPositions, allLinkJointMasks)

        if g_initFlag == 0:
            softConstPoint = controlModel.getBodyPositionGlobal(constBody)
            softConstPoint[1] -= .3
            g_initFlag = 1

        yjc.computeJacobian2(jFootL[0], DOFs, jointPositions, jointAxeses,
                             [positionFootL[0]], jointMasksFootL[0])
        yjc.computeJacobianDerivative2(dJFootL[0], DOFs, jointPositions,
                                       jointAxeses, linkAngVelocities,
                                       [positionFootL[0]], jointMasksFootL[0],
                                       False)

        yjc.computeJacobian2(jFootR[0], DOFs, jointPositions, jointAxeses,
                             [positionFootR[0]], jointMasksFootR[0])
        yjc.computeJacobianDerivative2(dJFootR[0], DOFs, jointPositions,
                                       jointAxeses, linkAngVelocities,
                                       [positionFootR[0]], jointMasksFootR[0],
                                       False)

        yjc.computeAngJacobian2(jAngFootL[0], DOFs, jointPositions,
                                jointAxeses, [positionFootL[0]],
                                jointMasksFootL[0])
        yjc.computeAngJacobianDerivative2(dJAngFootL[0], DOFs, jointPositions,
                                          jointAxeses, linkAngVelocities,
                                          [positionFootL[0]],
                                          jointMasksFootL[0], False)

        yjc.computeAngJacobian2(jAngFootR[0], DOFs, jointPositions,
                                jointAxeses, [positionFootR[0]],
                                jointMasksFootR[0])
        yjc.computeAngJacobianDerivative2(dJAngFootR[0], DOFs, jointPositions,
                                          jointAxeses, linkAngVelocities,
                                          [positionFootR[0]],
                                          jointMasksFootR[0], False)

        bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
            bodyIDsToCheck, mus, Ks, Ds)
        CP = yrp.getCP(contactPositions, contactForces)

        for i in range(len(bodyIDsToCheck)):
            controlModel.SetBodyColor(bodyIDsToCheck[i], 0, 0, 0)

        contactFlagFootL = [0] * footPartNum
        contactFlagFootR = [0] * footPartNum

        for i in range(len(bodyIDs)):
            controlModel.SetBodyColor(bodyIDs[i], 255, 105, 105)
            index = controlModel.id2index(bodyIDs[i])
            for j in range(len(indexFootL)):
                if index == indexFootL[j]:
                    contactFlagFootL[j] = 1
                    if j != 0:
                        yjc.computeJacobian2(jFootL[j], DOFs, jointPositions,
                                             jointAxeses, [positionFootL[j]],
                                             jointMasksFootL[j])
                        yjc.computeJacobianDerivative2(
                            dJFootL[j], DOFs, jointPositions, jointAxeses,
                            linkAngVelocities, [positionFootL[j]],
                            jointMasksFootL[j], False)
                    break
            for j in range(len(indexFootR)):
                if index == indexFootR[j]:
                    contactFlagFootR[j] = 1
                    if j != 0:
                        yjc.computeJacobian2(jFootR[j], DOFs, jointPositions,
                                             jointAxeses, [positionFootR[j]],
                                             jointMasksFootR[j])
                        yjc.computeJacobianDerivative2(
                            dJFootR[j], DOFs, jointPositions, jointAxeses,
                            linkAngVelocities, [positionFootR[j]],
                            jointMasksFootR[j], False)
                    break

        for j in range(len(indexFootL)):
            yjc.computeAngJacobian2(jAngFootL[j], DOFs, jointPositions,
                                    jointAxeses, [positionFootL[j]],
                                    jointMasksFootL[j])
            yjc.computeAngJacobianDerivative2(dJAngFootL[j], DOFs,
                                              jointPositions, jointAxeses,
                                              linkAngVelocities,
                                              [positionFootL[j]],
                                              jointMasksFootL[j], False)
            yjc.computeAngJacobian2(jAngFootR[j], DOFs, jointPositions,
                                    jointAxeses, [positionFootR[j]],
                                    jointMasksFootR[j])
            yjc.computeAngJacobianDerivative2(dJAngFootR[j], DOFs,
                                              jointPositions, jointAxeses,
                                              linkAngVelocities,
                                              [positionFootR[j]],
                                              jointMasksFootR[j], False)

        #
        if checkAll(contactFlagFootL, 0) == 1 and checkAll(
                contactFlagFootR, 0) == 1:
            footCenter = footCenter
        elif checkAll(contactFlagFootL, 0) == 1:
            footCenter = footCenterR
        elif checkAll(contactFlagFootR, 0) == 1:
            footCenter = footCenterL
        footCenter[1] = 0.

        desForeSupLAcc = [0, 0, 0]
        desForeSupRAcc = [0, 0, 0]

        totalNormalForce = [0, 0, 0]

        for i in range(len(contactForces)):
            totalNormalForce[0] += contactForces[i][0]
            totalNormalForce[1] += contactForces[i][1]
            totalNormalForce[2] += contactForces[i][2]

        # linear momentum
        CM_ref_plane = footCenter
        dL_des_plane = Kl * totalMass * (CM_ref_plane -
                                         CM_plane) - Dl * totalMass * dCM_plane

        # angular momentum
        CP_ref = footCenter

        timeStep = 30.
        if CP_old[0] == None or CP == None:
            dCP = None
        else:
            dCP = (CP - CP_old[0]) / (1 / timeStep)
        CP_old[0] = CP

        if CP != None and dCP != None:
            ddCP_des = Kh * (CP_ref - CP) - Dh * (dCP)
            CP_des = CP + dCP * (1 / timeStep) + .5 * ddCP_des * (
                (1 / timeStep)**2)
            dH_des = np.cross(
                (CP_des - CM),
                (dL_des_plane + totalMass * mm.s2v(wcfg.gravity)))
            #dH_des = np.cross((CP_des - CM_plane), (dL_des_plane + totalMass*mm.s2v(wcfg.gravity)))
        else:
            dH_des = None

        # momentum matrix
        RS = np.dot(P, Jsys)
        R, S = np.vsplit(RS, 2)

        rs = np.dot((np.dot(dP, Jsys) + np.dot(P, dJsys)), dth_flat)
        r_bias, s_bias = np.hsplit(rs, 2)

        ##############################
        # soft point constraint

        P_des = softConstPoint
        P_cur = controlModel.getBodyPositionGlobal(constBody)
        dP_des = [0, 0, 0]
        dP_cur = controlModel.getBodyVelocityGlobal(constBody)
        ddP_des1 = Ksc * (P_des - P_cur) - Dsc * (dP_cur - dP_des)

        r = P_des - P_cur
        I = np.vstack(([1, 0, 0], [0, 1, 0], [0, 0, 1]))
        Z = np.hstack((I, mm.getCrossMatrixForm(-r)))

        yjc.computeJacobian2(Jconst, DOFs, jointPositions, jointAxeses,
                             [softConstPoint], constJointMasks)
        JL, JA = np.vsplit(Jconst, 2)
        Q1 = np.dot(Z, Jconst)

        q1 = np.dot(JA, dth_flat)
        q2 = np.dot(mm.getCrossMatrixForm(q1),
                    np.dot(mm.getCrossMatrixForm(q1), r))

        yjc.computeJacobianDerivative2(dJconst, DOFs, jointPositions,
                                       jointAxeses, linkAngVelocities,
                                       [softConstPoint], constJointMasks,
                                       False)
        q_bias1 = np.dot(np.dot(Z, dJconst), dth_flat) + q2

        ##############################

        flagContact = True
        if dH_des == None or np.any(np.isnan(dH_des)) == True:
            flagContact = False
            viewer.doc.showRenderer('rd_grf_des', False)
            viewer.motionViewWnd.update(1, viewer.doc)
        else:
            viewer.doc.showRenderer('rd_grf_des', True)
            viewer.motionViewWnd.update(1, viewer.doc)
        '''
        0 : initial
        1 : contact
        2 : fly
        3 : landing
        '''

        #MOTION = FORWARD_JUMP
        if mit.MOTION == mit.FORWARD_JUMP:
            frame_index = [136, 100]
            #frame_index = [100000, 100000]
        elif mit.MOTION == mit.TAEKWONDO:
            frame_index = [130, 100]
            #frame_index = [100000, 100000]
        else:
            frame_index = [1000000, 1000000]

        #MOTION = TAEKWONDO
        #frame_index = [135, 100]
        '''
        if frame > 300 :
            if stage != DYNAMIC_BALANCING:
                print("#", frame,"-DYNAMIC_BALANCING")
            stage = DYNAMIC_BALANCING
            Kk = Kk*1
            Dk = 2*(Kk**.5)        
        '''
        if frame > frame_index[0]:
            if stage != POWERFUL_BALANCING:
                print("#", frame, "-POWERFUL_BALANCING")
            stage = POWERFUL_BALANCING
            Kk = Kk * 2
            Dk = 2 * (Kk**.5)
        elif frame > frame_index[1]:
            if stage != MOTION_TRACKING:
                print("#", frame, "-MOTION_TRACKING")
            stage = MOTION_TRACKING

        trackingW = w

        if stage == MOTION_TRACKING:
            trackingW = w2
            Bt = Bt * 2

        # optimization

        mot.addTrackingTerms(problem, totalDOF, Bt, trackingW, ddth_des_flat)

        mot.addSoftPointConstraintTerms(problem, totalDOF, Bsc, ddP_des1, Q1,
                                        q_bias1)

        if flagContact == True:
            if stage != MOTION_TRACKING + 10:
                mot.addLinearTerms(problem, totalDOF, Bl, dL_des_plane, R,
                                   r_bias)
                mot.addAngularTerms(problem, totalDOF, Bh, dH_des, S, s_bias)

        a_sup_2 = [None]
        Jsup_2 = [None]
        dJsup_2 = [None]

        ##############################
        # Hard constraint
        if stage != MOTION_TRACKING:
            Kk2 = Kk * 2.0
        else:
            Kk2 = Kk * 1.5

        Dk2 = 2 * (Kk2**.5)
        '''
        desLinearAccL, desPosL = getDesFootLinearAcc(motionModel, controlModel, supL, ModelOffset, CM_ref, CM, Kk2, Dk2) 
        desLinearAccR, desPosR = getDesFootLinearAcc(motionModel, controlModel, supR, ModelOffset, CM_ref, CM, Kk2, Dk2) 

        desAngularAccL = getDesFootAngularAcc(motionModel, controlModel, supL, Kk2, Dk2)
        desAngularAccR = getDesFootAngularAcc(motionModel, controlModel, supR, Kk2, Dk2)
        '''

        if stage != MOTION_TRACKING:
            idx = 0  #LEFT/RIGHT_TOES

            desLinearAccL, desPosL = getDesFootLinearAcc(
                motionModel, controlModel, indexFootL[idx], ModelOffset,
                CM_ref, CM, Kk2, Dk2)
            desLinearAccR, desPosR = getDesFootLinearAcc(
                motionModel, controlModel, indexFootR[idx], ModelOffset,
                CM_ref, CM, Kk2, Dk2)

            desAngularAccL = getDesFootAngularAcc(motionModel, controlModel,
                                                  indexFootL[idx], Kk2, Dk2)
            desAngularAccR = getDesFootAngularAcc(motionModel, controlModel,
                                                  indexFootR[idx], Kk2, Dk2)

            a_sup_2 = np.hstack((np.hstack((desLinearAccL, desAngularAccL)),
                                 np.hstack((desLinearAccR, desAngularAccR))))

            Jsup_2 = np.vstack((jFootL[idx], jFootR[idx]))
            dJsup_2 = np.vstack((dJFootL[idx], dJFootR[idx]))

            rd_DesPosL[0] = desPosL.copy()
            rd_DesPosR[0] = desPosR.copy()
        else:
            if footPartNum != 1:
                idx = 1
            else:
                idx = 0
            desAngularAccL = getDesFootAngularAcc(motionModel, controlModel,
                                                  indexFootL[idx], Kk2, Dk2)
            desAngularAccR = getDesFootAngularAcc(motionModel, controlModel,
                                                  indexFootR[idx], Kk2, Dk2)

            a_sup_2 = np.hstack((desAngularAccL, desAngularAccR))

            Jsup_2 = np.vstack((jAngFootL[idx], jAngFootR[idx]))
            dJsup_2 = np.vstack((dJAngFootL[idx], dJAngFootR[idx]))

        ##############################

        ##############################
        # Additional constraint

        if stage != MOTION_TRACKING:
            Kk2 = Kk * 1.5
            Dk2 = 2 * (Kk2**.5)
            desForePosL = [0, 0, 0]
            desForePosR = [0, 0, 0]
            desRearPosL = [0, 0, 0]
            desRearPosR = [0, 0, 0]

            for i in range(1, footPartNum):
                if contactFlagFootL[i] == 1:
                    desLinearAccL, desForePosL = getDesFootLinearAcc(
                        motionModel, controlModel, indexFootL[i], ModelOffset,
                        CM_ref, CM, Kk2, Dk2)
                    desAngularAccL = getDesFootAngularAcc(
                        motionModel, controlModel, indexFootL[i], Kk2, Dk2)
                    a_sup_2 = np.hstack(
                        (a_sup_2, np.hstack((desLinearAccL, desAngularAccL))))
                    Jsup_2 = np.vstack((Jsup_2, jFootL[i]))
                    dJsup_2 = np.vstack((dJsup_2, dJFootL[i]))
                if contactFlagFootR[i] == 1:
                    desLinearAccR, desForePosR = getDesFootLinearAcc(
                        motionModel, controlModel, indexFootR[i], ModelOffset,
                        CM_ref, CM, Kk2, Dk2)
                    desAngularAccR = getDesFootAngularAcc(
                        motionModel, controlModel, indexFootR[i], Kk2, Dk2)
                    a_sup_2 = np.hstack(
                        (a_sup_2, np.hstack((desLinearAccR, desAngularAccR))))
                    Jsup_2 = np.vstack((Jsup_2, jFootR[i]))
                    dJsup_2 = np.vstack((dJsup_2, dJFootR[i]))

            rd_DesForePosL[0] = desForePosL
            rd_DesForePosR[0] = desForePosR
            rd_DesRearPosL[0] = desRearPosL
            rd_DesRearPosR[0] = desRearPosR
        ##############################

        mot.setConstraint(problem, totalDOF, Jsup_2, dJsup_2, dth_flat,
                          a_sup_2)

        r = problem.solve()
        problem.clear()
        ype.nested(r['x'], ddth_sol)

        rootPos[0] = controlModel.getBodyPositionGlobal(selectedBody)
        localPos = [[0, 0, 0]]

        for i in range(stepsPerFrame):
            # apply penalty force
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(
                bodyIDsToCheck, mus, Ks, Ds)

            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals,
                                      contactForces)

            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0
                    or extraForce[0][2] != 0):
                forceApplyFrame += 1
                #vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                controlModel.applyBodyForceGlobal(selectedBody, extraForce[0])
                applyedExtraForce[0] = extraForce[0]

            if forceApplyFrame * wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0

            controlModel.setDOFAccelerations(ddth_sol)

            controlModel.solveHybridDynamics()
            '''
            extraForce[0] = viewer.GetForce()
            if (extraForce[0][0] != 0 or extraForce[0][1] != 0 or extraForce[0][2] != 0) :
                forceApplyFrame += 1
                vpWorld.applyPenaltyForce(selectedBodyId, localPos, extraForce)
                applyedExtraForce[0] = extraForce[0]
            
            if forceApplyFrame*wcfg.timeStep > 0.1:
                viewer.ResetForce()
                forceApplyFrame = 0            
            '''
            vpWorld.step()

        # rendering
        rd_footCenter[0] = footCenter

        rd_CM[0] = CM.copy()

        rd_CM_plane[0] = CM_plane.copy()

        rd_footCenter_ref[0] = footCenter_ref
        rd_CM_plane_ref[0] = CM_ref.copy()
        rd_CM_ref[0] = CM_ref.copy()
        rd_CM_ref_vec[0] = (CM_ref - footCenter_ref) * 3.
        rd_CM_vec[0] = (CM - footCenter) * 3

        #rd_CM_plane[0][1] = 0.

        if CP != None and dCP != None:
            rd_CP[0] = CP
            rd_CP_des[0] = CP_des

        rd_dL_des_plane[0] = dL_des_plane
        rd_dH_des[0] = dH_des

        rd_grf_des[0] = totalNormalForce - totalMass * mm.s2v(
            wcfg.gravity)  #dL_des_plane - totalMass*mm.s2v(wcfg.gravity)

        rd_exf_des[0] = applyedExtraForce[0]
        rd_root_des[0] = rootPos[0]

        rd_CMP[0] = softConstPoint

        rd_soft_const_vec[0] = controlModel.getBodyPositionGlobal(
            constBody) - softConstPoint

        if (forceApplyFrame == 0):
            applyedExtraForce[0] = [0, 0, 0]

    viewer.setSimulateCallback(simulateCallback)

    viewer.startTimer(1 / 60.)
    viewer.show()

    Fl.run()
Ejemplo n.º 25
0
def test_joint_pos_vel_acc_funcs_and_tracking():
    def getDesiredAngAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt):
        ddth_des = [None]*len(th_r) 
        for i in range(len(th_r)):
            ddth_des[i] = Kt*(mm.logSO3(np.dot(th[i].transpose(), th_r[i]))) + Dt*(dth_r[i] - dth[i]) + ddth_r[i]
        return ddth_des
    def getDesiredAcceleration(p_r, p, v_r, v, a_r, Kt, Dt):
        return Kt*(p_r - p) + Dt*(v_r - v) + a_r
    
#    bvhFilePath = '../samples/chain_1.bvh'
#    bvhFilePath = '../samples/block_tree_rotate.bvh'
    bvhFilePath = '../samples/chain_3_rotate_freely_move.bvh'
#    bvhFilePath = '../samples/chain_3_rotate_freely.bvh'
#    bvhFilePath = '../samples/chain_3_rotate_freely_expt_root.bvh'
#    bvhFilePath = '../samples/chain_3_rotate.bvh'
#    bvhFilePath = '../samples/chain_3_rotate_expt_root.bvh'
#    bvhFilePath = '../samples/chain_6_rotate_expt_root.bvh'
#    bvhFilePath = '../samples/chain_2_rotate_2axes.bvh'
    motion = yf.readBvhFile(bvhFilePath)
    
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = .8
    for i in range(motion[0].skeleton.getElementNum()):
        mcfg.addNode(motion[0].skeleton.getElementName(i))
    
    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = -1.
    wcfg.gravity = (0,0,0)
    stepsPerFrame = 30
    wcfg.timeStep = (1/30.)/stepsPerFrame
    
    vpWorld = cvw.VpWorld(wcfg)
    controlModel = cvm.VpControlModel(vpWorld, motion[0], mcfg)
    vpWorld.initialize()
    controlModel.initializeHybridDynamics(False)
    
#    controlModel.fixBody(0)
    controlModel.rotate(mm.exp(mm.v3(0,1,0)))
    print controlModel
    
    motion_p = []; motion_v = []; motion_a = []
    motion_ap = []; motion_av = []; motion_aa = []
    motion_ap_local = []; motion_av_local = []; motion_aa_local = []

    model_p = []; model_v = []; model_a = []
    model_ap = []; model_av = []; model_aa = []
    model_ap_local = []; model_av_local = []; model_aa_local = []
        
    model_body_p = []; model_body_a = []
    
    prev_model_v = [(0.,0.,0.)]*controlModel.getJointNum()
    prev_model_av = [(0.,0.,0.)]*controlModel.getJointNum()
    prev_model_av_local = [(0.,0.,0.)]*controlModel.getJointNum()

    viewer = ysv.SimpleViewer()
    viewer.record(False)
    viewer.doc.addRenderer('motion', yr.JointMotionRenderer(motion, (0,0,255), yr.LINK_WIREBOX))
    viewer.doc.addObject('motion', motion)
    viewer.doc.addRenderer('model', cvr.VpModelRenderer(controlModel, (255,240,255), yr.POLYGON_LINE))
    
#    viewer.doc.addRenderer('motion_p', yr.PointsRenderer(motion_p, (255,0,0)))
#    viewer.doc.addRenderer('model_p', yr.PointsRenderer(model_p, (0,255,0)))
#
#    viewer.doc.addRenderer('motion_v', yr.VectorsRenderer(motion_v, motion_p, (255,0,0)))
#    viewer.doc.addRenderer('model_v', yr.VectorsRenderer(model_v, model_p, (0,255,0)))

    viewer.doc.addRenderer('motion_a', yr.VectorsRenderer(motion_a, motion_p, (255,0,0)))
    viewer.doc.addRenderer('model_a', yr.VectorsRenderer(model_a, model_p, (0,255,0)))
#    viewer.doc.addRenderer('model_body_a', yr.VectorsRenderer(model_body_a, model_body_p, (255,255,0)))

#    viewer.doc.addRenderer('motion_ap', yr.OrientationsRenderer(motion_ap, motion_p, (255,0,0)))
#    viewer.doc.addRenderer('model_ap', yr.OrientationsRenderer(model_ap, model_p, (0,255,0)))
#    viewer.doc.addRenderer('motion_ap_local', yr.OrientationsRenderer(motion_ap_local, motion_p, (255,100,100)))
#    viewer.doc.addRenderer('model_ap_local', yr.OrientationsRenderer(model_ap_local, model_p, (100,255,100)))

#    viewer.doc.addRenderer('motion_av', yr.VectorsRenderer(motion_av, motion_p, (255,0,0)))
#    viewer.doc.addRenderer('model_av', yr.VectorsRenderer(model_av, model_p, (0,255,0)))
#    viewer.doc.addRenderer('motion_av_local', yr.VectorsRenderer(motion_av_local, motion_p, (255,100,100)))
#    viewer.doc.addRenderer('model_av_local', yr.VectorsRenderer(model_av_local, model_p, (100,255,100)))

#    viewer.doc.addRenderer('motion_aa', yr.VectorsRenderer(motion_aa, motion_p, (255,0,0)))
#    viewer.doc.addRenderer('model_aa', yr.VectorsRenderer(model_aa, model_p, (0,255,0)))
#    viewer.doc.addRenderer('motion_aa_local', yr.VectorsRenderer(motion_aa_local, motion_p, (255,100,100)))
#    viewer.doc.addRenderer('model_aa_local', yr.VectorsRenderer(model_aa_local, model_p, (100,255,100)))
    
    Kt = 200; Dt = 2*(Kt**.5)
    
    def simulateCallback(frame):
        th_r = motion.getJointOrientationsLocal(frame)
        th = controlModel.getJointOrientationsLocal()
        dth_r = motion.getJointAngVelocitiesLocal(frame)
        dth = controlModel.getJointAngVelocitiesLocal()
        ddth_r = motion.getJointAngAccelerationsLocal(frame)
        ddth_des = getDesiredAngAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt)
        
        p_r = motion.getJointPositionGlobal(0, frame)
        p = controlModel.getJointPositionGlobal(0)
        v_r = motion.getJointVelocityGlobal(0, frame)
        v = controlModel.getJointVelocityGlobal(0)
        a_r = motion.getJointAccelerationGlobal(0, frame)
        a_des = getDesiredAcceleration(p_r, p, v_r, v, a_r, Kt, Dt) 
        
        th_r0 = motion.getJointOrientationGlobal(0, frame)
        th0 = controlModel.getJointOrientationGlobal(0)
        dth_r0 = motion.getJointAngVelocityGlobal(0, frame)
        dth0 = controlModel.getJointAngVelocityGlobal(0)
        ddth_r0 = motion.getJointAngAccelerationGlobal(0, frame)
        ddth_des0 = getDesiredAngAccelerations([th_r0], [th0], [dth_r0], [dth0], [ddth_r0], Kt, Dt)[0]
                
        for i in range(stepsPerFrame):
#            controlModel.setBodyAccelerationGlobal(0, a_des)
#            controlModel.setJointAngAccelerationsLocal(ddth_des)

            controlModel.setJointAccelerationGlobal(0, a_des)
            controlModel.setJointAngAccelerationGlobal(0, ddth_des0)
            controlModel.setInternalJointAngAccelerationsLocal(ddth_des[1:])
            
            controlModel.solveHybridDynamics()

            vpWorld.step()
            
        motion_p[:] = motion.getJointPositionsGlobal(frame)
        motion_v[:] = motion.getJointVelocitiesGlobal(frame)
        motion_a[:] = motion.getJointAccelerationsGlobal(frame)
        motion_ap[:] = motion.getJointOrientationsGlobal(frame)
        motion_av[:] = motion.getJointAngVelocitiesGlobal(frame)
        motion_aa[:] = motion.getJointAngAccelerationsGlobal(frame)
        motion_ap_local[:] = motion.getJointOrientationsLocal(frame)
        motion_av_local[:] = motion.getJointAngVelocitiesLocal(frame)
        motion_aa_local[:] = motion.getJointAngAccelerationsLocal(frame)
        
        model_p[:] = controlModel.getJointPositionsGlobal()
        model_v[:] = controlModel.getJointVelocitiesGlobal()
        
#        model_a[:] = controlModel.getJointAccelerationsGlobal()
        model_a[:] = map(lambda v1,v0: (v1-v0)/(1/30.), model_v, prev_model_v)
        prev_model_v[:] = model_v

        model_ap[:] = controlModel.getJointOrientationsGlobal()
        model_av[:] = controlModel.getJointAngVelocitiesGlobal()
        
#        model_aa[:] = controlModel.getJointAngAccelerationsGlobal()
        model_aa[:] = map(lambda v1,v0: (v1-v0)/(1/30.), model_av, prev_model_av)
        prev_model_av[:] = model_av
        
        model_ap_local[:] = controlModel.getJointOrientationsLocal()
        model_av_local[:] = controlModel.getJointAngVelocitiesLocal()
        
#        model_aa_local[:] = controlModel.getJointAngAccelerationsLocal()
        model_aa_local[:] = map(lambda v1,v0: (v1-v0)/(1/30.), model_av_local, prev_model_av_local)
        prev_model_av_local[:] = model_av_local
        
        model_body_p[:] = controlModel.getBodyPositionsGlobal()
        model_body_a[:] = controlModel.getBodyAccelerationsGlobal()
            
    viewer.setSimulateCallback(simulateCallback)
    
    viewer.startTimer(1/30.)
    viewer.show()
    
    Fl.run()
    def simulateCallback(frame):
        # seginfo
        segIndex = seg_index[0]
        curState = seginfo[segIndex]['state']
        curInterval = yma.offsetInterval(acc_offset[0], seginfo[segIndex]['interval'])
        stanceLegs = seginfo[segIndex]['stanceHips']
        swingLegs = seginfo[segIndex]['swingHips']
        stanceFoots = seginfo[segIndex]['stanceFoots']
        swingFoots = seginfo[segIndex]['swingFoots']
        swingKnees = seginfo[segIndex]['swingKnees']
        groundHeight = seginfo[segIndex]['ground_height']
        maxStfPushFrame = seginfo[segIndex]['max_stf_push_frame']
        
        prev_frame = frame-1 if frame>0 else 0
#        prev_frame = frame
        
        # information
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(frame), bodyMasses, upperMass, uppers)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(frame), bodyMasses, upperMass, uppers)
##        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(frame), bodyMasses, totalMass)
##        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(frame), bodyMasses, totalMass)
#        stf_tar = motion_seg.getJointPositionGlobal(stanceFoots[0], frame)
#        CMr_tar = CM_tar - stf_tar

        dCM_tar = motion_seg.getJointVelocityGlobal(0, prev_frame)
        CM_tar = motion_seg.getJointPositionGlobal(0, prev_frame)
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(prev_frame), bodyMasses, upperMass, uppers)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(prev_frame), bodyMasses, upperMass, uppers)
#        dCM_tar = yrp.getCM(motion_seg.getJointVelocitiesGlobal(prev_frame), bodyMasses, totalMass)
#        CM_tar = yrp.getCM(motion_seg.getJointPositionsGlobal(prev_frame), bodyMasses, totalMass)
        stf_tar = motion_seg.getJointPositionGlobal(stanceFoots[0], prev_frame)
        CMr_tar = CM_tar - stf_tar
            
        dCM = avg_dCM[0]
        CM = controlModel.getJointPositionGlobal(0)
#        CM = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, upperMass, uppers)
#        CM = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, totalMass)
        CMreal = yrp.getCM(controlModel.getJointPositionsGlobal(), bodyMasses, totalMass)
        stf = controlModel.getJointPositionGlobal(stanceFoots[0])
        CMr = CM - stf
        
        diff_dCM = mm.projectionOnPlane(dCM-dCM_tar, (1,0,0), (0,0,1))
        diff_dCM_axis = np.cross((0,1,0), diff_dCM)
        rd_vec1[0] = diff_dCM; rd_vecori1[0] = CM_tar
        
        diff_CMr = mm.projectionOnPlane(CMr-CMr_tar, (1,0,0), (0,0,1))
#        rd_vec1[0] = diff_CMr; rd_vecori1[0] = stf_tar
        diff_CMr_axis = np.cross((0,1,0), diff_CMr)
        
        direction = mm.normalize2(mm.projectionOnPlane(dCM_tar, (1,0,0), (0,0,1)))
#        direction = mm.normalize2(mm.projectionOnPlane(dCM, (1,0,0), (0,0,1)))
        directionAxis = np.cross((0,1,0), direction)
        
        diff_dCM_sag, diff_dCM_cor = mm.projectionOnVector2(diff_dCM, direction)
#        rd_vec1[0] = diff_dCM_sag; rd_vecori1[0] = CM_tar
        diff_dCM_sag_axis = np.cross((0,1,0), diff_dCM_sag)
        diff_dCM_cor_axis = np.cross((0,1,0), diff_dCM_cor)
            
        diff_CMr_sag, diff_CMr_cor = mm.projectionOnVector2(diff_CMr, direction)
        diff_CMr_sag_axis = np.cross((0,1,0), diff_CMr_sag)
        diff_CMr_cor_axis = np.cross((0,1,0), diff_CMr_cor)
            
        t = (frame-curInterval[0])/float(curInterval[1]-curInterval[0])
        t_raw = t
        if t>1.: t=1.
        
        
        p_root = motion_stitch[frame].getJointPositionGlobal(0)
        R_root = motion_stitch[frame].getJointOrientationGlobal(0)

        motion_seg_orig.goToFrame(frame)
        motion_seg.goToFrame(frame)
        motion_stitch.goToFrame(frame)
        
        motion_debug1.append(motion_stitch[frame].copy())
        motion_debug1.goToFrame(frame)
        motion_debug2.append(motion_stitch[frame].copy())
        motion_debug2.goToFrame(frame)
        motion_debug3.append(motion_stitch[frame].copy())
        motion_debug3.goToFrame(frame)
        
        # paper implementation
        M_tc.append(motion_stitch[prev_frame])
        M_tc.goToFrame(frame)
        P_hat.append(M_tc[frame].copy())
        P_hat.goToFrame(frame)
        
        p_temp = ym.JointPosture(skeleton)
        p_temp.rootPos = controlModel.getJointPositionGlobal(0)
        p_temp.setJointOrientationsLocal(controlModel.getJointOrientationsLocal())
        P.append(p_temp)
        P.goToFrame(frame)
        
        # stance foot stabilize
        motion_stf_stabilize.append(motion_stitch[frame].copy())
        motion_stf_stabilize.goToFrame(frame)
        if STANCE_FOOT_STABILIZE:
            for stanceFoot in stanceFoots:
                R_target_foot = motion_seg[frame].getJointOrientationGlobal(stanceFoot)
                R_current_foot = motion_stf_stabilize[frame].getJointOrientationGlobal(stanceFoot)
                motion_stf_stabilize[frame].setJointOrientationGlobal(stanceFoot, cm.slerp(R_current_foot, R_target_foot , stf_stabilize_func(t)))
#                R_target_foot = motion_seg[frame].getJointOrientationLocal(stanceFoot)
#                R_current_foot = motion_stf_stabilize[frame].getJointOrientationLocal(stanceFoot)
#                motion_stf_stabilize[frame].setJointOrientationLocal(stanceFoot, cm.slerp(R_current_foot, R_target_foot , stf_stabilize_func(t)))

        # match stance leg 
        motion_match_stl.append(motion_stf_stabilize[frame].copy())
        motion_match_stl.goToFrame(frame)
        if MATCH_STANCE_LEG:
            if curState!=yba.GaitState.STOP:
                for i in range(len(stanceLegs)):
                    stanceLeg = stanceLegs[i]
                    stanceFoot = stanceFoots[i]
                    
#                    # motion stance leg -> character stance leg as time goes
                    R_motion = motion_match_stl[frame].getJointOrientationGlobal(stanceLeg)
                    R_character = controlModel.getJointOrientationGlobal(stanceLeg)
                    motion_match_stl[frame].setJointOrientationGlobal(stanceLeg, cm.slerp(R_motion, R_character, match_stl_func(t)))

#                    t_y = match_stl_func_y(t)
#                    t_xz = match_stl_func(t)
#                    
#                    R_motion = motion_match_stl[frame].getJointOrientationGlobal(stanceLeg)
#                    R_character = controlModel.getJointOrientationGlobal(stanceLeg)
#                    R = np.dot(R_character, R_motion.T)
#                    R_y, R_xz = mm.projectRotation((0,1,0), R)
#                    motion_match_stl[frame].mulJointOrientationGlobal(stanceLeg, mm.scaleSO3(R_xz, t_xz))
#                    motion_match_stl[frame].mulJointOrientationGlobal(stanceLeg, mm.scaleSO3(R_y, t_y))

        # swing foot placement
        motion_swf_placement.append(motion_match_stl[frame].copy())
        motion_swf_placement.goToFrame(frame)
        if SWING_FOOT_PLACEMENT:
            t_swing_foot_placement = swf_placement_func(t);
            
            if extended[0]:
                R_swp_sag = prev_R_swp[0][0]
                R_swp_cor = prev_R_swp[0][1]
            else:
                R_swp_sag = mm.I_SO3(); R_swp_cor = mm.I_SO3()
                R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement))
                R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement))
                if np.dot(direction, diff_CMr_sag) < 0:
                    R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement))
                R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement))

            for i in range(len(swingLegs)):
                swingLeg = swingLegs[i]
                swingFoot = swingFoots[i] 
                
                # save swing foot global orientation
#                R_swf = motion_swf_placement[frame].getJointOrientationGlobal(swingFoot)
                
                # rotate swing leg
                motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_sag)
                motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_cor)
                
                # restore swing foot global orientation
#                motion_swf_placement[frame].setJointOrientationGlobal(swingFoot, R_swf)
                
                prev_R_swp[0] = (R_swp_sag, R_swp_cor)

        # swing foot height
        motion_swf_height.append(motion_swf_placement[frame].copy())
        motion_swf_height.goToFrame(frame)
        if SWING_FOOT_HEIGHT:
            for swingFoot in swingFoots:
                stanceFoot = stanceFoots[0]

                # save foot global orientation
                R_foot = motion_swf_height[frame].getJointOrientationGlobal(swingFoot)
                R_stance_foot = motion_swf_height[frame].getJointOrientationGlobal(stanceFoot)

                height_tar = motion_swf_height[frame].getJointPositionGlobal(swingFoot)[1] - motion_swf_height[frame].getJointPositionGlobal(stanceFoot)[1]
#                motion_debug1[frame] = motion_swf_height[frame].copy()

                # rotate
                motion_swf_height[frame].rotateByTarget(controlModel.getJointOrientationGlobal(0))
#                motion_debug2[frame] = motion_swf_height[frame].copy()
#                motion_debug2[frame].translateByTarget(controlModel.getJointPositionGlobal(0))

                height_cur = motion_swf_height[frame].getJointPositionGlobal(swingFoot)[1] - motion_swf_height[frame].getJointPositionGlobal(stanceFoot)[1]

                offset_height = (height_tar - height_cur) * swf_height_func(t) * c_swf_stability
                offset_sine = c_swf_mid_offset * swf_height_sine_func(t)
                
                offset = 0.
                offset += offset_height
                offset += offset_sine

                if offset > 0.:
                    newPosition =  motion_swf_height[frame].getJointPositionGlobal(swingFoot)
                    newPosition[1] += offset
                    aik.ik_analytic(motion_swf_height[frame], swingFoot, newPosition)
                else:
                    newPosition =  motion_swf_height[frame].getJointPositionGlobal(stanceFoot)
                    newPosition[1] -= offset
                    aik.ik_analytic(motion_swf_height[frame], stanceFoot, newPosition)

                # return
#                motion_debug3[frame] = motion_swf_height[frame].copy()
#                motion_debug3[frame].translateByTarget(controlModel.getJointPositionGlobal(0))
                motion_swf_height[frame].rotateByTarget(R_root)
                
                # restore foot global orientation
                motion_swf_height[frame].setJointOrientationGlobal(swingFoot, R_foot)
                motion_swf_height[frame].setJointOrientationGlobal(stanceFoot, R_stance_foot)

                if plot!=None:
                    plot.addDataPoint('debug1', frame, height_tar)
                    plot.addDataPoint('debug2', frame, height_cur)
#                    plot.addDataPoint('diff', frame, diff)

        # swing foot orientation
        motion_swf_orientation.append(motion_swf_height[frame].copy())
        motion_swf_orientation.goToFrame(frame)
        if SWING_FOOT_ORIENTATION:
#    swf_orientation_func = yfg.concatenate([yfg.zero, yfg.hermite2nd, yfg.one], [.25, .75])
            for swingFoot in swingFoots:
                R_target_foot = motion_seg[curInterval[1]].getJointOrientationGlobal(swingFoot)
                R_current_foot = motion_swf_orientation[frame].getJointOrientationGlobal(swingFoot)
                motion_swf_orientation[frame].setJointOrientationGlobal(swingFoot, cm.slerp(R_current_foot, R_target_foot, swf_orientation_func(t)))
#    swf_stabilize_func = yfg.concatenate([yfg.hermite2nd, yfg.one], [c_taking_duration])
            # push orientation
#            for swingFoot in swingFoots:
#                R_target_foot = motion_seg[frame].getJointOrientationGlobal(swingFoot)
#                R_current_foot = motion_swf_orientation[frame].getJointOrientationGlobal(swingFoot)
#                motion_swf_orientation[frame].setJointOrientationGlobal(swingFoot, cm.slerp(R_current_foot, R_target_foot , swf_stabilize_func(t)))
            
        # stance foot push                
        motion_stf_push.append(motion_swf_orientation[frame].copy())
        motion_stf_push.goToFrame(frame)
        if STANCE_FOOT_PUSH:
            for swingFoot in swingFoots:
#                max_t = (maxStfPushFrame)/float(curInterval[1]-curInterval[0])
#                stf_push_func = yfg.concatenate([yfg.sine, yfg.zero], [max_t*2])
                stf_push_func = yfg.concatenate([yfg.sine, yfg.zero], [c_taking_duration*2])
                
                R_swp_sag = mm.I_SO3()
#                R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_stp_vel * -stf_push_func(t)))
                
#                if step_length_cur[0] < step_length_tar[0]:
#                    ratio = step_length_cur[0] / step_length_tar[0]
#                    R_max = maxmaxStfPushFrame
#                    R_zero = 
                R_swp_sag = np.dot(R_swp_sag, mm.exp((step_length_tar[0] - step_length_cur[0])*step_axis[0] * K_stp_pos * -stf_push_func(t)))
                    
                motion_stf_push[frame].mulJointOrientationGlobal(swingFoot, R_swp_sag)
                
        # stance foot balancing 
        motion_stf_balancing.append(motion_stf_push[frame].copy())
        motion_stf_balancing.goToFrame(frame)
        if STANCE_FOOT_BALANCING:
            R_stb = mm.exp(diff_dCM_axis * K_stb_vel * stf_balancing_func(t))
            for stanceFoot in stanceFoots:
                if frame < 5: continue
                motion_stf_balancing[frame].mulJointOrientationGlobal(stanceFoot, R_stb)
                    
        # control trajectory
        motion_control.append(motion_stf_balancing[frame].copy())
        motion_control.goToFrame(frame)
        
        #=======================================================================
        # tracking with inverse dynamics
        #=======================================================================
        th_r = motion_control.getDOFPositions(frame)
        th = controlModel.getDOFPositions()
        dth_r = motion_control.getDOFVelocities(frame)
        dth = controlModel.getDOFVelocities()
        ddth_r = motion_control.getDOFAccelerations(frame)
        ddth_des = yct.getDesiredDOFAccelerations(th_r, th, dth_r, dth, ddth_r, Kt, Dt)

        #=======================================================================
        # simulation
        #=======================================================================
        CP = mm.v3(0.,0.,0.)
        F = mm.v3(0.,0.,0.)
        avg_dCM[0] = mm.v3(0.,0.,0.)
        
        # external force rendering info
        del rd_forces[:]; del rd_force_points[:]
        for fi in forceInfos:
            if fi.startFrame <= frame and frame < fi.startFrame + fi.duration*(1/frameTime):
                rd_forces.append(fi.force)
                rd_force_points.append(controlModel.getBodyPositionGlobal(fi.targetBody))
                    
        for i in range(stepsPerFrame):
            
            bodyIDs, contactPositions, contactPositionLocals, contactForces = vpWorld.calcPenaltyForce(bodyIDsToCheck, mus, Ks, Ds)
            vpWorld.applyPenaltyForce(bodyIDs, contactPositionLocals, contactForces)
            
            # apply external force
            for fi in forceInfos:
                if fi.startFrame <= frame and frame < fi.startFrame + fi.duration*(1/frameTime):
                    controlModel.applyBodyForceGlobal(fi.targetBody, fi.force)
            
            controlModel.setDOFAccelerations(ddth_des)
            controlModel.solveHybridDynamics()
            
            if TORQUE_PLOT:
                rhip_torques[frame] += mm.length(controlModel.getJointTorqueLocal(rUpLeg))
                rknee_torques[frame] += mm.length(controlModel.getJointTorqueLocal(rKnee))
                rankle_torques[frame] += mm.length(controlModel.getJointTorqueLocal(rFoot))
            
            rd_torques[:] = [controlModel.getJointTorqueLocal(i)/100. for i in range(skeleton.getJointNum())]
            rd_joint_positions[:] = controlModel.getJointPositionsGlobal()
        
            vpWorld.step()
#            yvu.align2D(controlModel)

            if len(contactForces) > 0:
                CP += yrp.getCP(contactPositions, contactForces)
                F += sum(contactForces)
            avg_dCM[0] += controlModel.getJointVelocityGlobal(0)
#            avg_dCM[0] += yrp.getCM(controlModel.getJointVelocitiesGlobal(), bodyMasses, upperMass, uppers)
#            avg_dCM[0] += yrp.getCM(controlModel.getJointVelocitiesGlobal(), bodyMasses, totalMass)

#            if len(stanceFoots)>0:
#                avg_stf_v[0] += controlModel.getJointVelocityGlobal(stanceFoots[0])
#                avg_stf_av[0] += controlModel.getJointAngVelocityGlobal(stanceFoots[0])
        
        CP /= stepsPerFrame
        F /= stepsPerFrame
        avg_dCM[0] /= stepsPerFrame
        
#        if len(stanceFoots)>0:
#            avg_stf_v[0] /= stepsPerFrame
#            avg_stf_av[0] /= stepsPerFrame
#            rd_vec1[0] = avg_stf_av[0]; rd_vec1[0][0] = 0.; rd_vec1[0][2] = 0.
#            rd_vecori1[0]= controlModel.getJointPositionGlobal(stanceFoots[0])

        #=======================================================================
        # segment editing
        #=======================================================================
        lastFrame = False
        
        if SEGMENT_EDITING:
            if curState==yba.GaitState.STOP:
                if frame == len(motion_seg)-1:
                    lastFrame = True
                    
            elif (curState==yba.GaitState.LSWING or curState==yba.GaitState.RSWING) and t>c_min_contact_time:
                swingID = lID if curState==yba.GaitState.LSWING else rID

                contact = False
                if swingID in bodyIDs:
                    minContactVel = 1000.
                    for i in range(len(bodyIDs)):
                        if bodyIDs[i]==swingID:
                            vel = controlModel.getBodyVelocityGlobal(swingID, contactPositionLocals[i])
                            vel[1] = 0
                            contactVel = mm.length(vel)
                            if contactVel < minContactVel: minContactVel = contactVel 
                    if minContactVel < c_min_contact_vel: contact = True
                
                extended[0] = False
                
                if contact:
#                    print frame, 'foot touch'
                    lastFrame = True
                    acc_offset[0] += frame - curInterval[1]
                    
                elif frame == len(motion_seg)-1:
                    print frame, 'extend frame', frame+1
                    
                    preserveJoints = []
#                    preserveJoints = [lFoot, rFoot]
#                    preserveJoints = [lFoot, rFoot, lKnee, rKnee]
#                    preserveJoints = [lFoot, rFoot, lKnee, rKnee, lUpLeg, rUpLeg]
                    stanceKnees = [rKnee] if curState==yba.GaitState.LSWING else [lKnee]   
                    preserveJoints = [stanceFoots[0], stanceKnees[0], stanceLegs[0]]
   
                    diff = 3
                    motion_seg_orig.extend([motion_seg_orig[-1]])
                    motion_seg.extend(ymt.extendByIntegration_root(motion_seg, 1, diff))
                    
                    motion_stitch.extend(ymt.extendByIntegration_constant(motion_stitch, 1, preserveJoints, diff))

#                    # extend for swing foot ground speed matching & swing foot height lower
##                    extendedPostures = ymt.extendByIntegration(motion_stitch, 1, preserveJoints, diff)
##                    extendedPostures = [motion_stitch[-1]] 
##
#                    extendFrameNum = frame - curInterval[1] + 1
#                    k = 1.-extendFrameNum/5.
#                    if k<0.: k=0.
#                    extendedPostures = ymt.extendByIntegrationAttenuation(motion_stitch, 1, preserveJoints, diff, k)
#
##                    if len(swingFoots)>0 and np.inner(dCM_tar, dCM)>0.:
##                        print frame, 'speed matching'
##                        R_swf = motion_stitch[-1].getJointOrientationGlobal(swingFoots[0])
##                        
##                        p_swf = motion_stitch[-1].getJointPositionGlobal(swingFoots[0])
##                        v_swf = motion_stitch.getJointVelocityGlobal(swingFoots[0], frame-diff, frame)
##                        a_swf = motion_stitch.getJointAccelerationGlobal(swingFoots[0], frame-diff, frame)
##                        p_swf += v_swf * (frameTime) + a_swf * (frameTime)*(frameTime)
##                        aik.ik_analytic(extendedPostures[0], swingFoots[0], p_swf)
##                        
##                        extendedPostures[0].setJointOrientationGlobal(swingFoots[0], R_swf)
#
#                    motion_stitch.extend(extendedPostures)
                    
                    extended[0] = True
        else:
            if frame == len(motion_seg)-1: lastFrame = True
                    
        if lastFrame:
            if segIndex < len(segments)-1:
                print '%d (%d): end of %dth seg (%s, %s)'%(frame, frame-curInterval[1],segIndex, yba.GaitState.text[curState], curInterval)
                if plot!=None: plot.addDataPoint('diff', frame, (frame-curInterval[1])*.01)
                
                if len(stanceFoots)>0 and len(swingFoots)>0:
#                    step_cur = controlModel.getJointPositionGlobal(swingFoots[0]) - controlModel.getJointPositionGlobal(stanceFoots[0])
#                    step_tar = motion_seg[curInterval[1]].getJointPositionGlobal(swingFoots[0]) - motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
                    step_cur = controlModel.getJointPositionGlobal(0) - controlModel.getJointPositionGlobal(stanceFoots[0])
                    step_tar = motion_seg[curInterval[1]].getJointPositionGlobal(0) - motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
                    
                    step_cur = mm.projectionOnPlane(step_cur, (1,0,0), (0,0,1))
                    step_tar = mm.projectionOnPlane(step_tar, (1,0,0), (0,0,1))
                    
                    step_cur_sag, step_cur_cor = mm.projectionOnVector2(step_cur, direction)
                    step_tar_sag, step_tar_cor = mm.projectionOnVector2(step_tar, direction)
                    
                    step_length_tar[0] = mm.length(step_tar_sag)
                    if np.inner(step_tar_sag, step_cur_sag) > 0:
                        step_length_cur[0] = mm.length(step_cur_sag)
                    else:
                        step_length_cur[0] = -mm.length(step_cur_sag)
                    
                    step_axis[0] = directionAxis
                    
#                    rd_vec1[0] = step_tar_sag
#                    rd_vecori1[0] = motion_seg[curInterval[1]].getJointPositionGlobal(stanceFoots[0])
#                    rd_vec2[0] = step_cur_sag
#                    rd_vecori2[0] = controlModel.getJointPositionGlobal(stanceFoots[0])

                seg_index[0] += 1
                curSeg = segments[seg_index[0]]
                stl_y_limit_num[0] = 0
                stl_xz_limit_num[0] = 0
                
                del motion_seg_orig[frame+1:]
                motion_seg_orig.extend(ymb.getAttachedNextMotion(curSeg, motion_seg_orig[-1], False, False))
                
                del motion_seg[frame+1:]
                del motion_stitch[frame+1:]
                transitionLength = len(curSeg)-1

#                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, motion_seg[-1], False, False))
#                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, motion_control[-1], transitionLength, stitch_func, True, False))

                d = motion_seg[-1] - curSeg[0]
                d.rootPos[1] = 0.
                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, d, True, False))
                
                if NO_FOOT_SLIDING:
                    if segIndex == len(segments)-2:
                        Rl = motion_control[-1].getJointOrientationLocal(lUpLeg)
                        Rr = motion_control[-1].getJointOrientationLocal(rUpLeg)
                        Rlk = motion_control[-1].getJointOrientationLocal(lKnee)
                        Rrk = motion_control[-1].getJointOrientationLocal(rKnee)
                        Rlf = motion_control[-1].getJointOrientationLocal(lFoot)
                        Rrf = motion_control[-1].getJointOrientationLocal(rFoot)
                        for p in curSeg:
                            p.setJointOrientationLocal(lUpLeg, Rl, False)
                            p.setJointOrientationLocal(rUpLeg, Rr, False)
                            p.setJointOrientationLocal(lKnee, Rlk, False)
                            p.setJointOrientationLocal(rKnee, Rrk, False)
                            p.setJointOrientationLocal(lFoot, Rlf, False)
                            p.setJointOrientationLocal(rFoot, Rrf, False)
                            p.updateGlobalT()                
                d = motion_control[-1] - curSeg[0]
                d.rootPos[1] = 0.
                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, d, transitionLength, stitch_func, True, False))
                
#                motion_seg.extend(ymb.getAttachedNextMotion(curSeg, motion_seg[-1], False, True))
#                motion_stitch.extend(ymb.getStitchedNextMotion(curSeg, motion_control[-1], transitionLength, stitch_func, True, True))
            else:
                motion_seg_orig.append(motion_seg_orig[-1])
                motion_seg.append(motion_seg[-1])
                motion_stitch.append(motion_control[-1])
                
                
        # rendering
        motionModel.update(motion_ori[frame])
#        motionModel.update(motion_seg[frame])
        
        if SAVE_SIMULATION:
            p_temp = ym.JointPosture(skeleton)
            p_temp.initLocalRs()
            p_temp.rootPos = controlModel.getJointPositionGlobal(0)
            p_temp.setJointOrientationsLocal(controlModel.getJointOrientationsLocal())
            motion_simulation.append(p_temp)
            
            if frame == viewer.getMaxFrame():
                saveFilePath = SAVE_DIR+'simulated_'+filename
                yf.writeBvhFile(saveFilePath, motion_simulation)
                print saveFilePath, 'saved'
Ejemplo n.º 27
0
def create_biped():
    # motion
    # motionName = 'wd2_n_kick.bvh'

    if MOTION == STAND:
        # motionName = 'wd2_stand.bvh'
        motionName = 'wd2_stand2.bvh'
        # motionName = 'woddy2_jump0_short.bvh'
    elif MOTION == STAND2:
        motionName = 'ww13_41_V001.bvh'
    elif MOTION == FORWARD_JUMP:
        motionName = 'woddy2_jump0.bvh'
    elif MOTION == TAEKWONDO:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == TAEKWONDO2:
        motionName = './MotionFile/wd2_098_V001.bvh'
    elif MOTION == KICK:
        motionName = 'wd2_n_kick.bvh'
    elif MOTION == WALK:
        motionName = 'wd2_WalkForwardNormal00.bvh'
    elif MOTION == TIPTOE:
        motionName = './MotionFile/cmu/15_07_15_07.bvh'

    # motionName = 'ww13_41_V001.bvh'
    scale = 0.01
    if MOTION == WALK:
        scale = 1.0
    elif MOTION == TIPTOE:
        scale = 0.01

    motion = yf.readBvhFile(motionName, scale)

    yme.removeJoint(motion, HEAD, False)
    yme.removeJoint(motion, RIGHT_SHOULDER, False)
    yme.removeJoint(motion, LEFT_SHOULDER, False)

    yme.removeJoint(motion, RIGHT_TOES, False)
    yme.removeJoint(motion, RIGHT_TOES_END, False)
    yme.removeJoint(motion, LEFT_TOES, False)
    yme.removeJoint(motion, LEFT_TOES_END, False)

    yme.removeJoint(motion, RIGHT_HAND_END, False)
    yme.removeJoint(motion, LEFT_HAND_END, False)

    yme.offsetJointLocal(motion, RIGHT_ARM, (.03, -.05, 0.), False)
    yme.offsetJointLocal(motion, LEFT_ARM, (-.03, -.05, 0.), False)
    yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(1., 0., 0.), .01), False)
    # yme.rotateJointLocal(motion, HIP, mm.exp(mm.v3(0,0,1), -.01), False)

    # addFootSegment
    # Talus
    length1 = .15
    width1 = .03
    mass1 = .4
    # Phalange
    length3 = length1 * 0.75
    width3 = width1
    mass3 = 0.4

    length3_2 = length1 * 0.6
    width3_2 = width1
    mass3_2 = 0.4

    #Calcaneus
    length4 = 0.05
    width4 = width1
    mass4 = 0.4

    width1 = 0.03

    yme.addJoint(motion, LEFT_FOOT, LEFT_TALUS_1, (-0.025, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_TALUS_2, (0.025, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_TALUS_1, (0.025, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_TALUS_2, (-0.025, -0.06, -0.05))

    yme.addJoint(motion, LEFT_TALUS_1, LEFT_PHALANGE_1,
                 (0.0, 0.0, length1 - width1 - width3))
    yme.addJoint(motion, LEFT_TALUS_2, LEFT_PHALANGE_2,
                 (0.0, 0.0, length1 - width1 - width3_2))
    yme.addJoint(motion, RIGHT_TALUS_1, RIGHT_PHALANGE_1,
                 (0.0, 0.0, length1 - width1 - width3))
    yme.addJoint(motion, RIGHT_TALUS_2, RIGHT_PHALANGE_2,
                 (0.0, 0.0, length1 - width1 - width3_2))

    yme.addJoint(motion, LEFT_PHALANGE_1, 'LEFT_PHALANGE_Effector1',
                 (0.0, 0.0, length3 - width3))
    yme.addJoint(motion, LEFT_PHALANGE_2, 'LEFT_PHALANGE_Effector2',
                 (0.0, 0.0, length3_2 - width3_2))
    yme.addJoint(motion, RIGHT_PHALANGE_1, 'RIGHT_PHALANGE_Effector1',
                 (0.0, 0.0, length3 - width3))
    yme.addJoint(motion, RIGHT_PHALANGE_2, 'RIGHT_PHALANGE_Effector2',
                 (0.0, 0.0, length3_2 - width3_2))

    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_1, (-0.025, -0.06, -0.05))
    yme.addJoint(motion, LEFT_FOOT, LEFT_CALCANEUS_2, (0.025, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_1, (0.025, -0.06, -0.05))
    yme.addJoint(motion, RIGHT_FOOT, RIGHT_CALCANEUS_2, (-0.025, -0.06, -0.05))
    yme.addJoint(motion, LEFT_CALCANEUS_1, 'LEFT_CALCANEUS_Effector1',
                 (0.0, 0.0, -length4))
    yme.addJoint(motion, LEFT_CALCANEUS_2, 'LEFT_CALCANEUS_Effector2',
                 (0.0, 0.0, -length4))
    yme.addJoint(motion, RIGHT_CALCANEUS_1, 'RIGHT_CALCANEUS_Effector1',
                 (0.0, 0.0, -length4))
    yme.addJoint(motion, RIGHT_CALCANEUS_2, 'RIGHT_CALCANEUS_Effector2',
                 (0.0, 0.0, -length4))

    yme.rotateJointLocal(motion, RIGHT_FOOT, mm.exp(mm.v3(1.0, 0.0, 0.0), -.5),
                         False)
    yme.rotateJointLocal(motion, RIGHT_TALUS_1, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                       .5), False)
    yme.rotateJointLocal(motion, RIGHT_TALUS_2, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                       .5), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_2,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_1,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, RIGHT_CALCANEUS_2,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)

    #yme.rotateJointLocal(motion, LEFT_PHALANGE_1, mm.exp(mm.v3(0., 1., 0.), 1.57), False)

    yme.rotateJointLocal(motion, LEFT_FOOT, mm.exp(mm.v3(1.0, 0.0, 0.0), -.5),
                         False)
    yme.rotateJointLocal(motion, LEFT_TALUS_1, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                      .5), False)
    yme.rotateJointLocal(motion, LEFT_TALUS_2, mm.exp(mm.v3(1.0, 0.0, 0.0),
                                                      .5), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_2,
                         mm.exp(mm.v3(0.0, 0.0, 1.0), 3.14), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_1,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    yme.rotateJointLocal(motion, LEFT_CALCANEUS_2,
                         mm.exp(mm.v3(1.0, 0.0, 0.0), -.5), False)
    #yme.rotateJointLocal(motion, LEFT_CALCANEUS_1, mm.exp(mm.v3(0.0,-1.0,0.0), 1.57), False)

    yme.updateGlobalT(motion)

    ################
    if MOTION == FORWARD_JUMP:
        motion = motion[515:555]
    elif MOTION == TAEKWONDO:
        ## Taekwondo base-step
        motion = motion[0:31]
        #motion = motion[564:600]
    elif MOTION == TAEKWONDO2:
        ## Taekwondo base-step
        #motion = motion[0:31+40]
        ## Taekwondo turning-kick
        motion = motion[108:-1]
        #motion = motion[108:109]
    elif MOTION == KICK:
        #motion = motion[141:-1]
        #motion = motion[100:-1]
        #motion = motion[58:-1]
        motion = motion[82:-1]
        #motion = motion[0:-1]
    elif MOTION == STAND2:
        motion = motion[1:-1]
    elif MOTION == TIPTOE:
        #motion = motion[183:440]
        #motion = motion[350:410]
        motion = motion[350:550]

    motion[0:0] = [motion[0]] * 40
    motion.extend([motion[-1]] * 2000)

    # world, model
    mcfg = ypc.ModelConfig()
    mcfg.defaultDensity = 1000.
    mcfg.defaultBoneRatio = 1.

    for name in massMap:
        node = mcfg.addNode(name)
        node.mass = massMap[name]

    node = mcfg.getNode(HIP)
    node.length = .2
    node.width = .25

    node = mcfg.getNode(SPINE1)
    node.length = .2
    node.offset = (0, 0, 0.1)

    node = mcfg.getNode(SPINE)
    node.width = .22
    # node.length = .2 ####

    node = mcfg.getNode('RightFoot')
    node.length = .1
    node.width = .1

    node = mcfg.getNode('LeftFoot')
    node.length = .1
    node.width = .1

    #Talus
    #length1 = .12
    #width1 = 0.03
    #mass1 = 0.4

    #Phalange
    #length3 = length1
    #width3  = width1
    #mass3   = 0.4

    #length3_2 = length1*0.8
    #width3_2  = width1
    #mass3_2   = 0.4

    #Calcaneus1
    #length4 = 0.1
    #width4  = width1
    #mass4   = 0.4

    #Foot
    length8 = .1
    width8 = 0.028 * 3
    mass8 = .4 * 1.5

    node = mcfg.getNode(RIGHT_FOOT)
    node.length = length8
    node.width = width8
    node.mass = mass8

    node = mcfg.getNode(RIGHT_TALUS_1)
    node.length = length1 - width1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(RIGHT_TALUS_2)
    node.length = length1 - width1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(RIGHT_PHALANGE_1)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(RIGHT_PHALANGE_2)
    node.length = length3_2
    node.width = width3_2
    node.mass = mass3_2

    node = mcfg.getNode(RIGHT_CALCANEUS_1)
    node.length = length4 - width4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(RIGHT_CALCANEUS_2)
    node.length = length4 - width4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(LEFT_FOOT)
    node.length = length8
    node.width = width8
    node.mass = mass8

    node = mcfg.getNode(LEFT_TALUS_1)
    node.length = length1 - width1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_TALUS_2)
    node.length = length1 - width1
    node.width = width1
    node.mass = mass1

    node = mcfg.getNode(LEFT_PHALANGE_1)
    node.length = length3
    node.width = width3
    node.mass = mass3

    node = mcfg.getNode(LEFT_PHALANGE_2)
    node.length = length3_2
    node.width = width3_2
    node.mass = mass3_2

    node = mcfg.getNode(LEFT_CALCANEUS_1)
    node.length = length4  # - width4
    node.width = width4
    node.mass = mass4

    node = mcfg.getNode(LEFT_CALCANEUS_2)
    node.length = length4  # - width4
    node.width = width4
    node.mass = mass4

    #node.offset = (0.0, -0.025, 0.0)

    node = mcfg.getNode('LeftFoot')

    node = mcfg.getNode(RIGHT_TALUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_TALUS_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(LEFT_TALUS_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_TALUS_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(RIGHT_METATARSAL_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(RIGHT_METATARSAL_2)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_METATARSAL_1)
    node.geom = 'MyFoot3'
    node = mcfg.getNode(LEFT_METATARSAL_2)
    node.geom = 'MyFoot3'

    node = mcfg.getNode(RIGHT_PHALANGE_1)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(RIGHT_PHALANGE_2)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(LEFT_PHALANGE_1)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(LEFT_PHALANGE_2)
    node.geom = 'MyFoot4'

    node = mcfg.getNode(RIGHT_CALCANEUS_1)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(RIGHT_CALCANEUS_2)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(LEFT_CALCANEUS_1)
    node.geom = 'MyFoot4'
    node = mcfg.getNode(LEFT_CALCANEUS_2)
    node.geom = 'MyFoot4'

    wcfg = ypc.WorldConfig()
    wcfg.planeHeight = 0.
    wcfg.useDefaultContactModel = False
    stepsPerFrame = 120
    wcfg.timeStep = (1 / 30.) / (stepsPerFrame)
    #stepsPerFrame = 10
    #wcfg.timeStep = (1/120.)/(stepsPerFrame)
    #wcfg.timeStep = (1/1800.)

    # parameter
    config = {}
    config['Kt'] = 200
    config['Dt'] = 2 * (config['Kt']**.5)  # tracking gain
    config['Kl'] = .10
    config['Dl'] = 2 * (config['Kl']**.5)  # linear balance gain
    config['Kh'] = 0.1
    config['Dh'] = 2 * (config['Kh']**.5)  # angular balance gain
    config['Ks'] = 20000
    config['Ds'] = 2 * (config['Ks']**.5)  # penalty force spring gain
    config['Bt'] = 1.
    config['Bl'] = 1.  #0.5
    config['Bh'] = 1.

    config['weightMap'] = {
        RIGHT_ARM: .2,
        RIGHT_FORE_ARM: .2,
        LEFT_ARM: .2,
        LEFT_FORE_ARM: .2,
        SPINE: .3,
        SPINE1: .2,
        RIGHT_FOOT: .3,
        LEFT_FOOT: .3,
        HIP: .3,
        RIGHT_UP_LEG: .1,
        RIGHT_LEG: .2,
        LEFT_UP_LEG: .1,
        LEFT_LEG: .2,
        LEFT_TALUS_1: .1,
        RIGHT_TALUS_1: .1,
        LEFT_TALUS_2: .1,
        RIGHT_TALUS_2: .1,
        RIGHT_CALCANEUS_1: .2,
        LEFT_CALCANEUS_1: .2,
        RIGHT_CALCANEUS_2: .2,
        LEFT_CALCANEUS_2: .2,
        LEFT_PHALANGE_1: .1,
        LEFT_PHALANGE_2: .1,
        RIGHT_PHALANGE_1: .1,
        RIGHT_PHALANGE_2: .1
    }

    config['weightMap2'] = {
        RIGHT_ARM: .2,
        RIGHT_FORE_ARM: .2,
        LEFT_ARM: .2,
        LEFT_FORE_ARM: .2,
        SPINE: .5,
        SPINE1: .3,
        RIGHT_FOOT: .7,
        LEFT_FOOT: .7,
        HIP: .5,
        RIGHT_UP_LEG: .7,
        RIGHT_LEG: .7,
        LEFT_UP_LEG: .7,
        LEFT_LEG: .7,
        LEFT_TALUS_1: .7,
        RIGHT_TALUS_1: .7,
        LEFT_TALUS_2: .7,
        RIGHT_TALUS_2: .7,
        RIGHT_CALCANEUS_1: .7,
        LEFT_CALCANEUS_1: .7,
        RIGHT_CALCANEUS_2: .7,
        LEFT_CALCANEUS_2: .7,
        LEFT_PHALANGE_1: .4,
        LEFT_PHALANGE_2: .4,
        RIGHT_PHALANGE_1: .4,
        RIGHT_PHALANGE_2: .4
    }
    '''                    
    (1, 'RightUpLeg')
    (2, 'RightLeg')
    (3, 'RightFoot')
    (4, 'Spine')
    (5, 'Spine1')
    (6, 'LeftArm')
    (7, 'LeftForeArm')
    (8, 'RightArm')
    (9, 'RightForeArm')
    (10, 'LeftUpLeg')
    (11, 'LeftLeg')
    (12, 'LeftFoot')
    (13, 'LeftTalus_1')
    (14, 'LeftTalus_2')
    (15, 'RightTalus_1')
    (16, 'RightTalus_2')
    (17, 'LeftPhalange_1')
    (18, 'LeftPhalange_2')
    (19, 'RightPhalange_1')
    (20, 'RightPhalange_2')
    (21, 'LeftCalcaneus_1')
    (22, 'LeftCalcaneus_2')
    (23, 'RightCalcaneus_1')
    (24, 'RightCalcaneus_2')
    '''
    config['trackWMap'] = {
        10, 5, .1, 20, 10, 5, 2, 10, 5, .1, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
        0.01, 0.01, 0.01, 0.01, 0.10, 0.01
    }

    config['supLink'] = LEFT_FOOT
    config['supLink2'] = RIGHT_FOOT
    # config['end'] = HIP
    config['end'] = SPINE1

    config['trunk'] = SPINE
    config['const'] = HIP
    config['root'] = HIP

    config['FootPartNum'] = FOOT_PART_NUM

    config['FootLPart'] = [
        LEFT_FOOT, LEFT_CALCANEUS_1, LEFT_CALCANEUS_2, LEFT_TALUS_1,
        LEFT_TALUS_2, LEFT_PHALANGE_1, LEFT_PHALANGE_2
    ]
    config['FootRPart'] = [
        RIGHT_FOOT, RIGHT_CALCANEUS_1, RIGHT_CALCANEUS_2, RIGHT_TALUS_1,
        RIGHT_TALUS_2, RIGHT_PHALANGE_1, RIGHT_PHALANGE_2
    ]

    return motion, mcfg, wcfg, stepsPerFrame, config