maya打开bvh脚本

目录

maya打开脚本编辑器

运行打开bvh脚本

maya导出bvh脚本


maya打开脚本编辑器

打开Maya软件,点击右下角 “脚本编辑器”

运行打开bvh脚本

https://github.com/jhoolmans/mayaImporterBVH/blob/master/bvh_importer.py

import os
import re
from typing import Optionalimport maya.cmds as mcspace_re = re.compile(r"\s+")# This maps the BVH naming convention to Maya
translationDict = {"Xposition": "translateX","Yposition": "translateY","Zposition": "translateZ","Xrotation": "rotateX","Yrotation": "rotateY","Zrotation": "rotateZ"
}class TinyDAG(object):"""Tiny DAG class for storing the hierarchy of the BVH file."""def __init__(self, obj: str, parent: Optional["TinyDAG"] = None):"""Constructor"""self.obj = objself.__parent = parent@propertydef parent(self):"""Returns the parent of the object"""return self.__parentdef __str__(self) -> str:"""String representation of the object"""return str(self.obj)def full_path(self) -> str:"""Returns the full path of the object"""if self.parent is not None:return "%s|%s" % (self.parent.full_path(), str(self))return str(self.obj)class BVHImporterDialog(object):"""BVH Importer DialogThis class is the main dialog for the BVH importer."""def __init__(self, debug=False):self._name = "bvhImportDialog"self._title = "BVH Importer v2.0"if debug:print("Debug is deprecated.")# UI relatedself._textfield = ""self._scale_field = ""self._frame_field = ""self._rotation_order = ""self._reload = ""# Otherself._root_node = None  # Used for targeting# BVH specific stuffself._filename = ""self._channels = []self.setup_ui()def setup_ui(self):"""Builds the UI"""win = self._nameif mc.window(win, ex=True):mc.deleteUI(win)# Non sizeable dialogwin = mc.window(self._name, title=self._title, w=200, rtf=True,sizeable=False)mc.columnLayout(adj=1, rs=5)mc.separator()mc.text("Options")mc.separator()mc.rowColumnLayout(numberOfColumns=2,columnWidth=[(1, 80), (2, 150)],cal=[(1, "right"), (2, "center")],cs=[(1, 5), (2, 5)],rs=[(1, 5), (2, 5)])mc.text("Rig scale")self._scale_field = mc.floatField(minValue=0.01, maxValue=2, value=1)mc.text("Frame offset")self._frame_field = mc.intField(minValue=0)mc.text("Rotation Order")self._rotation_order = mc.optionMenu()mc.menuItem(label='XYZ')mc.menuItem(label='YZX')mc.menuItem(label='ZXY')mc.menuItem(label='XZY')mc.menuItem(label='YXZ')mc.menuItem(label='ZYX')mc.setParent("..")mc.separator()# Targeting UImc.text("Skeleton Targeting")mc.text("(Select the hips)")mc.separator()mc.rowColumnLayout(numberOfColumns=2,columnWidth=[(1, 150), (2, 80)],cs=[(1, 5), (2, 5)],rs=[(1, 5), (2, 5)])self._textfield = mc.textField(editable=False)mc.button("Select/Clear", c=self._on_select_root)mc.setParent("..")mc.separator()mc.button("Import..", c=self._on_select_file)self._reload = mc.button("Reload", enable=False, c=self._read_bvh)# Footermc.text("by Jeroen Hoolmans")mc.window(win, e=True, rtf=True, sizeable=False)mc.showWindow(win)def _on_select_file(self, e):"""Callback for the import button."""file_filter = "All Files (*.*);;Motion Capture (*.bvh)"result = mc.fileDialog2(fileFilter=file_filter, dialogStyle=1, fm=1)if result is None or not len(result):returnself._filename = result[0]mc.button(self._reload, e=True, enable=True)# Action!self._read_bvh()def load_bvh(self, filename):self._filename = filenameself._read_bvh()def _read_bvh(self, *_args):# Safe close is needed for End Site part to keep from setting new# parent.safe_close = False# Once motion is active, animate.motion = False# Clear channels before appendingself._channels = []# Scale the entire rig and animationrig_scale = mc.floatField(self._scale_field, q=True, value=True)frame = mc.intField(self._frame_field, q=True, value=True)rot_order = mc.optionMenu(self._rotation_order, q=True, select=True) - 1with open(self._filename) as f:# Check to see if the file is valid (sort of)if not f.readline().startswith("HIERARCHY"):mc.error("No valid .bvh file selected.")return Falseif self._root_node is None:# Create a group for the rig, easier to scale.# (Freeze transform when ungrouping please..)mocap_name = os.path.basename(self._filename)grp = mc.group(em=True, name="_mocap_%s_grp" % mocap_name)mc.setAttr("%s.scale" % grp, rig_scale, rig_scale, rig_scale)# The group is now the 'root'my_parent = TinyDAG(grp, None)else:my_parent = TinyDAG(self._root_node, None)self._clear_animation()for line in f:line = line.replace("	", " ")  # force spacesif not motion:# root jointif line.startswith("ROOT"):# Set the Hip joint as rootif self._root_node:my_parent = TinyDAG(str(self._root_node), None)else:my_parent = TinyDAG(line[5:].rstrip(), my_parent)# Update root node in case we want to reload.self._root_node = my_parentmc.textField(self._textfield,e=True,text=my_parent.full_path())if "JOINT" in line:jnt = space_re.split(line.strip())# Create the jointmy_parent = TinyDAG(jnt[1], my_parent)if "End Site" in line:# Finish up a hierarchy and ignore a closing bracketsafe_close = Trueif "}" in line:# Ignore when safeClose is onif safe_close:safe_close = Falsecontinue# Go up one levelif my_parent is not None:my_parent = my_parent.parentif my_parent is not None:mc.select(my_parent.full_path())if "CHANNELS" in line:chan = line.strip()chan = space_re.split(chan)# Append the channels that are animatedfor i in range(int(chan[1])):self._channels.append("%s.%s" % (my_parent.full_path(),translationDict[chan[2 + i]]))if "OFFSET" in line:offset = line.strip()offset = space_re.split(offset)jnt_name = str(my_parent)# When End Site is reached, name it "_tip"if safe_close:jnt_name += "_tip"# skip if existsif mc.objExists(my_parent.full_path()):jnt = my_parent.full_path()else:# Build a new jointjnt = mc.joint(name=jnt_name, p=(0, 0, 0))mc.setAttr(jnt + ".rotateOrder", rot_order)mc.setAttr(jnt + ".translate",float(offset[1]),float(offset[2]),float(offset[3]))if "MOTION" in line:# Animate!motion = Trueelse:# We don't really need to use Frame count and time# (since Python handles file reads nicely)if "Frame" not in line:data = space_re.split(line.strip())# Set the values to channelsfor index, value in enumerate(data):mc.setKeyframe(self._channels[index],time=frame,value=float(value))frame = frame + 1def _clear_animation(self):if self._root_node is None:mc.error("Could not find root node to clear animation.")return# Select hierarchymc.select(str(self._root_node), hi=True)nodes = mc.ls(sl=True)trans_attrs = ["translateX", "translateY", "translateZ"]rot_attrs = ["rotateX", "rotateY", "rotateZ"]for node in nodes:for attr in trans_attrs + rot_attrs:# Delete input connectionsconnections = mc.listConnections("%s.%s" % (node, attr),s=True,d=False)if connections is not None:mc.delete(connections)for attr in rot_attrs:# Reset rotationmc.setAttr("%s.%s" % (node, attr), 0)def _on_select_root(self, *_args):# When targeting, set the root joint (Hips)selection = mc.ls(sl=True, type="joint", l=True)if len(selection) == 0:self._root_node = Nonemc.textField(self._textfield, e=True, text="")else:self._root_node = selection[0]mc.textField(self._textfield, e=True, text=self._root_node)if __name__ == "__main__":dialog = BVHImporterDialog()

