Working with Qt maya2011

本文详细介绍了如何利用Qt Designer为Maya制作UI界面。从下载Qt框架、安装Designer,到创建窗口、布局控件、绑定事件,直至最终实现与Maya脚本的交互,提供了一个从零到一的完整流程。通过步骤演示,读者能够掌握如何将设计师制作的UI文件(.ui)转换为Maya可识别的UI,并通过mel和python脚本来控制UI的动态行为。
maya2011使用了Qt框架,10年来几乎一成不变的maya界面,现今变成了黑糊糊的界面,虽然只是随便的玩弄了一下,感觉比以前的界面好多了。
Ok,感叹到此为止,进入我们今天的话题"Working with Qt",主要介绍如何使用Qt的Designer来给maya制作UI,有了Designer不管你是程序员还是非程序员,都能轻松给maya制作UI。
先给出Qt的下载地址,Maya 2011 使用的是 Qt 4.5,版本4.5.X的X是无关紧要的,如果你只是用来制作UI我认为版本应该不重要,但如果你是想要写基于Qt的maya插件,那版本就十分重要了。

Win
[url]ftp://ftp.qt.nokia.com/qt/source/qt-win-opensource-4.5.3-mingw.exe[/url]

Linux 请参考[url]http://download.autodesk.com/us/maya/2011help/files/Setting_up_your_build_environment_Linux_environments_32bit_and_64bit.htm[/url]

Mac
[url]ftp://ftp.qt.nokia.com/qt/source/qt-mac-cocoa-opensource-4.5.3.dmg[/url]

安装好Qt后就可以使用Designer了,在开始制作UI前我简单的给你们说一下maya是如何读取.ui文件的。虽然maya2011使用了Qt框架,但据我所知maya不是像Qt那样的读取.ui文件,而是通过loadUI命令来读取的,再通过MQtUtil类来进行(已识别的)maya的脚本和Qt的插件(widgets)的连接来完成的,简单的说就是通过loadUI命令读取.ui文件,将读取的内容给MQtUtil进行过滤,如果能识别就会转化成对应mel命令来实现UI。所以虽然你使用Designer制作的UI,实际用起来还是基于mel的UI。可见maya还是在力挺mel啊,都撑了10年了。
打开Designer,我们要开始制作UI了,选择"Dialog without Buttons",点击"Create"

[img]http://dl.iteye.com/upload/attachment/237430/8ca111df-b13a-3e05-a4ee-078e254c8fcc.png[/img]

给窗口一个独一无二的名称,如"QtDialog",就像你在用mel写UI时一样给窗口一个独一无二的名称是一个很安全的做法,这样你以后就能用mel后python来对其进行访问了,如果你像更改窗口的标题可以在"windowTitle"那里更改

[img]http://dl.iteye.com/upload/attachment/237432/ab309d13-b766-39c0-ba44-042d2c86fdd4.png[/img]

加入我们需要的控件两个"Label",一个"Combo Box"和一个"Line Edit",在Widget Box中找到后直接拖到窗口中就行

[img]http://dl.iteye.com/upload/attachment/237437/f680b080-6bb9-3b04-94bf-b913a216f062.png[/img][img]http://dl.iteye.com/upload/attachment/237440/14c203d3-b39b-35cc-a11f-b34acb60c1f9.png[/img]

双击"Label"就可以编辑它们的显示内容,因为我们不需要对其进行访问,所以不需要给它们一个独一无二的名称,你也可以编辑它们的字体等属性,但"Combo Box"和"Line Edit"就需要了,如图Object列是它们在maya里的名称,Class是控件的类型,我把"Combo Box"命名为"objTypeOM","OM"是optionMenu的缩写,这样命名是因为"Combo Box"就是optionMenu,可以推论"Line Edit"就是textField,所以我命名为"objNameTF"

[img]http://dl.iteye.com/upload/attachment/237442/2eeaf617-89d9-334d-b6b1-cdb161998156.png[/img]

右键"Combo Box"来编辑它的项目

[img]http://dl.iteye.com/upload/attachment/237446/8c18a779-c3da-3404-9db7-423114085bc2.png[/img]

并加入"Sphere","Cube","Cylinder","Cone","Plane"

[img]http://dl.iteye.com/upload/attachment/238027/b731caff-66fd-3f6b-9eec-15b9018febb6.png[/img]

现在我们来添加两个按钮,也许你会问为什么不在一开始就选择一个有按钮的UI来创建呢,原因很简单,Qt里默认的带按钮的窗口都是使用QDialogButtonBox插件(widgets),这是maya不能识别的,因为mel没有按钮组,只有按钮(button)命令,所以我们只能使用PushButton,双击就能更改显示名称

[img]http://dl.iteye.com/upload/attachment/238040/a06ab2a8-03a2-3104-b541-11957a4c38d2.png[/img]

到这里我们的UI就完成了,接下来就是对相应的控件进行命令绑定,当objTypeOM(Combo Box)的项目发生变化时,我希望objNameTF(Line Edit)里的内容是objTypeOM所选的项目的名称,mel_changeType()就是用来完成这些的命令
global proc mel_changeType()
{
string $objType = `optionMenu -q -v objTypeOM`;
textField -e -tx $objType objNameTF;
}

而当objNameTF里的内容是objTypeOM中的项目名称时,按下回车后objTypeOM会把该项目设置为当前所选的项目,我们需要mel_changeName()
global proc mel_changeName()
{
string $objTypes[] = {"Sphere","Cube","Cylinder","Cone","Plane"};
string $text = `textField -q -tx objNameTF`;
for($i in $objTypes)
{
if ($text == $i)
optionMenu -e -v $i objTypeOM;
}
}

最后是Ok按钮的命令,在按下Ok按钮时我希望能根据objTypeOM所选的项目来创建相应的物体,物体的名称则是objNameTF里的内容,这就需要mel_btnCmd()
global proc mel_btnCmd()
{
string $objType = `optionMenu -q -v objTypeOM`;
string $objName = `textField -q -tx objNameTF`;
switch($objType)
{
case "Sphere":
polySphere -n $objName;
break;
case "Cube":
polyCube -n $objName;
break;
case "Cylinder":
polyCylinder -n $objName;
break;
case "Cone":
polyCone -n $objName;
break;
case "Plane":
polyPlane -n $objName;
break;
}
}

现在我们把这些方法和对应的控件进行绑定,选择objTypeOM在Property Editor里点击加号图标并选择"String"来添加动态属性

[img]http://dl.iteye.com/upload/attachment/238055/a9e4ce67-c36b-343d-b39d-3223ee523228.png[/img]

因为"Combo Box"就是optionMenu,所以我们只要加入optionMenu命令的标签maya就能识别,需要注意的是在标签前面是"-"的代表使用mel,是"+"的代表使用python,我为什么给上面的方法都加一个"mel"前缀,就是为了区分mel和python。我们需要的是"changeCommand"标签,所以我们要输入"-changeCommand"

[img]http://dl.iteye.com/upload/attachment/238061/e3a1df83-b411-376b-8731-0310fd9abcc5.png[/img]

然后在"-changeCommand"属性中加入"mel_changeType()"(包括双引号),来完成绑定

[img]http://dl.iteye.com/upload/attachment/238070/21e03fe3-5e4d-33f9-b696-e17b43c471fd.png[/img]

同样我们也给objNameTF添加"-changeCommand"属性,并将它和"mel_changeName()"绑定;而Ok按钮就添加"-command"属性并将它和"mel_btnCmd()"绑定;最后是Close按钮,也给它添加"-command"属性,并输入"deleteUI QtDialog",这样在点击Close时就会关闭窗口。
把UI保存为createDialog.ui(可以是其它名称),我们可以转到maya来了,因为我的本本无法使用maya2011,所以就无法截图了。在脚本编辑器(mel面板)中执行下面的脚本
// 请根据你的createDialog.ui文件路径进行修改
// 如果使用的是win系统,请使用\\来代替\
string $dialog = `loadUI -uiFile "/home/schi/createDialog.ui"`;
showWindow $dialog;

// objTypeOM command
global proc mel_changeType()
{
string $objType = `optionMenu -q -v objTypeOM`;
textField -e -tx $objType objNameTF;
}

// objNameTF command
global proc mel_changeName()
{
string $objTypes[] = {"Sphere","Cube","Cylinder","Cone","Plane"};
string $text = `textField -q -tx objNameTF`;
for($i in $objTypes)
{
if ($text == $i)
optionMenu -e -v $i objTypeOM;
}
}

// Ok button command
global proc mel_btnCmd()
{
string $objType = `optionMenu -q -v objTypeOM`;
string $objName = `textField -q -tx objNameTF`;
switch($objType)
{
case "Sphere":
polySphere -n $objName;
break;
case "Cube":
polyCube -n $objName;
break;
case "Cylinder":
polyCylinder -n $objName;
break;
case "Cone":
polyCone -n $objName;
break;
case "Plane":
polyPlane -n $objName;
break;
}
}

[img]http://dl.iteye.com/upload/attachment/238096/ece4832b-b2af-37ab-801b-f1cfd02b0a86.png[/img]

