0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

python maya export scene to fbx

Posted at

Z up

import os
import pymel.core as pm
from maya import cmds, OpenMaya, OpenMayaAnim

def ChangeUpAxis():
    cmds.upAxis(ax='z', rv=True)

def getBakeAttrs(objects):
    """
    Get the attributes that are not connected to an animation curve.

    :type objects: list[str]
    :rtype: list[str]
    """
    result = []

    if not objects:
        raise ValueError("No objects specified")

    connections = maya.cmds.listConnections(
        objects,
        plugs=True,
        source=True,
        connections=True,
        destination=False
    ) or []

    for dstObj, srcObj in zip(connections[::2], connections[1::2]):
        nodeType = maya.cmds.nodeType(srcObj)

        if not nodeType.startswith("animCurve"):
            result.append(dstObj)

    return result

def bakeConnected(objects, time, sampleBy=1):
    bakeAttrs = getBakeAttrs(objects)
    if bakeAttrs:
        cmds.bakeResults(
            bakeAttrs,
            time=time,
            shape=True,
            simulation=True,
            sampleBy=sampleBy,
            controlPoints=False,
            minimizeRotation=True,
            bakeOnOverrideLayer=False,
            preserveOutsideKeys=False,
            sparseAnimCurveBake=False,
            disableImplicitControl=True,
            removeBakedAttributeFromLayer=False,
        )
    else:
        print("Cannot find any connection to bake!")

def BakeJoints():
    frameRange = GetFrameRange()
    bakeConnected(GetAllJoints(), frameRange)

def GetAllCamera():
    return pm.ls(type='camera', l=True)

def GetAllJoints():
    joints = cmds.ls(type="joint")
    chraRootList = [joint for joint in joints if ":root" in joint]
    pm.select(chraRootList)
    selected = pm.selected()
    children_joints = cmds.listRelatives(allDescendents=True, type='joint')
    pm.select(children_joints)
    return children_joints

def GetFrameRange():
    start = int(pm.playbackOptions(q=True, min=True))
    end = int(pm.playbackOptions(q=True, max=True))
    return (start, end)

def GetSceneName():
    return os.path.splitext(os.path.basename(cmds.file(q=True, sn=True)))[0]

def ExportFbx(filePath):
    # pm.select(GetAllCamera())
    # pm.select(GetAllJoints(), add=True)
    if not cmds.pluginInfo('fbxmaya', q=True, loaded=True):
        cmds.loadPlugin('fbxmaya')
    # cmds.file(file_path, force=True, options="v=0;", type="FBX export", exportSelected=True)
    cmds.file(file_path, force=True, options="v=0;", type="FBX export")

def DeleteAllCurves():
    cmds.delete(cmds.ls(type='nurbsCurve'))

def rename_joints():
    # Get a list of all joints in the scene
    joints = cmds.ls(type='joint')

    # Rename each joint by adding the suffix '_MoCap_M'
    for joint1 in joints:
        new_name = ""
        if joint1.endswith('_M'):
            new_name = joint1.replace('_M', '_MoCap_M')
        elif joint1.endswith('_R'):
            new_name = joint1.replace('_R', '_MoCap_R')
        elif joint1.endswith('_L'):
            new_name = joint1.replace('_L', '_MoCap_L')
        if new_name != "":
            cmds.rename(joint1, new_name)

def main():
    cameras = GetAllCamera()
    ChangeUpAxis()
    BakeJoints() # Bake joint animation
    sceneName = GetSceneName()

    outputFolder = "D:/FOD2_Project/Exported"
    if not os.path.exists(outputFolder):
        os.makedirs(outputFolder)
    filePath = os.path.join(outputFolder, "Exported.fbx")
    print(filePath)
    ExportFbx(filePath)
    cmds.file(filePath, open=True, force=True)
    DeleteAllCurves()
    #rename_joints()
    ExportFbx(filePath)
    print("EXPORT FINISHED",filePath)

main()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?