maya导出bvh脚本

https://github.com/zhaozigu/maya-export-bvh/blob/main/export_bvh.py

import os
import mathimport maya.cmds as cmds
import maya.api.OpenMaya as omdef get_bone_rotation(bone):cur_mat = om.MMatrix(cmds.xform(bone, q=True, ws=True, m=True))parent = cmds.listRelatives(bone, p=True)[0]parent_mat = om.MMatrix(cmds.xform(parent, q=True, ws=True, m=True))local_mat = cur_mat * parent_mat.inverse()cur_xfo_mat = om.MTransformationMatrix(local_mat)rotation = [math.degrees(x) for x in cur_xfo_mat.rotation().asVector()]return rotationdef export_motion(joints, start_frame, end_frame, rot_order: tuple):motion_str = ""root_joint = joints[0]for frame in range(start_frame, end_frame + 1):cmds.currentTime(frame)for joint in joints:joint_name = cmds.ls(joint, long=True)[0]rot = get_bone_rotation(joint_name)if joint == root_joint:loc = cmds.xform(joint_name, q=True, translation=True)motion_str += "%.6f %.6f %.6f " % (loc[0], loc[1], loc[2])motion_str += "%.6f %.6f %.6f " % (rot[rot_order[0]], rot[rot_order[1]], rot[rot_order[2]])motion_str += "\n"return motion_strdef export_hierarchy(joints, rot_order: str):hierarchy_str = "HIERARCHY\n"def _process_joint(joint, indent):nonlocal hierarchy_strjoint_name_raw = cmds.ls(joint, long=True)[0]joint_name = joint_name_raw.split("|")[-1].split(":")[-1]if indent == 0:hierarchy_str += "{}ROOT {}\n".format('\t' * indent, joint_name)else:hierarchy_str += "{}JOINT {}\n".format('\t' * indent, joint_name)loc = cmds.xform(joint_name_raw, q=True, translation=True)hierarchy_str += "{}{{\n".format('\t' * indent)hierarchy_str += "{}OFFSET {:.6f} {:.6f} {:.6f}\n".format('\t' * (indent + 1), loc[0], loc[1], loc[2])if indent == 0:hierarchy_str += "{}CHANNELS 6 Xposition Yposition Zposition {}rotation {}rotation {}rotation\n".format('\t' * (indent + 1), rot_order[0], rot_order[1], rot_order[2])else:hierarchy_str += "{}CHANNELS 3 {}rotation {}rotation {}rotation\n".format('\t' * (indent + 1), rot_order[0], rot_order[1], rot_order[2])children = cmds.listRelatives(joint, children=True, type="joint")if children:for child in children:_process_joint(child, indent + 1)else:hierarchy_str += "{}End Site\n".format('\t' * (indent + 1))hierarchy_str += "{}{{\n".format('\t' * (indent + 1))hierarchy_str += "{}OFFSET 0.0 0.0 0.0\n".format('\t' * (indent + 2))hierarchy_str += "{}}}\n".format('\t' * (indent + 1))hierarchy_str += "{}}}\n".format('\t' * indent)root_joint = joints[0]_process_joint(root_joint, 0)return hierarchy_strdef export_bvh(joints, output_file_path, start_frame, end_frame, rot_order="ZXY"):_order = {"XYZ": (0, 1, 2),"XZY": (0, 2, 1),"YXZ": (1, 0, 2),"YZX": (1, 2, 0),"ZXY": (2, 0, 1),"ZYX": (2, 1, 0),}assert rot_order in _order, "The parameters of the rotation order are incorrect"hierarchy = export_hierarchy(joints, rot_order)motion = export_motion(joints, start_frame, end_frame, _order[rot_order])num_frames = end_frame - start_frame + 1frame_rate = cmds.playbackOptions(query=True, framesPerSecond=True)if frame_rate == 0:frame_rate = 24.0frame_time = 1.0 / frame_ratewith open(output_file_path, "w") as output_file:output_file.write(hierarchy)output_file.write(f"MOTION\nFrames: {num_frames}\nFrame Time: {frame_time:.6f}\n")output_file.write(motion)def get_ordered_joints(joint):ordered_joints = [joint]children = cmds.listRelatives(joint, children=True, type="joint")if children:for child in children:ordered_joints.extend(get_ordered_joints(child))return ordered_jointsif __name__ == "__main__":root_joint_name = "root"root_joint = Nonechildren = cmds.listRelatives(root_joint_name, children=True, type="joint")if children:root_joint = children[0]else:raise ValueError(f"No joint found under {root_joint_name}")joints = get_ordered_joints(root_joint)print(joints)start_frame = int(cmds.playbackOptions(query=True, minTime=True))end_frame = int(cmds.playbackOptions(query=True, maxTime=True))# Set the output file pathoutput_file_path = os.path.join(os.path.expanduser("~"), "maya_body_test.bvh")export_bvh(joints, output_file_path, start_frame, end_frame, "ZYX")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/767089.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