这个窗口就会出现在你的面前,当然是黑色的UI,你可以选择不同的物体类型来查看效果,或是在物体名称栏中输入"Sphere","Cube","Cylinder","Cone","Plane"(不包括双引号),最后点击按钮,你都会看到相应的动作。

你还可以将这个窗口和maya的主窗口进行整合,这样可以使你的窗口像Attribute Editor和Channel Box一样可以随便移动到maya的主窗口的任何位置,你只需要使用这一行命令
dockControl -content $dialog;

要使用python命令,就是把控件的属性添加成"+"的就行,其它都是一样的,需要注意的是你不能给控件同时添加"-"和"+"的属性,因为这样做并不能同时使用mel和python反而会造成无法识别方法而发生错误。

最后附上python的方法并附上.ui文件
# 请根据你的createDialog.ui文件路径进行修改
# 如果使用的是win系统,请使用\\来代替\
dialog = cmds.loadUI(uiFile='C:\\mack\\qt\\createDialog_py.ui')
cmds.showWindow(dialog)

# 如需要整合到maya主界面,可以使用该行
cmds.dockControl( area='left', content=dialog )

# objTypeOM command
def py_changeType():
objType = cmds.optionMenu('objTypeOM_py',q=1,v=1)
cmds.textField('objNameTF_py',e=1,tx=objType)

# objNameTF command
def py_changeName():
objTypes = ("Sphere","Cube","Cylinder","Cone","Plane")
name = cmds.textField('objNameTF_py',q=1,tx=1)
[cmds.optionMenu('objTypeOM_py',e=1,v=i) for i in objTypes if name == i]

# Ok button command
def py_btnCmd():
objType = cmds.optionMenu('objTypeOM_py',q=1,v=1)
name = cmds.textField('objNameTF_py',q=1,tx=1)