训练不了AI,怎么办?

即使直接训练人工智能(AI)模型对许多人来说可能是一个技术上和资源上的挑战,仍然有多种方式可以参与、利用和推动AI技术的发展,而不必直接参与到模型的训练过程中。以下是一些可以考虑的途径: 1. 使用现有的AI服务和工…

excel处理_多个excel文件合并

data文件夹内,有多个xls文件。每个xls文件格式一致, 表头占两行,表位汇总数据占一行。 表头两行,拼接前第二行设置为表头,且删除第二行。 在python读入的dataframe中,成本表是表头,第一行是线路…

40 openlayers setCenter 之后 绘制了Overlay 地图定位异常

前言 这是之前在 生产环境碰到的一个问题 这个其实就是 业务上一个地图点击点位展示详情, 然后再点击另外一个点位 展示详情, 切换中心店的这个过程 其主要的问题是 使用 openlayers 的 Map.View.setCenter() 了之后, 整个地图的中心点切换到了一个莫名其妙的地方 然后 经…

MySQL多表联查会重复查找记录

在做尚上优选项目时,根据商品id查询商品参加的活动信息。需要根据skuid(商品id)对商品信息表、活动表、活动规则表进行多表联查。 但是发现,查询出来的数据会重复,如下图所示: 后把sql语句放在navicat中进…

web集群-lvs-DR模式基本配置

目录 环境: 一、配置RS 1、安装常见软件 2、配置web服务 3、添加vip 4、arp抑制 二、配置LVS 1、添加vip 2、安装配置工具 3、配置DR 三、测试 四、脚本方式配置 1、LVS-DR 2、LVS-RS 环境: master lvs 192.168.80.161 no…

opencv函数使用查找

opencv官方文档地址:https://docs.opencv.org/4.x/index.html 先选对应的版本opencv-python 以这个函数为例子 model cv2.face.LBPHFaceRecognizer.create() 点开后找face类的LBP里面就有create函数的用法

什么是智能物联网关?有哪些作用?

随着物联网技术的不断发展和普及,智能物联网关已经成为连接物理世界与数字世界的桥梁,成为实现万物互联的重要枢纽。那么,什么是智能物联网关?它又有哪些价值呢?今天,就让我们一起走进HiWoo Box的世界&…

5、双亲委派机制

双亲委派机制指的是:当一个类加载器接收到加载类的任务时,会自底向上查找是否加载过, 再由顶向下进行加载。 详细流程: 每个类加载器都有一个父类加载器。父类加载器的关系如下,启动类加载器没有父类加载器&#xff1…

Python将字符串转换为datetime

有这样一些字符串: 1710903685 20240320110125 2024-03-20 11:01:25 要转换成Python的datetime 代码如下: import functools import re from datetime import datetime, timedelta from typing import Union# pip install python-dateutil from date…