if objType == "Sphere": cmds.polySphere(n=name)
elif objType == "Cube": cmds.polyCubee(n=name)
elif objType == "Cylinder": cmds.polyCylinder(n=name)
elif objType == "Cone": cmds.polyCone(n=name)
elif objType == "Plane": cmds.polyPlane(n=name)
ldtcommon代码: """ .. module:: ldtcommon :synopsis: Constants and templates non dcc specific used in other packages. .. moduleauthor:: Ezequiel Mastrasso """ import lucidity import logging import os logger = logging.getLogger(__name__) LOOKDEVTOOLS_FOLDER = os.environ['LOOKDEVTOOLS'] #: Attributes for tagging meshes for surfacing and texture-to-mesh matching ATTR_SURFACING_PROJECT = "surfacing_project" ATTR_SURFACING_OBJECT = "surfacing_object" #: Attribute for tagging Materials. Values: name of assigned project or object ATTR_MATERIAL = "surfacing_material" #: Attribute for tagging material assignmnents. Values: 'project' or 'object'] ATTR_MATERIAL_ASSIGN = "surfacing_assign" #: Attribute for tagging viewport material. Values: 'color' or 'pattern'] ATTR_MATERIAL_VP = "surfacing_vp" #: Global string matching ratios to compare strings against lucidity parsed files. #: Notice that the ratio constant should be high enough, TEXTURE_MATCHING_RATIO = 90 TEXTURE_CHANNEL_MATCHING_RATIO = 90 #: Texture file template, ANCHOR RIGHT TEXTURE_FILE_PATTERN = '{surfacing_project}_{surfacing_object}_{channel}_{colorspace}.{udim}.{extension}' #: Default shader node to use DEFAULT_SHADER = 'PxrSurface' #: Materials json Config, contains texture name mappings to shader plugs CONFIG_MATERIALS_JSON = os.path.join( os.environ['LOOKDEVTOOLS'], 'python', 'ldtconfig', 'materials.json') def texture_file_template(custom_pattern=None): """ Get a lucidity Template object using a custom template. Kwargs: custom_pattern (str): Custom lucidity file pattern. Returns: lucity.Template object with the custom partern """ logger.info('Loading lucidity with:\n %s' % custom_pattern) texture_file_template = lucidity.Template( 'textureset_element', custom_pattern, anchor=lucidity.Template.ANCHOR_END # TODO (Eze) Add STRICT? ) return texture_file_template ldtmaya代码: """ .. module:: ldtmaya :synopsis: general maya functions. .. moduleauthor:: Ezequiel Mastrasso """ import ldtcommon import ldtutils from ldtcommon import ATTR_SURFACING_PROJECT from ldtcommon import ATTR_SURFACING_OBJECT from ldtcommon import ATTR_MATERIAL from ldtcommon import ATTR_MATERIAL_ASSIGN from ldtcommon import ATTR_MATERIAL_VP from ldtui import qtutils from Qt import QtGui, QtWidgets, QtCore from Qt.QtWidgets import QApplication, QWidget, QLabel, QMainWindow import os import sys import traceback import random import logging import pymel.core as pm import maya.mel as mel import maya.cmds as mc logger = logging.getLogger(__name__) def surfacingInit(): """ Initialize the scene for surfacing projects. Creates the surfacing root, an empty surfacing project and object, and runs the validation to create and connect the partition Returns: bool. Valid scene. """ root = create_surfacing_root() if not root.members: surfacing_project = create_surfacing_project("defaultProject") create_surfacing_object(surfacing_project, "defaultObject") validate_surfacing() def create_surfacing_root_node(): """Create projects root node""" surfacing_root = pm.createNode( "objectSet", name="surfacing_root" ) surfacing_root.setAttr( "surfacing_root", "", force=True ) return surfacing_root def create_surfacing_root(): """Create projects root if it doesnt exist.""" if not get_surfacing_root(): surfacing_root = get_surfacing_root() return surfacing_root else: return get_surfacing_root() def create_surfacing_project(name=None): """ Creates a surfacing project. Kwargs: name (str): surfacing project name """ if not name: name = "project" surfacing_project = pm.createNode( "objectSet", name=name ) surfacing_project.setAttr( ATTR_SURFACING_PROJECT, "", force=True ) create_surfacing_object(surfacing_project) get_surfacing_root().add(surfacing_project) update_surfacing_partition() return surfacing_project def create_surfacing_object(project, name=None): """ Creates a surfacing Object under a given project. Args: project (PyNode): surfacing project Kwargs: name (str): surfacing object name """ if not name: name = "object" surfacing_set = pm.createNode( "objectSet", name=name ) surfacing_set.setAttr( ATTR_SURFACING_OBJECT, "", force=True ) project.add(surfacing_set) return surfacing_set def get_surfacing_root(): """ Get the project root node. Returns: PyNode. Surfacing root node Raises: Exception. """ objSetLs = [ item for item in pm.ls(type="objectSet") if item.hasAttr("surfacing_root") ] if len(objSetLs) == 0: logger.info( "surfacing_root node found, creating one" ) return create_surfacing_root_node() elif len(objSetLs) > 1: raise Exception( "More than 1 surfacing_root node found, clean up your scene" ) return objSetLs[0] def get_surfacing_projects(): """ Get all surfacing Projects under the root. Returns: list. surfacing projects PyNodes list. """ objSetLs = [ item for item in pm.ls(type="objectSet") if item.hasAttr(ATTR_SURFACING_PROJECT) ] return objSetLs def get_surfacing_project_by_name(name=None): """ Get surfacing Project by name. Kwargs: name (str): surfacing project name. Returns: PyNode. Returns first found hit, we are assuming the objectSet name is equal to surfacing_project attr value. """ projects_list = get_surfacing_projects() for each in projects_list: if name == each.name(): return each return None def get_surfacing_object_by_name(name=None): """ Get surfacing Object by name. Kwargs: name (str): surfacing object name. Returns: PyNode. Returns first found hit, we are assuming the objectSet name is equal to surfacing_object attr value. """ projects_list = get_surfacing_projects() for prj in projects_list: objs = get_surfacing_objects(prj) for obj in objs: if name == obj.name(): return obj return None def delete_surfacing_project(project): """ Delete a surfacing_project, and its members. Args: project (PyNode): surfacing project. """ if is_surfacing_project(project): pm.delete(project.members()) def get_surfacing_objects(project): """ Get all surfacing Objects under the given surfacing project Args: project (PyNode): surfacing project """ if is_surfacing_project(project): return project.members() else: return [] def is_surfacing_project(project): """ Check if the node is a surfacing project Args: project (PyNode): surfacing project Returns: bool. True if it is. """ if project.hasAttr(ATTR_SURFACING_PROJECT): return True else: return False def is_surfacing_object(surfacing_object): """ Check if node is surfacing Object Args: surfacing_object (PyNode): surfacing_object """ if surfacing_object.hasAttr(ATTR_SURFACING_OBJECT): return True else: return False def remove_surfacing_invalid_members(): """ Pops all not-allowd member types from surfacing projects and objects. Only Allowed types: objectSets (surfacing_projects) inside the surfacing projects root objectSets (surfacing_object) inside surfacing projects transforms (that have a mesh) inside surfacing_object """ project_root = get_surfacing_root() for project in project_root.members(): if ( not project.type() == "objectSet" ): # TODO (eze) add check for attr project_root.removeMembers([project]) for project in get_surfacing_projects(): for object in get_surfacing_objects( project ): # TODO (eze) add check for attr if not object.type() == "objectSet": project.removeMembers([object]) else: for member in object.members(): if not member.type() == "transform": logger.info( "removing invalid member: %s" % member ) object.removeMembers([member]) elif not member.listRelatives( type="mesh" ): logger.info( "removing invalid member: %s" % member ) object.removeMembers([member]) def get_mesh_transforms(object_list): # TODO move to common """ Get all the mesh shapes transforms. Includes all descendants in hierarchy. Args: object_list (list): PyNode list of nodes. """ shapes_in_hierarchy = pm.listRelatives( object_list, allDescendents=True, path=True, f=True, type="mesh", ) shapes_transforms = pm.listRelatives( shapes_in_hierarchy, p=True, path=True, f=True ) return shapes_transforms def add_member(surfacing_object, transform): # TODO move to common """ Add transform to surfacing Object Args: surfacing_object (PyNode): surfacing object transform (PyNode): transform node """ pm.sets(surfacing_object, transform, fe=True) def add_mesh_transforms_to_surfacing_object( surfacing_object, object_list ): """ Add all mesh shape transforms -and descendants- from the list to a surfacing Object. Args: surfacing_object (PyNode): surfacing object object_list (list): object list """ pm.select() if is_surfacing_object(surfacing_object): for item in object_list: # Disconnect the objects from other Surf proj and obj for c in item.instObjGroups.listConnections(c=True, p=True): if is_surfacing_object(c[1].node()) or is_surfacing_project(c[1].node()): logger.info( "disconnecting from Surf project or obj: %s" % c[1].node() ) pm.disconnectAttr("%s"%c[0], "%s"%c[1]) for transform in get_mesh_transforms(item): pm.select(transform) add_member(surfacing_object, transform) def update_surfacing_partition(): """Recreate the partition node, and reconnects to all the surfacing objects objectSets.""" partitions = [ item for item in pm.ls(type="partition") if item.hasAttr("surfacing_partition") ] for each in partitions: logger.info( "disconnecting existing partition: %s" % each ) each.sets.disconnect() pm.delete(each) logger.info("deleted partition") surfacing_partition = pm.createNode( "partition", name="surfacing_partition" ) logger.info( "partition created: %s" % surfacing_partition ) surfacing_partition.setAttr( "surfacing_partition", "", force=True ) for project in get_surfacing_projects(): for object in get_surfacing_objects(project): pm.connectAttr( "%s.partition" % object, surfacing_partition.sets, na=True, ) logger.info( "partition connected: %s " % object ) def remove_invalid_characters(): """Remove not allowed characters from surfacing projects and names like '_'.""" project_root = get_surfacing_root() surfacing_projects = get_surfacing_projects() #invalid_character = '_' invalid_character = '*' for project in surfacing_projects: if invalid_character in project.name(): project.rename(project.name().replace(invalid_character, '')) logger.info( 'Invalid character removed from surfacing_project,' 'new name: %s' % project) for surfacing_object in get_surfacing_objects(project): if invalid_character in surfacing_object.name(): surfacing_object.rename( surfacing_object.name().replace(invalid_character, '')) logger.info( 'Invalid characters removed from surfacing_object,' 'new name: %s' % surfacing_object) def validate_surfacing(): """ Validate the scene. Removes invalidad characters and members, updates the partition, and mesh attributes. """ remove_invalid_characters() remove_surfacing_invalid_members() update_surfacing_partition() update_surfacing_attributes() def export_alembic(geo_list, file_path): """ Export alembic file from the object list. Args: geo_list (list): list of geometry to export file_path (str): export file path """ if geo_list and file_path: roots = " -root |" + " -root |".join( [str(x) for x in geo_list] ) cmd = ( r'-frameRange 0 0 -uvWrite -dataFormat ogawa ' r'-userAttrPrefix surfacing' + roots + ' -file ' + (file_path) ) logger.info("AbcExport: %s" % cmd) mc.AbcExport(j=cmd) logger.info( "Succesful Alembic export to: %s" % file_path ) def merge_surfacing_object_meshes(surfacing_object): """ Merge all the meshs assigned to a surfacing Object. Args: surfacing_object (PyNode): surfacing object Raises: BaseException. Could not merge member meshes. """ try: members = surfacing_object.members() logger.info("Merging members: %s" % members) geo_name = "%s_geo" % str(surfacing_object) if len(members) > 1: geo = pm.polyUnite(*members, n=geo_name) return geo[0] else: logger.info( "single object found, skipping merge: %s" % members[0] ) members[0].rename(geo_name) pm.parent(members[0], world=True) return members[0] except BaseException: logger.error( "Could not merge members of: %s" % surfacing_object ) return False def export_surfacing_project(project, subdiv_level=0, single_export=True, folder_path=False): """ Export surfacing Project to Alembic. Args: project (PyNode): surfacing project Kwargs: single_export (bool): is single export folder_path (str): Export folder path """ current_file = pm.sceneName() if single_export: save_unsaved_scene_() if not folder_path: folder_path = qtutils.get_folder_path() project_geo_list = [] if ldtutils.is_directory(folder_path) and is_surfacing_project(project): for each in get_surfacing_objects(project): merged_geo = merge_surfacing_object_meshes(each) if merged_geo: project_geo_list.append(merged_geo) if project_geo_list: if subdiv_level: for geo in project_geo_list: logger.info( "subdivision level: %s" % subdiv_level ) logger.info( "subdividing merged members: %s" % geo ) # -mth 0 -sdt 2 -ovb 1 -ofb 3 -ofc 0 -ost 0 -ocr 0 -dv 3 # -bnr 1 -c 1 -kb 1 -ksb 1 -khe 0 -kt 1 -kmb 1 -suv 1 # -peh 0 -sl 1 -dpe 1 -ps 0.1 -ro 1 -ch 1 pm.polySmooth( geo, mth=0, sdt=2, ovb=1, dv=subdiv_level ) export_file_path = os.path.join( folder_path, str(project) + ".abc" ) export_alembic(project_geo_list, export_file_path) export_surfacing_object_dir = os.path.join( folder_path, str(project) ) ldtutils.create_directoy(export_surfacing_object_dir) for geo in project_geo_list: export_root = " -root |" + geo export_surfacing_object_path = os.path.join( export_surfacing_object_dir + "/" + geo + ".abc" ) export_alembic( [geo], export_surfacing_object_path ) if single_export: pm.openFile(current_file, force=True) def export_all_surfacing_projects(folder_path=None, subdiv_level=0): """ Export all surfacing Projects. Kwargs: folder_path (str): folder to export files. """ save_unsaved_scene_() if not folder_path: folder_path = qtutils.get_folder_path() current_file = pm.sceneName() for project in get_surfacing_projects(): export_surfacing_project( project, subdiv_level, single_export=False, folder_path=folder_path ) pm.openFile(current_file, force=True) return True def save_unsaved_scene_(): # TODO move to common """Check the scene state, if modified, will ask the user to save it.""" if unsaved_scene(): if save_scene_dialog(): pm.saveFile(force=True) else: raise ValueError("Unsaved changes") def update_surfacing_attributes(): """ Create attributes on meshes of what surfacing object they are assigned to. Adds the attributes to all the shapes transforms assigned to surfacing objects. This will be used later for quick shader/material creation and assignment. """ for project in get_surfacing_projects(): project.setAttr(ATTR_SURFACING_PROJECT, project) logger.info( "Updating attributes for project: %s" % project ) for surfacing_object_set in get_surfacing_objects(project): logger.info( "\tUpdating attributes for object texture set: %s" % surfacing_object_set ) surfacing_object_set.setAttr( ATTR_SURFACING_OBJECT, surfacing_object_set ) members = surfacing_object_set.members() logger.info( "\t\tUpdating attr for meshes: %s" % members ) for member in members: member.setAttr( ATTR_SURFACING_PROJECT, project.name(), force=True, ) member.setAttr( ATTR_SURFACING_OBJECT, surfacing_object_set.name(), force=True, ) def set_wifreframe_color_black(): """Set the wireframe color to black in all mesh objects.""" transforms = pm.ls(type="transform") shape_transforms = get_mesh_transforms(transforms) for mesh in shape_transforms: mesh_shape = mesh.getShape() mesh_shape.overrideEnabled.set(1) mesh_shape.overrideRGBColors.set(0) mesh_shape.overrideColor.set(1) def set_wifreframe_color_none(): """Remove the wireframe color in all mesh objects.""" transforms = pm.ls(type="transform") shape_transforms = get_mesh_transforms(transforms) for mesh in shape_transforms: mesh_shape = mesh.getShape() mesh_shape.overrideEnabled.set(0) def set_wireframe_colors_per_project(): """ Set the wireframe color per surfacing project. For all meshes, sets it to black to start with, this implies that the mesh has not be assigned to any surfacing object yet will show black in the VP """ set_wifreframe_color_black() projects = get_surfacing_projects() for project in projects: random.seed(project) wire_color = random.randint(1, 31) for surfacingObject in get_surfacing_objects(project): for mesh in surfacingObject.members(): mesh_shape = mesh.getShape() try: mesh_shape.overrideEnabled.set(1) mesh_shape.overrideRGBColors.set(0) mesh_shape.overrideColor.set(wire_color) except: logger.error('Could not set override color for: %s, might ' 'belong to a display layer' % mesh ) def set_wireframe_colors_per_object(): """ Set the wireframe color per surfacing object. For all meshes, sets it to black to start with, this implies that the mesh has not be assigned to any surfacing object yet will show black in the VP """ set_wifreframe_color_black() projects = get_surfacing_projects() print projects for project in projects: for surfacingObject in get_surfacing_objects(project): for mesh in surfacingObject.members(): mesh_shape = mesh.getShape() try: mesh_shape.overrideEnabled.set(1) mesh_shape.overrideRGBColors.set(1) mesh_shape.overrideColorRGB.set( ldtutils.get_random_color(surfacingObject) ) except: logger.error('Could not set override color for: %s, might ' 'belong to a display layer' % mesh ) def set_materials_per_object(shader_type): """Create a material per surfacing project and assigns it""" delete_materials() projects = get_surfacing_projects() for project in projects: for obj in get_surfacing_objects(project): shader, shading_group = create_shader( type=shader_type) pm.select(obj) meshes = pm.ls(sl=True) pm.sets(shading_group, forceElement=meshes) pm.select(None) if shader_type == 'aiStandardSurface': shader.baseColor.set( ldtutils.get_random_color(obj) ) else: shader.color.set( ldtutils.get_random_color(obj) ) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL), 'obj', force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_ASSIGN), obj.name(), force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_VP), 'color', force=True) def set_materials_per_project(shader_type): """Create a material per surfacing project and assigns it""" delete_materials() projects = get_surfacing_projects() for project in projects: shader, shading_group = create_shader( type=shader_type) pm.select(project) meshes = pm.ls(sl=True) pm.sets(shading_group, forceElement=meshes) pm.select(None) if shader_type == 'aiStandardSurface': shader.baseColor.set( ldtutils.get_random_color(project) ) else: shader.color.set( ldtutils.get_random_color(project) ) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL), 'project', force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_ASSIGN), project.name(), force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_VP), 'color', force=True) def delete_materials(): """delete all material networks that have surfacing attributes""" all_shading_groups = pm.ls(type="shadingEngine") to_delete = [] for shading_group in all_shading_groups: if pm.hasAttr(shading_group, ATTR_MATERIAL): to_delete.append(shading_group) pm.delete(to_delete) def delete_materials_viewport(type=None): """ delete all material networks that have surfacing attributes. Kwargs: type (str): type of vp material to delete, usually 'color', or 'pattern' """ all_shading_groups = pm.ls(type="shadingEngine") to_delete = [] for shading_group in all_shading_groups: if pm.hasAttr(shading_group, ATTR_MATERIAL_VP): to_delete.append(shading_group) pm.delete(to_delete) def unsaved_scene(): """Check for unsaved changes.""" import maya.cmds as cmds return cmds.file(q=True, modified=True) def save_scene_dialog(): """ Ask the user to go ahead save or cancel the operation. Returns: bool. True is Ok clicked, false otherwise. """ msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Your scene has unsaved changes") msg.setInformativeText("") msg.setWindowTitle("Warning") msg.setDetailedText( "This tool will do undoable changes. It requires you to save your scene, and reopen it after its finished" ) msg.setStandardButtons( QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel ) retval = msg.exec_() if retval == QtWidgets.QMessageBox.Ok: return True else: return False def create_file_node(name=None): """ Create a file node, and its 2dPlacement Node. Kwargs: name (str): file node name Returns: PyNode. Image file node """ file_node = pm.shadingNode( 'file', name=name, asTexture=True, isColorManaged=True) placement_name = '%s_place2dfile_nodeture' % name placement_node = pm.shadingNode( 'place2dTexture', name=placement_name, asUtility=True) file_node.filterType.set(0) pm.connectAttr(placement_node.outUV, file_node.uvCoord) pm.connectAttr(placement_node.outUvFilterSize, file_node.uvFilterSize) pm.connectAttr(placement_node.coverage, file_node.coverage) pm.connectAttr(placement_node.mirrorU, file_node.mirrorU) pm.connectAttr(placement_node.mirrorV, file_node.mirrorV) pm.connectAttr(placement_node.noiseUV, file_node.noiseUV) pm.connectAttr(placement_node.offset, file_node.offset) pm.connectAttr(placement_node.repeatUV, file_node.repeatUV) pm.connectAttr(placement_node.rotateFrame, file_node.rotateFrame) pm.connectAttr(placement_node.rotateUV, file_node.rotateUV) pm.connectAttr(placement_node.stagger, file_node.stagger) pm.connectAttr(placement_node.translateFrame, file_node.translateFrame) pm.connectAttr(placement_node.wrapU, file_node.wrapU) pm.connectAttr(placement_node.wrapV, file_node.wrapV) return file_node def create_shader(type='PxrSurface'): """ Create shaders and shading groups. Kwargs: type (str): type of material shader to create, for ie 'blinn' tag (str): tag to set in ATTR_MATERIAL, usually the surfacing project or surfacing object Returns: tuple. PyNode shader, and PyNode shading_group """ shader, shading_group = pm.createSurfaceShader(type) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL), '', force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_ASSIGN), '', force=True) pm.setAttr('%s.%s' % (shading_group, ATTR_MATERIAL_VP), '', force=True) return shader, shading_group def import_surfacing_textures(): """ TODO WE DONT REALLY NEED THIS DONT WE TODO THIS IS A WORKING HARDCODED IMPORT, IMPLEMENT CORRECTLY Import textures to surfacing objects or projects. Kwargs: parsed_files (list): list of lucidity parsed files with 'filepath' key key (str): surfacing attr to use for import, surfacing project or surfacing object shaders (list): a list of shaders, where the keys match the parsed files key to use for import """ import pymel.core as pm from ldtcommon import TEXTURE_FILE_PATTERN import ldtmaya import ldtutils import ldttextures textures_folder = '/run/media/ezequielm/misc/wrk/current/cabinPixar/textures' texture_list = ldtutils.get_files_in_folder( textures_folder, recursive=True, pattern='.tex') texture_finder = ldttextures.TextureFinder( TEXTURE_FILE_PATTERN, texture_list) texture_finder.get_channel_plug(texture_list[0]) for surfPrj in ldtmaya.get_surfacing_projects(): for surfObj in ldtmaya.get_surfacing_objects(surfPrj): # Find texture files with a matching surfacing_project, get udim paths texture_files = texture_finder.find_key_values( surfacing_project=surfPrj, merge_udims=True) if texture_files: print surfObj # create and assign the material to each surfacing_object pm.select(surfObj) meshes = pm.ls(sl=True) shader, shading_group = ldtmaya.create_shader() shader.rename('%s_%s' % (surfObj, 'material')) pm.sets(shading_group, forceElement=meshes) pm.select(None) for texture_file in texture_files: # get the shader plug input, to connect the texture to shader_plug = texture_finder.get_channel_plug(texture_file) if shader_plug: shader_plug = pm.PyNode( '%s.%s' % (shader.name(), shader_plug)) # create image nodes file_node = ldtmaya.create_file_node( '%s_%s' % (surfObj, shader_plug)) # paths come with 'udim', replac this with the prman <UDIM> file_node.fileTextureName.set( texture_file.replace('udim', '<UDIM>')) pm.setAttr('%s.%s' % (file_node, 'uvTilingMode'), 3) pm.setAttr('%s.%s' % (file_node, 'alphaIsLuminance'), 1) # TODO Query the shader plug, connect RGB or single channel # TODO if a normal or bump, create the inbetween node # if shader_plug == "normal" or shader_plug == "bump" print "plug %s -->%s" % (texture_file, shader_plug) if len(shader_plug.elements()) == 4: if "bump" in shader_plug.name(): bump_node = pm.shadingNode( 'bump2d', asTexture=True) bump_node.rename('%s_%s' % (surfObj, 'bump')) file_node.outAlpha.connect(bump_node.bumpValue) bump_node.outNormal.connect(shader_plug) else: file_node.outColor.connect(shader_plug) else: file_node.outAlpha.connect(shader_plug) ldtui代码:init_.py: """ .. module:: ldtui :synopsis: Main tools UI. .. moduleauthor:: Ezequiel Mastrasso """ from Qt import QtGui, QtWidgets, QtCore from Qt.QtWidgets import QApplication, QWidget, QLabel, QMainWindow import sys import imp import os import logging from functools import partial from ldtui import qtutils import ldt logger = logging.getLogger(__name__) class LDTWindow(QMainWindow): '''Main Tools UI Window. Loads the plugInfo.plugin_object.plugin_layout QWidget from all loaded plugins as tabs''' def __init__(self, plugins): super(LDTWindow, self).__init__() self.setWindowTitle("Look Dev Tool Set") self.setGeometry(0, 0, 650, 600) layout = QtWidgets.QGridLayout() self.setLayout(layout) tabwidget = QtWidgets.QTabWidget() tabwidget.setTabBar(qtutils.HTabWidget(width=150, height=50)) tabwidget.setTabPosition(QtWidgets.QTabWidget.West) # Stylesheet fix for Katana # With default colors, the tab text is almost the # same as the tab background stylesheet = """ QTabBar::tab:unselected {background: #222222;} QTabWidget>QWidget>QWidget{background: #222222;} QTabBar::tab:selected {background: #303030;} QTabWidget>QWidget>QWidget{background: #303030;} """ tabwidget.setStyleSheet(stylesheet) layout.addWidget(tabwidget, 0, 0) plugins_ui = {} plugins_buttons = {} for pluginInfo in plugins.getAllPlugins(): tabwidget.addTab( pluginInfo.plugin_object.plugin_layout, pluginInfo.name) self.setCentralWidget(tabwidget) qtutils.py: """ .. module:: qtutils :synopsis: small qt utilies and custom widgets. .. moduleauthor:: Ezequiel Mastrasso """ from Qt import QtGui, QtWidgets, QtCore from Qt.QtWidgets import QApplication, QWidget, QLabel, QMainWindow import logging logger = logging.getLogger(__name__) def get_folder_path(): """Gets a folder path from the user""" file_dialog = QtWidgets.QFileDialog() file_dialog.setFileMode(QtWidgets.QFileDialog.Directory) if file_dialog.exec_(): path = str(file_dialog.selectedFiles()[0]) return path else: return None class HTabWidget(QtWidgets.QTabBar): ''' QPaint event to draw the QTabWidget titles horizontally ''' def __init__(self, *args, **kwargs): self.tabSize = QtCore.QSize(kwargs.pop('width'), kwargs.pop('height')) super(HTabWidget, self).__init__(*args, **kwargs) def paintEvent(self, event): painter = QtWidgets.QStylePainter(self) option = QtWidgets.QStyleOptionTab() for index in range(self.count()): self.initStyleOption(option, index) tabRect = self.tabRect(index) tabRect.moveLeft(10) painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option) painter.drawText(tabRect, QtCore.Qt.AlignVCenter | QtCore.Qt.TextDontClip, self.tabText(index)) def tabSizeHint(self, index): return self.tabSize ldtutils代码: """ .. module:: ldtutils :synopsis: general non dcc specific utils. .. moduleauthor:: Ezequiel Mastrasso """ from ldtcommon import CONFIG_MATERIALS_JSON from ldtcommon import TEXTURE_CHANNEL_MATCHING_RATIO from ldtcommon import TEXTURE_MATCHING_RATIO from fuzzywuzzy import fuzz import subprocess import multiprocessing import sys import json import logging import os import random import lucidity logger = logging.getLogger(__name__) def create_commands(texture_mapping): default_command = "maya -batch -file someMayaFile.mb -command " commands = [] for key, value in texture_mapping: dir, filename = os.path.split(key) filename, ext = os.path.splitext(filename) filename = os.path.join(dir, filename + "WithTexture." + ext) commands.append("".format(default_command, "abc_file", key, "texture", value, "file -save ", filename)) return commands def launch_function(func, args): commands = create_commands(args) launch_multiprocess(launch_subprocess, commands) def launch_subprocess(command): try: subprocess_output = subprocess.check_output(command) logger.info("Subprocess launched\t{out}\nrunning the command\t{command}", out=subprocess_output, command=command) except subprocess.CalledProcessError as e: logger.exception( "Error while trying to launch subprocess: {}".format(e.output)) raise return command def launch_multiprocess(function, args): """ :param function: Function to be called inside the multiprocess -- Takes only 1 arg :param args: list/tuple of arguments for above function :return: """ multiprocessing.freeze_support() pool = multiprocessing.Pool(processes=int(multiprocessing.cpu_count()/2)) logger.debug("Pool created") try: pool_process = pool.map_async(function, (args)) except Exception as e: msg = "Error while trying to launch process in pool: {}".format(e) logger.exception(msg) raise finally: pool.close() pool.join() try: logger.info("output from the process: {pool_out}", out=pool_process.successful()) return 0 except AssertionError: logger.exception("Couldn't communicate with the process poll created; \ No output from processes fetched") return 1 def map_textures_to_alembic(texture_mapping): launch_subprocess(command) def load_json(file_path): """ Load a json an returns a dict. Args: file_path (str): Json file path to open. """ with open(file_path) as handle: dictdump = json.loads(handle.read()) return dictdump def save_json(file_path, data): """ Dump a dict into a json file. Args: file_path (str): Json file path to save. data (dict): Data to save into the json file. """ # TODO (eze) pass def get_random_color(seed): """ Return a random color using a seed. Used by all material creating, and viewport color functions that do not use textures, to have a common color accross dccs Args: seed (str): Returns: tuple, R,G,B colors. """ random.seed(seed + "_r") color_red = random.uniform(0, 1) random.seed(seed + "_g") color_green = random.uniform(0, 1) random.seed(seed + "_b") color_blue = random.uniform(0, 1) return color_red, color_green, color_blue def create_directoy(path): """ Create a folder. Args: path (str): Directory path to create. """ os.mkdir(path) logger.info("Directory created: %s" % path) def is_directory(path): """ Check if the given path exists, and is a directory. Args: path (str): Directory to check. """ if os.path.exists(path) and os.path.isdir(path): return True else: return False def get_files_in_folder(path, recursive=False, pattern=None): """ Search files in a folder. Args: path (str): Path to search. Kwards: recursive (bool): Search files recursively in folder. pattern (str): pattern to match, for ie '.exr'. Returns: array. File list """ logger.info("Searching for files in: %s" % path) logger.info("Searching options: Recursive %s, pattern: %s" % (recursive, pattern)) file_list = [] for path, subdirs, files in os.walk(path): for file in files: # skip .mayaswatchs stuff if ".maya" not in file: if pattern: if pattern in file: file_list.append(os.path.join(path, file)) logger.debug( "File with pattern found, added to the list: %s" % file) else: file_list.append(os.path.join(path, file)) logger.debug("File added to the list: %s" % file) if not recursive: break return file_list def string_matching_ratio(stringA, stringB): """ Compare two strings and returns a fuzzy string matching ratio. In general ratio, partial_ratio, token_sort_ratio and token_set_ratio did not give different results given that we are comparin a single. TODO: Try bitap algorithm for fuzzy matching, partial substring matching might be better for our cases. Different channels fuzzy ratio comparission ('baseColor','diffusecolor') = 67 ('base','diffusecolor') = 25 ('specular','specularColor') = 76 ('specular','specularcolor') = 76 ('specular_color', 'specular_bump') = 67 ('coat_color', 'coat_ior') = 78 ('secondary_specular_color', 'secondary_specular_ior') = 91 ('subsurface_weight', 'subsurface_Color') = 67 ('emission', 'emission_weight') = 70 Same channel diferent naming ratio comparission ('diffuse_weight','diffuseGain') = 64 Args: stringA (str): string to compare against. stringB (str): string to compare. Returns: int. Ratio, from 0 to 100 according to fuzzy matching. """ return fuzz.token_set_ratio(stringA, stringB) def get_config_materials(): """ Gets the CONFIG_MATERIALS_JSON as a dict Returns: dict. CONFIG_MATERIALS_JSON """ return load_json(CONFIG_MATERIALS_JSON)
08-21
麻烦帮我优化这段代码,需要保留完整功能和逻辑from PySide2 import QtGui from PySide2 import QtWidgets, QtCore from shiboken2 import wrapInstance from maya.app.general.mayaMixin import MayaQWidgetDockableMixin from maya import OpenMayaUI as omui import maya.OpenMaya as om import maya.cmds as cmds import maya.mel as mel import os, platform, subprocess, sys import xml.dom.minidom as xml # 用于XML设置 DEBUG = False PRNT_STRING = "<RizomUV桥接工具>" # 日志前缀汉化 try: # Python 3 from . import scriptlist except ImportError: import scriptlist class Settings(): def __init__(self): config_path = os.path.join('%s/RizomBridge' % os.getenv('APPDATA')) config_file = 'uisettings.xml' # 脚本路径设置 rizom_script_path = os.path.join(config_path, "MayaRizomBridgeScript.lua") self.rizom_script_path = rizom_script_path.replace('\\', '/') self.apppath = None self.config_file_path = os.path.join(config_path, config_file) self.check_config_exists(config_path) try: self.read_settings() except: print("<RizomUV桥接工具> 读取设置失败,正在创建新的xml文件。") # 日志汉化 self.set_defaults() self.save_xml() self.read_settings() self.exportFile = os.path.join(config_path, self.objname) self.exportFile = self.exportFile.replace('\\', '/') def read_settings(self): doc = xml.parse(self.config_file_path) ui_app = doc.getElementsByTagName("Application")[0] self.apppath = ui_app.getAttribute("apppath") self.objname = ui_app.getAttribute("objname") self.upaxis = ui_app.getAttribute("upaxis") self.loaduvs = self.str_to_bool(ui_app.getAttribute("loaduvs")) self.useuvlink = self.str_to_bool(ui_app.getAttribute("useuvlink")) self.fixuvnames = self.str_to_bool(ui_app.getAttribute("fixuvnames")) ui_packer = doc.getElementsByTagName("Packer")[0] self.quality = int(ui_packer.getAttribute("quality")) self.mutations = int(ui_packer.getAttribute("mutations")) self.margin = int(ui_packer.getAttribute("margin")) self.spacing = int(ui_packer.getAttribute("spacing")) self.resolution = int(ui_packer.getAttribute("resolution")) self.initscaleavg = self.str_to_bool(ui_packer.getAttribute("initscaleavg")) self.autofit = self.str_to_bool(ui_packer.getAttribute("autofit")) def set_defaults(self): self.objname = "MayaRizomExport.fbx" self.upaxis = "Y" self.loaduvs = True self.useuvlink = True self.fixuvnames = False self.quality = 2 self.mutations = 256 self.margin = 2 self.spacing = 2 self.resolution = 1024 self.initscaleavg = True self.autofit = True self.apppath = self.findall_rizom_installs()[-1] def save_xml(self): print(PRNT_STRING, f"将设置保存到磁盘: {self.config_file_path}") # 日志汉化 doc = xml.Document() root_element = doc.createElement("RizomBridge") element_application = doc.createElement("Application") element_application.setAttribute("apppath", str(self.apppath)) element_application.setAttribute("objname", str(self.objname)) element_application.setAttribute("upaxis", str(self.upaxis)) element_application.setAttribute("loaduvs", str(self.loaduvs)) element_application.setAttribute("useuvlink", str(self.useuvlink)) element_application.setAttribute("fixuvnames", str(self.fixuvnames)) element_packer = doc.createElement("Packer") element_packer.setAttribute("quality", str(self.quality)) element_packer.setAttribute("mutations", str(self.mutations)) element_packer.setAttribute("margin", str(self.margin)) element_packer.setAttribute("spacing", str(self.spacing)) element_packer.setAttribute("resolution", str(self.resolution)) element_packer.setAttribute("initscaleavg", str(self.initscaleavg)) element_packer.setAttribute("autofit", str(self.autofit)) doc.appendChild(root_element) root_element.appendChild(element_application) root_element.appendChild(element_packer) doc.writexml(open(self.config_file_path, 'w'), indent=" ", addindent=" ", newl='\n') def check_config_exists(self, config_path): print(PRNT_STRING, f"检查配置文件: {self.config_file_path}") # 日志汉化 if not os.path.exists(config_path): os.makedirs(config_path) if not os.path.exists(self.config_file_path): print(PRNT_STRING, "未找到配置文件。") # 日志汉化 self.set_defaults() self.save_xml() else: print(PRNT_STRING, "找到配置文件。") # 日志汉化 def findall_rizom_installs(self): """ 返回注册表中所有存在的rizom.exe路径 """ try: import winreg except: self.manual_locate_rizom() return [self.apppath] key_path = "SOFTWARE\\Rizom Lab\\" parent_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) installs = [] i = 0 while i < 1000: try: key = winreg.EnumKey(parent_key, i) try: exe_path = winreg.QueryValue(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path + key), "rizomuv.exe") + ".exe" except FileNotFoundError: exe_path = "" if os.path.exists(exe_path): installs.append(exe_path.replace("\\", "/")) except WindowsError: break i += 1 print(PRNT_STRING, "在Windows注册表中找到RizomUV安装路径:") # 日志汉化 for inst in sorted(installs): print(" ..", inst) return sorted(installs) def manual_locate_rizom(self): om.MGlobal.displayWarning(f"无法定位rizomuv.exe: {self.apppath}") # 提示汉化 fname = QtWidgets.QFileDialog.getOpenFileName(None, '定位rizomuv.exe', 'C:/Program Files/Rizom Lab/', "可执行文件 (*.exe)") # 对话框标题及过滤器汉化 self.apppath = fname[0] self.appver = self.get_version() self.save_xml() def get_version(self): """ 从文件夹名称读取版本号,返回列表形式,例如 [2022, 2] """ # 注释汉化 return os.path.dirname(self.apppath).split()[-1].split('.') def check_lua_path(self): if not os.path.exists(self.rizom_script_path): with open(self.rizom_script_path, 'w') as f: if DEBUG: print(PRNT_STRING, f"在{self.rizom_script_path}创建空白lua文件") # 日志汉化 f.write('') def str_to_bool(self, s): if s == 'True': return True else: # 其他情况均返回False,否则可能返回None导致崩溃 return False class RizomUVBridgeWindow(MayaQWidgetDockableMixin, QtWidgets.QDialog): def __init__(self, rootWidget=None, *args, **kwargs): super(RizomUVBridgeWindow, self).__init__() self.conf = Settings() self.conf.check_lua_path() print("Rizom路径:", self.conf.apppath) # 日志汉化 self.setWindowTitle("桥接工具") # 窗口标题汉化 self.sj_num_selchange = cmds.scriptJob(parent=self.objectName(), event=['SelectionChanged', self.ui_update_uvchannels]) self.resize(250, 300) self.create_widgets() self.create_layouts() self.create_connections() self.exported_objects = [] self.ui_update_uvchannels() self.cleanse_namespaces() self.config_updated = False if not os.path.exists(self.conf.apppath): self.conf.manual_locate_rizom() v = self.conf.get_version() self.btn_run.setText(f'运行RizomUV {v[0]}.{v[1]}') # 按钮文本汉化 rizom_link_path = os.path.dirname(self.conf.apppath) + '/RizomUVLink' self.port = None if rizom_link_path not in sys.path: sys.path.append(os.path.dirname(self.conf.apppath) + '/RizomUVLink') try: from RizomUVLink import CRizomUVLink self.link = CRizomUVLink() except: self.link = None def create_widgets(self): v = ".".join(self.conf.get_version()) self.btn_run = QtWidgets.QPushButton(f'运行RizomUV {v}', self) # 按钮文本汉化 self.btn_export = QtWidgets.QPushButton('导出', self) # 按钮文本汉化 self.btn_import = QtWidgets.QPushButton('导入', self) # 按钮文本汉化 self.cbx_use_link = QtWidgets.QCheckBox('尝试使用CRizomUVLink连接', self) # 复选框文本汉化 self.cbx_use_link.setChecked(self.conf.useuvlink) self.cbx_fix_set_names = QtWidgets.QCheckBox('导入时修复UV集名称', self) # 复选框文本汉化 self.cbx_fix_set_names.setChecked(self.conf.fixuvnames) if not os.path.exists(self.conf.exportFile): self.btn_import.setEnabled(False) # 导出设置组件 self.radioAxisY = QtWidgets.QRadioButton('Y轴') # 单选按钮文本汉化 self.radioAxisZ = QtWidgets.QRadioButton('Z轴') # 单选按钮文本汉化 if self.conf.upaxis == 'Y': self.radioAxisY.setChecked(True) else: self.radioAxisZ.setChecked(True) self.cbx_keepuv = QtWidgets.QCheckBox('加载现有UV', self) # 复选框文本汉化 self.cbx_keepuv.setChecked(self.conf.loaduvs) self.combo_scripts = QtWidgets.QComboBox(self) self.combo_scripts.addItem("无脚本") # 下拉框文本汉化 for s in scriptlist.scripts: self.combo_scripts.addItem(s[1]) # 工具组件 self.btn_fix_shell_normals = QtWidgets.QPushButton('将UV边界边设为硬边') # 按钮文本汉化 self.btn_edit_settings = QtWidgets.QPushButton('打开设置文件夹') # 按钮文本汉化 self.combo_pack_uvset = QtWidgets.QComboBox(self) self.btn_pack = QtWidgets.QPushButton('导出并打包UV', self) # 按钮文本汉化 self.combo_pack_quality = QtWidgets.QComboBox(self) self.combo_pack_quality.addItems(['低', '普通', '高', '较高', '极高']) # 下拉框文本汉化 self.combo_pack_quality.setCurrentIndex(self.conf.quality) self.slider_pack_uvmap = QtWidgets.QSlider(QtCore.Qt.Orientation(1)) self.slider_pack_uvmap.setMinimum(0) self.slider_pack_uvmap.setMaximum(5) self.slider_pack_uvmap.setValue(1) self.label_uvmap = QtWidgets.QLabel("1") self.dspin_pack_mutations = QtWidgets.QSpinBox() self.dspin_pack_mutations.setSingleStep(1) self.dspin_pack_mutations.setRange(1, 1000) self.dspin_pack_mutations.setWrapping(False) self.dspin_pack_mutations.setValue(self.conf.mutations) self.dspin_pack_resolution = QtWidgets.QSpinBox() self.dspin_pack_resolution.setSingleStep(8) self.dspin_pack_resolution.setRange(8, 8192) self.dspin_pack_resolution.setWrapping(False) self.dspin_pack_resolution.setValue(self.conf.resolution) self.dspin_pack_margin = QtWidgets.QSpinBox() self.dspin_pack_margin.setSingleStep(1) self.dspin_pack_margin.setWrapping(False) self.dspin_pack_margin.setValue(self.conf.margin) self.dspin_pack_spacing = QtWidgets.QSpinBox() self.dspin_pack_spacing.setSingleStep(1) self.dspin_pack_spacing.setWrapping(False) self.dspin_pack_spacing.setValue(self.conf.spacing) self.cbx_initial_scale_avg = QtWidgets.QCheckBox("使用'平均'初始缩放", self) # 复选框文本汉化 self.cbx_initial_scale_avg.setChecked(self.conf.initscaleavg) self.cbx_layout_scaling = QtWidgets.QCheckBox("布局:自动适配", self) # 复选框文本汉化 self.cbx_layout_scaling.setChecked(self.conf.autofit) def create_layouts(self): main_layout = QtWidgets.QVBoxLayout(self) grp_layout = QtWidgets.QVBoxLayout() grp_layout.addWidget(self.btn_run) grp_layout.addWidget(self.btn_export) grp_layout.addWidget(self.btn_import) grp_layout.addWidget(self.cbx_use_link) grp_layout.addWidget(self.cbx_fix_set_names) grp = QtWidgets.QGroupBox("UV操作") # 组框标题汉化 grp.setLayout(grp_layout) main_layout.addWidget(grp) # 导出设置 grp_layout = QtWidgets.QVBoxLayout() grp_layout.addWidget(self.cbx_keepuv) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("脚本")) # 标签文本汉化 hor_layout.addWidget(self.combo_scripts) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("上方向轴")) # 标签文本汉化 hor_layout.addWidget(self.radioAxisY) hor_layout.addWidget(self.radioAxisZ) grp_layout.addLayout(hor_layout) grp = QtWidgets.QGroupBox("导出设置") # 组框标题汉化 grp.setLayout(grp_layout) main_layout.addWidget(grp) # 工具 grp_layout = QtWidgets.QVBoxLayout() grp_layout.addWidget(self.btn_fix_shell_normals) grp_layout.addWidget(self.btn_edit_settings) grp = QtWidgets.QGroupBox("工具") # 组框标题汉化 grp.setLayout(grp_layout) main_layout.addWidget(grp) # UV打包 grp_layout = QtWidgets.QVBoxLayout() grp = QtWidgets.QGroupBox("UV打包") # 组框标题汉化 hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(self.btn_pack) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("要打包的UV集")) # 标签文本汉化 hor_layout.addWidget(self.combo_pack_uvset) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("打包质量")) # 标签文本汉化 hor_layout.addWidget(self.combo_pack_quality) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("迭代次数")) # 标签文本汉化 hor_layout.addWidget(self.dspin_pack_mutations) hor_layout.addWidget(QtWidgets.QLabel("分辨率")) # 标签文本汉化 hor_layout.addWidget(self.dspin_pack_resolution) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(QtWidgets.QLabel("边距")) # 标签文本汉化 hor_layout.addWidget(self.dspin_pack_margin) hor_layout.addWidget(QtWidgets.QLabel("间距")) # 标签文本汉化 hor_layout.addWidget(self.dspin_pack_spacing) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(self.cbx_initial_scale_avg) grp_layout.addLayout(hor_layout) hor_layout = QtWidgets.QHBoxLayout() hor_layout.addWidget(self.cbx_layout_scaling) grp_layout.addLayout(hor_layout) grp_layout.addStretch() grp.setLayout(grp_layout) main_layout.addWidget(grp) def create_connections(self): self.btn_run.clicked.connect(self.riz_run) self.btn_export.clicked.connect(self.riz_export) self.btn_import.clicked.connect(self.riz_import) self.btn_fix_shell_normals.clicked.connect(fix_shell_border_normals) self.btn_edit_settings.clicked.connect(self.browse_settings_location) self.cbx_keepuv.stateChanged.connect(self.set_config) self.slider_pack_uvmap.valueChanged.connect(self.ui_pack_update_labels) self.radioAxisY.clicked.connect(self.set_config) self.radioAxisZ.clicked.connect(self.set_config) self.dspin_pack_mutations.valueChanged.connect(self.set_config) self.dspin_pack_resolution.valueChanged.connect(self.set_config) self.dspin_pack_margin.valueChanged.connect(self.set_config) self.dspin_pack_spacing.valueChanged.connect(self.set_config) self.cbx_layout_scaling.stateChanged.connect(self.set_config) self.cbx_use_link.stateChanged.connect(self.set_config) self.cbx_fix_set_names.stateChanged.connect(self.set_config) self.btn_pack.clicked.connect(self.riz_pack) return def riz_run(self): # 确认应用程序路径 if not os.path.exists(self.conf.apppath): self.manual_locate_rizom() if self.link and self.cbx_use_link.isChecked(): self.port = self.link.RunRizomUV() print(PRNT_STRING, f"RizomUV {self.link.RizomUVVersion()}链接已建立。正在TCP端口{self.port}监听命令") # 日志汉化 else: # 链接不可用时使用原始方法 print(PRNT_STRING, "RizomUV链接不可用。将使用LUA脚本文件通信。") # 日志汉化 cmd = '"' + self.conf.apppath + '" -cf "' + self.conf.rizom_script_path + '"' print(cmd) if platform.system() == "Windows": self.sp = subprocess.Popen(cmd, shell=True) else: self.sp = subprocess.Popen(["open", "-a", self.conf.apppath, "-cf", self.conf.rizom_script_path]) self.btn_export.setEnabled(True) return def riz_pack(self): # 导出模型不加载脚本 current_uv = self.combo_pack_uvset.currentText() exported = self.riz_export(False, False) if not exported: return # 根据GUI选项构建LUA代码 cmd = '' # 重复使用的文本块 cmd_properties_prefix = 'ZomIslandGroups({Mode="SetGroupsProperties", WorkingSet="Visible", MergingPolicyString="A_ADD|AIB_ADD_A_VALUE_B|B_CLONE", GroupPaths={ "RootGroup" }, ' # 加载模型 cmd += 'ZomLoad({File={Path="'+self.conf.exportFile+'", ImportGroups=true, XYZUVW=true, UVWProps=true}})\n' cmd += 'ZomUvset({Mode="SetCurrent", Name="%s"})\n' % current_uv cmd += cmd_properties_prefix + 'Properties={Pack={Rotate={Step=90}}}})\n' cmd += cmd_properties_prefix + 'Properties={Pack={Rotate={Mode=0}}}})\n' margin = float(self.dspin_pack_margin.value()) / self.dspin_pack_resolution.value() spacing = float(self.dspin_pack_spacing.value()) / self.dspin_pack_resolution.value() cmd += cmd_properties_prefix + 'Properties={Pack={SpacingSize=%f}}})\n' % spacing cmd += cmd_properties_prefix + 'Properties={Pack={MarginSize=%f}}})\n' % margin quality = [128, 256, 512, 1024, 2048] cmd += cmd_properties_prefix + 'Properties={Pack={Resolution=%i}}})\n' % quality[self.combo_pack_quality.currentIndex()] cmd += cmd_properties_prefix + 'Properties={Pack={MaxMutations=%i}}})\n' % self.dspin_pack_mutations.value() init_scale = 0 if self.cbx_initial_scale_avg.isChecked(): init_scale = 2 layout_scale = 0 if self.cbx_layout_scaling.isChecked(): layout_scale = 2 cmd += 'ZomSet({Path="Prefs.PackOptions.__ScalingMode", Value=%i})\n' % init_scale cmd += 'ZomSave({File={Path="c:/users/root/appdata/local/temp/MayaRizomExport.fbx", UVWProps=true}, __UpdateUIObjFileName=true})\n' cmd += 'ZomIslandGroups({Mode="DistributeInTilesEvenly", WorkingSet="Visible&Flat", MergingPolicyString="A_ADD|AIB_ADD_A_VALUE_B|B_CLONE", UseTileLocks=true, UseIslandLocks=true})\n' cmd += 'ZomPack({RootGroup="RootGroup", WorkingSet="Visible&Flat", ProcessTileSelection=false, RecursionDepth=1, Translate=true, LayoutScalingMode=%i, Scaling={Mode=%i}})\n' % (layout_scale, init_scale) if DEBUG: print(cmd) self.write_to_lua_file(cmd) return def fbx_export(self): # FBX导出 if not cmds.pluginInfo("fbxmaya", loaded=True, query=True): cmds.loadPlugin("fbxmaya") cmds.undoInfo(openChunk=True) mel.eval('ConvertInstanceToObject;') # 这是唯一需要撤销的命令 mel.eval('FBXExportSmoothingGroups -v true;') mel.eval('FBXExportTriangulate -v false;') mel.eval('FBXExportSmoothMesh -v false;') mel.eval('FBXExportUpAxis {};'.format(self.conf.upaxis)) print(f'FBXExport -s -f "{self.conf.exportFile}";') mel.eval(f'FBXExport -s -f "{self.conf.exportFile}";') try: cmds.undo() except RuntimeError as RE: # 没有更多可撤销的命令 pass # 结束FBX导出 return def riz_export(self, use_script=True, load_model=True): if self.link and self.cbx_use_link.isChecked(): print("Rizom链接版本", self.link.Version()) self.exported_objects = cmds.ls(selection=True, tr=True) # FBX导出 self.fbx_export() if not self.port: self.riz_run() params = { "File.Path": self.conf.exportFile, "File.XYZUVW": True, # 加载3D+UV数据(使用File.XYZ仅加载3D数据) "File.UVWProps": True, # 加载UV属性(如固定、纹理密度设置等) "File.ImportGroups": True, # 加载岛组层级 "__Focus": True, # 在视口中聚焦加载的网格 } self.link.Load(params) if DEBUG: print("<RIZOM> 导出至:", self.conf.exportFile) # 日志汉化 cmds.select(self.exported_objects) # 启用导入按钮(如果之前禁用) self.btn_import.setEnabled(True) else: # 传统方法 # print("<RIZOM> 正在导出模型") # 日志汉化 self.cleanse_namespaces() # 强制清理 self.exported_objects = cmds.ls(selection=True, tr=True) if not self.exported_objects: return False # 删除历史记录(防止存在空组被此操作移除) # 否则导入时会被清除,导致对象计数不匹配 cmds.bakePartialHistory() cmd = '' # 导出选项 if load_model: if self.cbx_keepuv.isChecked(): cmd += 'ZomLoad({File={Path="'+self.conf.exportFile+'", ImportGroups=true, XYZUVW=true, UVWProps=true}})\n' else: cmd += 'ZomLoad({File={Path="'+self.conf.exportFile+'", ImportGroups=true, XYZ=true}, NormalizeUVW=true})\n' # 添加脚本 if self.combo_scripts.currentIndex() and use_script is True: script_name = scriptlist.scripts[self.combo_scripts.currentIndex()-1][0] script_path = os.path.join(os.path.dirname(__file__), 'lua_scripts/%s' % script_name) with open(script_path, 'r') as lua_script: cmd += lua_script.read() if DEBUG: print("<RizomUV桥接工具>", cmd) # 日志汉化 # FBX导出 self.fbx_export() if DEBUG: print("<RIZOM> 导出至:", self.conf.exportFile) # 日志汉化 cmds.select(self.exported_objects) self.write_to_lua_file(cmd) self.btn_import.setEnabled(True) # 如果有显著更改,将配置写入磁盘 if self.config_updated == True: self.conf.save_xml() return True def riz_import(self): if not os.path.exists(self.conf.exportFile): om.MGlobal.displayError(f"无法找到导出文件: {self.conf.exportFile}") # 错误提示汉化 self.btn_import.setEnabled(False) if self.cbx_use_link.isChecked(): if self.link: try: self.link.Save({"File.Path": self.conf.exportFile}) except RuntimeError as RE: cmds.error('无法通过Python链接向Rizom发送保存命令。导出时是否启用了链接?') # 错误提示汉化 # FBX导入 namespace = ':RIZOMUV' if not cmds.namespace(ex=namespace): cmds.namespace(add=namespace) cmds.namespace(set=namespace) mel.eval('FBXImportMode -v add;') mel.eval(f'FBXImport -f "{self.conf.exportFile}";') # 结束FBX导入 imported_objects = cmds.ls('RIZOMUV:*', long=True, type="transform") original_matches = [] for riz_obj in imported_objects: print("导入的对象名称", riz_obj) # 日志汉化 original = riz_obj.replace('RIZOMUV:', '') original_matches.append(original) # 列出每个项目的UV集,无UV集则跳过(排除组节点等对象) original_uvsets = cmds.polyUVSet(original, allUVSets=True, q=True) imported_uvsets = cmds.polyUVSet(riz_obj, allUVSets=True, q=True) if original_uvsets: # 检查名称 # if self.cbx_fix_set_names.isChecked(): for i in range(len(original_uvsets)): try: if not original_uvsets[i] == imported_uvsets[i]: cmds.polyUVSet(riz_obj, rename=True, uvSet=imported_uvsets[i], newUVSet=original_uvsets[i]) except IndexError: # 可能因Maya奇怪的bug导致(polyUVSet命令列出的UV集数量与UV集编辑器中不同) print("UV集索引错误。对象的UV集数量似乎不匹配") # 日志汉化 print("原始UV集:", original_uvsets, original) print("导入的UV集:", imported_uvsets, riz_obj) pass try: cmds.polyTransfer(original, ao=riz_obj, ch=False, uv=True) except RuntimeError as rt: print(f"<RizomUV桥接工具> 无法从{riz_obj}向{original}传输UV") # 日志汉化 if DEBUG: print(f"<RizomUV桥接工具> 从{riz_obj}向{original}传输UV") # 日志汉化 cmds.select(original_matches) cmds.bakePartialHistory() cmds.delete(':RIZOMUV:*') cmds.namespace(rm=':RIZOMUV') return def browse_settings_location(self): os.startfile(os.path.dirname(self.conf.config_file_path)) def ui_pack_update_labels(self): print("值已更改") # 日志汉化 self.label_uvmap.setText(str(self.slider_pack_uvmap.value())) def ui_update_uvchannels(self): sel_obj = cmds.ls(sl=True, tr=True) if not sel_obj: self.combo_pack_uvset.clear() return uvsets = cmds.polyUVSet(sel_obj[0], allUVSets=True, q=True) current_set = cmds.polyUVSet(sel_obj[0], cuv=True, q=True) if uvsets: print(uvsets) self.combo_pack_uvset.clear() self.combo_pack_uvset.addItems(uvsets) self.combo_pack_uvset.setCurrentIndex(uvsets.index(current_set[0])) def cleanse_namespaces(self): """ 第一步 -- 尝试删除所有现有RIZOMUV命名空间直到失败,这应该能清除像 RIZOMUV:RIZOMUV:RIZOMUV这样的嵌套实例 """ fail = False while(not fail): try: cmds.namespace(rm=':RIZOMUV', mnr=True) except: fail = True """ 第二步 -- 在某些场景中,命名空间可能被重命名为RIZOMUV1、RIZOMUV2、RIZOMUV3等 因此需要查找并删除这些残留 """ """ 第二步(更新)-- 尝试删除除RIZOM之外的其他命名空间,因为存在其他命名空间可能导致导入失败 """ c = cmds.listRelatives(ad=True) if not c: return for obj in c: ns_split = obj.split(':') if len(ns_split)>1: result = cmds.confirmDialog( m="选中的对象已分配命名空间。\n" # 对话框文本汉化 "使用工具前必须移除这些命名空间\n" "是否为您删除?(包括未选中的对象)\n\n" "对象上的命名空间:\n%s" % ns_split[0], button=['移除', '取消'] # 按钮文本汉化 ) if result == '移除': cmds.namespace(rm=ns_split[0], mnr=True) else: return return def write_to_lua_file(self, command): with open(self.conf.rizom_script_path, 'w') as f: f.write(command) print("<RIZOM> 已将命令写入lua文件:", self.conf.rizom_script_path) # 日志汉化 for line in command.split("\n"): print("\t", line) return def set_config(self): self.conf.loaduvs = self.cbx_keepuv.isChecked() if self.radioAxisY.isChecked(): self.conf.upaxis = "Y" else: self.conf.upaxis = "Z" self.conf.mutations = self.dspin_pack_mutations.value() self.conf.resolution = self.dspin_pack_resolution.value() self.conf.margin = self.dspin_pack_margin.value() self.conf.spacing = self.dspin_pack_spacing.value() self.conf.autofit = self.cbx_layout_scaling.isChecked() self.conf.fixuvnames = self.cbx_fix_set_names.isChecked() self.conf.useuvlink = self.cbx_use_link.isChecked() self.config_updated = True self.conf.save_xml() def closeEvent(self, event): self.conf.save_xml() def GetMayaWidget(): """ 返回Maya主窗口部件的Python对象 """ # 注释汉化 main_window_ptr = omui.MQtUtil.mainWindow() if sys.version_info.major >= 3: return wrapInstance(int(main_window_ptr), QtWidgets.QWidget) else: return wrapInstance(long(main_window_ptr), QtWidgets.QWidget) def fix_shell_border_normals(): obj_list = cmds.ls(sl=True, o=True) all_final_borders = [] for sub_obj in obj_list: cmds.select(sub_obj, r=True) cmds.polyNormalPerVertex(ufn=True) cmds.polySoftEdge(sub_obj, a=180, ch=1) print("全部软化") # 日志汉化 # 选择对象UV cmds.select(sub_obj + '.map[*]') mel.eval('polySelectBorderShell 1;') uv_border = cmds.polyListComponentConversion(te=True, internal=True) uv_border = cmds.ls(uv_border, fl=True) final_border = [] # 特殊过滤 for curEdge in uv_border: edge_uvs = cmds.polyListComponentConversion(curEdge, tuv=True) edge_uvs = cmds.ls(edge_uvs, fl=True) if len(edge_uvs) > 2: final_border.append(curEdge) cmds.polySoftEdge(final_border, a=0, ch=1) all_final_borders.append(final_border) cmds.select(cl=True) for sel_l in all_final_borders: cmds.select(sel_l, add=True) cmds.hilite(obj_list) def run(): scriptJobs = cmds.scriptJob(listJobs=True) for sj in scriptJobs: if "RizomBridge" in sj: print(PRNT_STRING, f"终止已存在的scriptJob: {sj}") # 日志汉化 cmds.scriptJob(kill=int(sj.split(':')[0])) d = RizomUVBridgeWindow() d.show(dockable=True) if __name__ == "__main__": run()
11-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值