鸿蒙一次开发,多端部署(十五)常见问题

如何查询设备类型 设备类型分为default(默认设备)、tablet、tv、wearable、2in1等,有多种查询设备类型的方式。 通过命令行的方式查询设备类型。 通过命令行查询指定系统参数(const.product.devicetype)进而确定设备…

Linux(Centos)安装mysql 8 并且使用systemctl管理服务

1.下载mysql包 地址 MySQL :: Download MySQL Community Server (Archived Versions) 注:下载我圈住的减压之后里面会有tar.gz 再次减压才会是软件主体 2.安装和准备 yum -y install numactl 安装numactl tar -xvf mysql-8.0.30-el7-x86_64.tar 拆分 …

逆向爬虫技术的进阶应用与实战技巧

前言 在互联网的海洋中,数据是无价的财富。爬虫技术作为获取这些数据的重要手段,一直备受关注。然而,随着网站反爬虫机制的日益完善,简单的爬虫程序已经很难满足我们的需求。因此,掌握爬虫逆向技术,突破反爬…

【计算机网络篇】数据链路层(3)差错检测

文章目录 🥚误码🍔两种常见的检错技术⭐奇偶校验⭐循环冗余校验🎈例子 🥚误码 误码首先介绍误码的相关概念 🍔两种常见的检错技术 ⭐奇偶校验 奇校验是在待发送的数据后面添加1个校验位,使得添加该校验…

NVIDIA最新 Blackwell架构简介

NVIDIA Blackwell架构简介 在AI和大型语言模型(LLMs)迅速发展的领域中,追求实时性能和可扩展性至关重要。从医疗保健到汽车行业,组织正深入探索生成性AI和加速计算解决方案的领域。对生成性AI解决方案的需求激增,促使企…

【前端寻宝之路】学习和使用表单标签和表单控件

🌈个人主页: Aileen_0v0 🔥热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法|MySQL| ​💫个人格言:“没有罗马,那就自己创造罗马~” #mermaid-svg-cR8zvB8CkpxTk485 {font-family:"trebuchet ms",verdana,arial,sans-serif;f…

Linux——生产者消费者模型

为何要使用生产者消费者模型 生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,…

MUNIK第二届功能安全及自动驾驶研讨会将在沪召开

2024年4月26日,由上海秒尼科技术服务有限公司(以下简称“Munik”)联合Parosoft主办的“第二届功能安全及自动驾驶研讨会”将在上海虹桥隆重开幕。 据了解,本次功能与自动驾驶安全研讨会,将聚焦在ISO 26262标准体系下,自动驾驶新形势下各个零部件供应商如何满足功能安全等相关重…

论文解读:Relational Embedding for Few-Shot Classification

文章汇总 问题 最近的方法通过元学习一个深度嵌入函数来解决小样本问题,使得嵌入空间上图像之间的距离符合它们的语义距离。然而,学习到的嵌入函数经常会过度拟合到不相关的特征[4,9,14],从而无法迁移到训练中尚未观察到的新类。 动机 与…

web自动化--元素定位之xpath和css

元素定位 xpath绝对路径相对路径案例xpath策略(路径)案例xpath策略(层级、扩展)属性层级与属性层级与属性拓展层级与属性综合 csscss选择器(id、类、标签、属性)id选择器类选择器标签选择器属性选择器案例-…

重看Spring聚焦BeanFactory分析

目录 一、理解BeanFactory (一)功能性理解 (二)BeanFactory和它的子接口 (三)BeanFactory的实现类 二、BeanFactory根接口 (一)源码展示和理解 (二)基…