def addAttribsToAssetLib(self): # TODO: append hair attribs to cache file (assetName, ok) = QtGui.QInputDialog.getText(self, "input asset Name", "Asset Name:", inputMethodHints="untiltled") if not ok: return if not assetName: pmcore.displayWarning("Pleate enter a name") return attribDict = self.getAttribsDictFromSelectedHairNode() if self.assetDict.has_key(assetName): ok = QtGui.QMessageBox.question(self, "Replace Asset?", "Replace Asset?", \ QtGui.QMessageBox.Yes, \ QtGui.QMessageBox.No) if ok == QtGui.QMessageBox.Yes: print(ok, type(ok), QtGui.QMessageBox.Yes) self.assetDict[assetName] = attribDict self.writeCacheFile() else: return else: self.assetDict[assetName] = attribDict # print(assetName) self.writeCacheFile() self.refreshList() pass
def prepareEnv(): log.debug("prepareEnv") if os.environ.has_key("MTM_ENVDONE"): if os.environ['MTM_ENVDONE'] == "TRUE": log.debug("Env already initialized, skipping.") return True if not os.environ.has_key('H'): if pm.about(batch=True): log.error("Environment variable 'H' not set. Cannot find houdini. Exiting.") else: pm.displayWarning("Environment variable 'H' not set. Cannot find houdini. Exiting.") return False if not os.environ.has_key("MTM_HOME"): if pm.about(batch=True): log.error("Environment variable 'MTM_HOME' not set. Cannot find installdir. Exiting.") else: pm.displayWarning("Environment variable 'MTM_HOME' not set. Cannot find installdir. Exiting.") return False tmpdir = "" if not os.environ.has_key('TMP'): if not os.environ.has_key('tmp'): # TODO: correct tmpdir pass else: tmpdir = os.environ['tmp'] else: tmpdir = os.environ['TMP'] basePath = os.environ['H'] os.environ['HTB'] = basePath + "/toolkit/bin" username = getpass.getuser() currentDir = pm.workspace.path sn = realSceneName() os.environ['HB'] = basePath + "/bin" os.environ['HD'] = basePath + "/demo" os.environ['HFS'] = basePath os.environ['HH'] = basePath + "/houdini" os.environ['HHC'] = basePath + "/houdini/config" os.environ['HIP'] = currentDir + "/mantra/" + sn os.environ['HIPNAME'] = "untitled.hip" os.environ['HOUDINI_TEMP_DIR'] = tmpdir + "/houdini" os.environ['HSITE'] = basePath + "/site" os.environ['HT'] = basePath + "/toolkit" os.environ['HTB'] = basePath + "/toolkit/bin" #os.environ['HOUDINI_OTL_PATH'] = os.environ['HOUDINI_OTL_PATH'] + ";" + currentDir + "/mantra/" + sn + "/shaders" os.environ['HOUDINI_VEX_PATH'] = currentDir + "/mantra/" + sn + "/shaders" + ";&;" path = os.environ['PATH'] if not (basePath + "/bin") in path: os.environ['PATH'] = basePath + "/bin;" + path os.environ['MTM_ENVDONE'] = "TRUE" log.debug("prepareEnv done") return True
def populate_componentControls(self): """Populate Controls Populate the controls values from the custom attributes of the component. """ # populate tab self.tabs.insertTab(1, self.settingsTab, "Component Settings") # populate component settings self.populateCheck(self.settingsTab.joint_checkBox, "joint") self.populateCheck(self.settingsTab.uniScale_checkBox, "uniScale") self.populateCheck(self.settingsTab.neutralRotation_checkBox, "neutralRotation") self.populateCheck(self.settingsTab.mirrorBehaviour_checkBox, "mirrorBehaviour") self.settingsTab.ctlSize_doubleSpinBox.setValue( self.root.attr("ctlSize").get()) sideIndex = self.iconsList.index(self.root.attr("icon").get()) self.settingsTab.controlShape_comboBox.setCurrentIndex(sideIndex) self.populateCheck(self.settingsTab.tx_checkBox, "k_tx") self.populateCheck(self.settingsTab.ty_checkBox, "k_ty") self.populateCheck(self.settingsTab.tz_checkBox, "k_tz") self.populateCheck(self.settingsTab.rx_checkBox, "k_rx") self.populateCheck(self.settingsTab.ry_checkBox, "k_ry") self.populateCheck(self.settingsTab.rz_checkBox, "k_rz") self.populateCheck(self.settingsTab.ro_checkBox, "k_ro") self.populateCheck(self.settingsTab.sx_checkBox, "k_sx") self.populateCheck(self.settingsTab.sy_checkBox, "k_sy") self.populateCheck(self.settingsTab.sz_checkBox, "k_sz") self.settingsTab.ro_comboBox.setCurrentIndex( self.root.attr("default_rotorder").get()) ikRefArrayItems = self.root.attr("ikrefarray").get().split(",") for item in ikRefArrayItems: self.settingsTab.ikRefArray_listWidget.addItem(item) # populate connections in main settings for cnx in Guide.connectors: self.mainSettingsTab.connector_comboBox.addItem(cnx) cBox = self.mainSettingsTab.connector_comboBox self.connector_items = [cBox.itemText(i) for i in range(cBox.count())] currentConnector = self.root.attr("connector").get() if currentConnector not in self.connector_items: self.mainSettingsTab.connector_comboBox.addItem(currentConnector) self.connector_items.append(currentConnector) pm.displayWarning("The current connector: %s, is not a valid " "connector for this component. " "Build will Fail!!") comboIndex = self.connector_items.index(currentConnector) self.mainSettingsTab.connector_comboBox.setCurrentIndex(comboIndex)
def populate_componentControls(self): """Populate Controls Populate the controls values from the custom attributes of the component. """ # populate tab self.tabs.insertTab(1, self.settingsTab, "Component Settings") # populate component settings self.settingsTab.ikfk_slider.setValue( int(self.root.attr("blend").get() * 100)) self.settingsTab.ikfk_spinBox.setValue( int(self.root.attr("blend").get() * 100)) self.settingsTab.maxStretch_spinBox.setValue( self.root.attr("maxstretch").get()) self.populateCheck(self.settingsTab.ikTR_checkBox, "ikTR") self.populateCheck(self.settingsTab.supportJoints_checkBox, "supportJoints") self.populateCheck(self.settingsTab.mirrorMid_checkBox, "mirrorMid") self.populateCheck(self.settingsTab.mirrorIK_checkBox, "mirrorIK") self.populateCheck(self.settingsTab.extraTweak_checkBox, "extraTweak") self.settingsTab.div0_spinBox.setValue(self.root.attr("div0").get()) self.settingsTab.div1_spinBox.setValue(self.root.attr("div1").get()) ikRefArrayItems = self.root.attr("ikrefarray").get().split(",") for item in ikRefArrayItems: self.settingsTab.ikRefArray_listWidget.addItem(item) upvRefArrayItems = self.root.attr("upvrefarray").get().split(",") for item in upvRefArrayItems: self.settingsTab.upvRefArray_listWidget.addItem(item) pinRefArrayItems = self.root.attr("pinrefarray").get().split(",") for item in pinRefArrayItems: self.settingsTab.pinRefArray_listWidget.addItem(item) # populate connections in main settings self.c_box = self.mainSettingsTab.connector_comboBox for cnx in Guide.connectors: self.c_box.addItem(cnx) self.connector_items = [ self.c_box.itemText(i) for i in range(self.c_box.count()) ] currentConnector = self.root.attr("connector").get() if currentConnector not in self.connector_items: self.c_box.addItem(currentConnector) self.connector_items.append(currentConnector) pm.displayWarning( "The current connector: %s, is not a valid connector for this" " component. Build will Fail!!") comboIndex = self.connector_items.index(currentConnector) self.c_box.setCurrentIndex(comboIndex)
def get_eye_mesh(eyeMesh): if eyeMesh: try: eyeMesh = pm.PyNode(eyeMesh) return eyeMesh except pm.MayaNodeError: pm.displayWarning("The object %s can not be found in the " "scene" % (eyeMesh)) return else: pm.displayWarning("Please set the eye mesh first")
def createRunTimeCommand(name, rCmd, ann=""): """Create run time commands from raw string. This function is used to create the mGear hotkeys. """ if pm.runTimeCommand(name, ex=True): pm.runTimeCommand(name, e=True, delete=True) pm.displayWarning("Old hotkey: " + name + " Deleted") pm.runTimeCommand(name, ann=ann, c=rCmd, cat="mGear") pm.displayInfo("Hotkey: " + name + " created")
def load_btn_cmd(self): curr_item = self.model_list_box.currentItem() if curr_item: # get the item name of the curr selected item_name = curr_item.text() print 'Loading:', item_name model = Model(name=item_name) self.model_lib.load_model(model) else: # nothing is selected, display a warning pmc.displayWarning('Please select a model to load.')
def get_description_from_selection(): if pm.selected(): description = pm.selected()[0].getShape() if description.type() == "xgmSplineDescription": return description else: pm.displayWarning( "{} is not an xgen IGS description".format(description)) else: pm.displayWarning( "Nothing selected. Please select xgen IGS description")
def filter_curve_guides(crvs, xgen_description): # return only the curves that are part of the description guides crv_guides = get_connected_curve_guides(xgen_description) filtered_crvs = [] for crv in crvs: if crv in crv_guides: filtered_crvs.append(crv) else: pm.displayWarning("Object {0} is not crv guide for {1} and will be" " skipped".format(crv.name(), xgen_description)) return filtered_crvs
def save_btn_cmd(self): model_name = self.save_line.text() if model_name: print 'Saving', model_name model = Model(name=model_name) self.model_lib.save_model(model=model) self.save_line.setText('') # refresh the model list since it has been updated... self.refresh_btn_cmd() else: pmc.displayWarning('Please enter model name to save.')
def customStep(self, customSteps=None): if customSteps: for step in customSteps: if not self.stopBuild: if step.startswith("*"): continue self.stopBuild = guide.helperSlots.runStep( step.split("|")[-1][1:], self.customStepDic) else: pm.displayWarning("Build Stopped") break
def save_node_data(self): """Save current node data """ current_node = self.get_current_node() if not current_node: pm.displayWarning("Node data can't be saved." " Please check if node exist") return cmn.set_node_data(current_node, self.get_channel_master_config()) pm.displayInfo("Node: {} data saved".format(current_node))
def setMultiChannel(self): oSel = pm.selected() if oSel: channels = att.getSelectedChannels(True) if not channels: channels = att.getSelectedObjectChannels(oSel[0], True, True) for ch in channels: self._addNewRow(ch, oSel[0].name(), oSel[0].name()) else: pm.displayWarning( "To set the source, you need to select at one source object")
def alignToPointsLoop(points=None, loc=None, name=None, *args): """ Create space locator align to the plain define by at less 3 vertex Args: points (None or vertex list, optional): The reference vertex to align the ref locator loc (None or dagNode, optional): If none will create a new locator name (None or string, optional): Name of the new locator *args: Description Returns: TYPE: Description """ if not points: oSel = pm.selected(fl=True) if not oSel or len(oSel) < 3 or str(type(oSel[0])) != "<class 'pymel.core.general.MeshVertex'>": pm.displayWarning("We need to select a points loop, with at less 3 or more points") return else: points = oSel if not loc: if not name: name = "axisCenterRef" loc = pm.spaceLocator(n=name) oLen = len(points) wPos = [0,0,0] for x in points: pos = x.getPosition(space="world") wPos[0] += pos[0] wPos[1] += pos[1] wPos[2] += pos[2] centerPosition = dt.Vector([wPos[0]/oLen, wPos[1]/oLen, wPos[2]/oLen ]) lookat = dt.Vector(points[0].getPosition(space="world")) # NORMAL a = lookat - centerPosition a.normalize() nextV = dt.Vector(points[1].getPosition(space="world")) b = nextV - centerPosition b.normalize() normal = pmu.cross(b, a) normal.normalize() trans = tra.getTransformLookingAt(centerPosition,lookat, normal, axis="xy", negate=False) loc.setTransformation(trans)
def delete_btn_cmd(self): curr_item = self.model_list_box.currentItem() if curr_item: item_name = curr_item.text() print 'Deleting:', item_name model = Model(name=item_name) # TODO: should we also delete the model from the directory? # delete model from library self.model_lib.delete_model(model) self.refresh_btn_cmd() else: pmc.displayWarning('Please select a model to remove.')
def getRigTopNode(node=None): if not node and pm.selected(): node = pm.selected()[0] if not node.hasAttr("is_rig"): pm.displayWarning( "Please select a valid rig top node!. '{}' " "is not a rig top node".format(node.name())) return False return node.name() else: pm.displayWarning("Please select a rig top node!") return False
def populateMeshTopNode(self): """Populate the geometry top node information Returns: bool """ if pm.selected(): node = pm.selected()[0] self.gtUIInst.meshNode_lineEdit.setText(node.name()) else: pm.displayWarning("Please select a Mesh top node!") return False
def __init__(self, parent=None): # constructors of base classes super(BeamUI, self).__init__(parent) self.setObjectName('mainUI') self.setWindowIcon(QtGui.QIcon('')) self.setWindowTitle("Beam Editor") self.setAcceptDrops(True) self.mainVboxLayout = QtGui.QVBoxLayout (self) self.guideLayout = QtGui.QVBoxLayout () self.mainVboxLayout.addLayout(self.guideLayout) self.build_from_selection = QtGui.QPushButton("build_from_selection") self.mainVboxLayout.addWidget(self.build_from_selection) compDir = shifter.getComponentDirectories () path = self.current_path () trackLoadComponent = [] for path, comps in compDir.iteritems (): for comp_name in comps: if comp_name in trackLoadComponent: pm.displayWarning( "Custom component name: %s, already in default " "components. Names should be unique. This component is" " not loaded" % comp_name) continue else: trackLoadComponent.append (comp_name) if not os.path.exists(os.path.join(path, comp_name, "__init__.py")): continue module = shifter.importComponentGuide (comp_name) print "BeamUI.__init__.module",module reload (module) commandbutton = self.loadUiWidget (os.path.join (path.replace("beam_components","widgets"), "commandbutton.ui")) icon = QtGui.QPixmap(os.path.join (path,module.TYPE,"icon.jpg")) self.guideLayout.addWidget (commandbutton) commandbutton.pushButton.setText(module.TYPE) commandbutton.label.setPixmap (icon) QtCore.QObject.connect (commandbutton.pushButton, QtCore.SIGNAL ("clicked()"), partial (self.drawComp, module.TYPE)) self.createConnections()
def skinClusterManager_import_pushButton_cmd(self): items = self.skinClusterManager_two_listWidget.selectedItems() if len(items) == 1: dataPath = items[0].linkPath self.skinClusterManager_progressBar.show() self.machine.importSkinWeight( method='single', weightFilePath=dataPath, QWidget=[self.skinClusterManager_progressBar]) self.skinClusterManager_progressBar.setValue(0) self.skinClusterManager_progressBar.hide() else: pm.displayWarning('must select only one item ! try again...')
def updateHostUI(self, lEdit, targetAttr): oType = pm.nodetypes.Transform oSel = pm.selected() if oSel: if isinstance(oSel[0], oType) and oSel[0].hasAttr("isGearGuide"): lEdit.setText(oSel[0].name()) self.root.attr(targetAttr).set(lEdit.text()) else: pm.displayWarning("The selected element is not a " "valid object or not from a guide") else: pm.displayWarning("Please select first the object.")
def _new_complete(self): if not self.ui_led_01.text(): pmc.displayWarning("Please enter a name for the Sol handle.") return self.return_data = Method.create_handle( name=self.ui_led_01.text(), camera=self.ui_led_02.text(), light=self.ui_led_03.text(), geometry=self.ui_led_04.text() ) self.accept()
def setMultiChannel(self): """sets new rows from the selectec channels. 1 channel for each row""" oSel = pm.selected() if oSel: channels = attribute.getSelectedChannels(True) if not channels: channels = attribute.getSelectedObjectChannels( oSel[0], True, True) for ch in channels: self._addNewRow(ch, oSel[0].name(), oSel[0].name()) else: pm.displayWarning("To set the source, you need to select at " "one source object")
def _getControllerWalkSiblings(node, direction="right", multi=False): """Get the sibling tag of the controller tag Arguments: node (dagNode or list of dagNode): Node with the controller tag direction (str, optional): Direction of the walk. Values "right" and "left" multi (bool, optional): If true, selects all the siblings Returns: TYPE: Description """ if direction == "right": d = 1 else: d = -1 if not isinstance(node, list): node = [node] siblingsTags = [] for n in node: tag = getWalkTag(n) if tag: pTag = tag.parent.connections() if pTag: siblings = cleanOrphaneControllerTags( pTag[0].children.connections()) if multi: siblingsTags = siblingsTags + siblings else: i = siblings.index(tag) if i <= len(siblings) - 2: siblingsTags.append(siblings[i + d]) else: siblingsTags.append(siblings[0]) else: pm.displayWarning("The tag: %s doesn't have parent " "tag" % tag.name()) else: pm.displayWarning("The selected object: %s without Controller tag" " will be skipped" % n.name()) siblingsNode = [] for t in siblingsTags: siblingsNode.append(t.controllerObject.connections()[0]) return siblingsNode
def mirrorPoseOld(flip=False, nodes=False): axis = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] aDic = {"tx":"invTx", "ty":"invTy", "tz":"invTz", "rx":"invRx", "ry":"invRy", "rz":"invRz", "sx":"invSx", "sy":"invSy", "sz":"invSz"} mapDic = {"L":"R", "R":"L"} if not nodes: nodes = pm.selected() pm.undoInfo(ock=1) try: nameSpace = False if nodes: if len(nodes[0].split(":")) == 2: nameSpace = nodes[0].split(":")[0] for oSel in nodes: if nameSpace: nameParts = oSel.name().split(":")[1].split("|")[-1].split("_") else: nameParts = oSel.name().split("|")[-1].split("_") if nameParts[1][0] == "C": if not oSel.attr("tx").isLocked(): oSel.attr("tx").set(oSel.attr("tx").get()*-1) if not oSel.attr("ry").isLocked(): oSel.attr("ry").set(oSel.attr("ry").get()*-1) if not oSel.attr("rz").isLocked(): oSel.attr("rz").set(oSel.attr("rz").get()*-1) else: nameParts[1] = mapDic[nameParts[1][0]] + nameParts[1][1:] if nameSpace: nameTarget = nameSpace+":"+"_".join(nameParts) else: nameTarget = "_".join(nameParts) oTarget = pm.PyNode(nameTarget) for a in axis: if not oSel.attr(a).isLocked(): if oSel.attr(aDic[a]).get(): inv = -1 else: inv = 1 if flip: flipVal = oTarget.attr(a).get() oTarget.attr(a).set(oSel.attr(a).get()*inv) if flip: oSel.attr(a).set(flipVal*inv) except: pm.displayWarning("Flip/Mirror pose fail") pass finally: pm.undoInfo(cck=1)
def finalize(self): """ Finalize the rig. """ groupIdx = 0 # Properties -------------------------------------- mgear.log("Finalize") # Groups ------------------------------------------ mgear.log("Creating groups") # Retrieve group content from components for name in self.componentsIndex: component = self.components[name] for name, objects in component.groups.items(): self.addToGroup(objects, name) #Create master set to group all the groups masterSet = pm.sets(n=self.model.name()+"_sets_grp", em=True) pm.connectAttr(masterSet.message, self.model.rigGroups[groupIdx]) groupIdx += 1 # Creating all groups pm.select(cl=True) for name, objects in self.groups.items(): s = pm.sets(n=self.model.name()+"_"+name+"_grp") s.union( objects) pm.connectAttr(s.message, self.model.rigGroups[groupIdx]) groupIdx += 1 masterSet.add(s) # Bind pose --------------------------------------- print self.groups["controllers"] pm.select(self.groups["controllers"]) node = pm.dagPose(save=True, selection=True) pm.connectAttr(node.message, self.model.rigPoses[0]) print node # Bind skin re-apply if self.options["importSkin"]: try: pm.displayInfo("Importing Skin") skin.importSkin(self.options["skin"]) except: pm.displayWarning("Skin doesn't exist or is not correct. "+self.options["skin"]+" Skipped!")
def setRow(self): """Sets a new row Sets a new row with the information on the channel and target lineEdit """ fullChanName = self.cwUIInst.channel_lineEdit.text() if fullChanName: sourceName, chanName = fullChanName.split(".") targetName = self.cwUIInst.target_lineEdit.text() if fullChanName and targetName: # TODO: checker for the new rule, be sure is not duplicated self._addNewRow(chanName, sourceName, targetName) else: pm.displayWarning("Channel and target are not set properly")
def _populate_object(self, lEdit, oType=True): if oType: testInstance = pm.nodetypes.Transform else: testInstance = pm.nodetypes.ObjectSet oSel = pm.selected() if oSel: if isinstance(oSel[0], testInstance): lEdit.setText(oSel[0].name()) else: pm.displayWarning("The selected element is not a valid object") else: pm.displayWarning("Please select first the element to add.")
def disconnectExport(self): name = self.gtUIInst.assetName_lineEdit.text() rigTopNode = self.gtUIInst.rigNode_lineEdit.text() meshTopNode = self.gtUIInst.meshNode_lineEdit.text() path = self.gtUIInst.path_lineEdit.text() postScript = self.gtUIInst.script_lineEdit.text() if name and rigTopNode and meshTopNode and path: exportAssetAssembly( name, rigTopNode, meshTopNode, path, postScript) else: pm.displayWarning( "Name, Rig Top Node, Mesh Top Node and path " "are mandatory fields. Please check it.")
def delete_tab(self): """Delete the current tab """ cur_idx = self.tab_widget.currentIndex() if cur_idx >= 1: button_pressed = QtWidgets.QMessageBox.question( self, "Delete Tab", "Confirm Delete Tab?") if button_pressed == QtWidgets.QMessageBox.Yes: page = self.tab_widget.widget(cur_idx) self.tab_widget.removeTab(cur_idx) page.deleteLater() # self.save_node_data() else: pm.displayWarning("Main Tab Can't be deleted!")
def bakeAnimation(self, switch_attr_name, val_src_nodes, key_src_nodes, key_dst_nodes, startFrame, endFrame, onlyKeyframes=True): # type: (str, List[pm.nodetypes.Transform], # List[pm.nodetypes.Transform], # List[pm.nodetypes.Transform], int, int, bool) -> None # Temporaly turn off cycle check to avoid misleading cycle message # on Maya 2016. With Maya 2016.5 and 2017 the cycle warning doesn't # show up if versions.current() < 201650: pm.cycleCheck(e=False) pm.displayWarning("Maya version older than: 2016.5: " "CycleCheck temporal turn OFF") channels = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] worldMatrixList = self.getWorldMatrices(startFrame, endFrame, val_src_nodes) keyframeList = sorted( set(pm.keyframe(key_src_nodes, at=["t", "r", "s"], q=True))) # delete animation in the space switch channel and destination ctrls pm.cutKey(key_dst_nodes, at=channels, time=(startFrame, endFrame)) pm.cutKey(switch_attr_name, time=(startFrame, endFrame)) for i, x in enumerate(range(startFrame, endFrame + 1)): if onlyKeyframes and x not in keyframeList: continue pm.currentTime(x) # set the new space in the channel self.changeAttrToBoundValue() # bake the stored transforms to the cotrols for j, n in enumerate(key_dst_nodes): n.setMatrix(worldMatrixList[i][j], worldSpace=True) pm.setKeyframe(key_dst_nodes, at=channels) if versions.current() < 201650: pm.cycleCheck(e=True) pm.displayWarning("CycleCheck turned back ON")
def populate_object(self, lEdit, oType=None): if oType == 1: oType = pm.nodetypes.Joint else: oType = pm.nodetypes.Transform oSel = pm.selected() if oSel: if isinstance(oSel[0], oType): lEdit.setText(oSel[0].name()) else: pm.displayWarning("The selected element is not a valid object") else: pm.displayWarning("Please select first the object.")
def skinClusterManager_batchImport_pushButton_cmd(self): items = self.skinClusterManager_two_listWidget.selectedItems() if len(items) != 0: self.skinClusterManager_progressBar.show() for item in items: dataPath = item.linkPath self.machine.importSkinWeight( method='batch', weightFilePath=dataPath, QWidget=[self.skinClusterManager_progressBar]) self.skinClusterManager_progressBar.setValue(0) self.skinClusterManager_progressBar.hide() else: pm.displayWarning('must select item ! try again...')
def addSupportJoint(oSel=None, select=True, *args): """Add an extra joint to the blended joint. This is meant to be use with SDK for game style deformation. Args: oSel (None or blended joint, optional): If None will use the current selection. *args: Mays's dummy Returns: list: blended joints list """ if not oSel: oSel = pm.selected() elif not isinstance(oSel, list): oSel = [oSel] jnt_list = [] for x in oSel: if x.name().split("_")[0] == "blend": children = [ item for item in pm.selected()[0].listRelatives(ad=True, type="joint") ] i = len(children) name = x.name().replace("blend", "blendSupport_%s" % str(i)) jnt = pm.createNode('joint', n=name, p=x) jnt_list.append(jnt) jnt.attr('radius').set(1.5) jnt.attr("overrideEnabled").set(1) jnt.attr("overrideColor").set(17) try: defSet = pm.PyNode("rig_deformers_grp") except pm.MayaNodeError: pm.sets(n="rig_deformers_grp") defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=jnt) else: pm.displayWarning("Support Joint can't be added to: %s. Because " "is not blend joint" % x.name()) if jnt_list and select: pm.select(jnt_list) return jnt_list
def arMayaMenuUnique01(): arMenu = pm.menu('arUtilsMenu', p = 'MayaWindow', l = 'arUtils',to = 1) pm.menuItem(p = arMenu, l = 'Options', c = 'import arutils.ui.generalUI;arOptions = arutils.ui.generalUI.Options();AR_MAIN["Options"] = arOptions;arOptions.show()') pm.menuItem(d = True) pm.menuItem(p = arMenu, l = 'Online Documentation', c = 'import arutils.doc.openDoc;arutils.doc.openDoc.openOnlineDoc()') pm.menuItem(d = True) pm.menuItem(p = arMenu, l = 'Viewport Render', c = 'import arutils.ui.generalUI;arViewportRender = arutils.ui.generalUI.drawViewportRenderRegion();AR_MAIN["ViewportRender"] = arViewportRender') pm.menuItem(p = arMenu, l = 'Texture Switch', c = 'import arutils.ui.generalUI;' 'arTextureSwitch = arutils.ui.generalUI.TextureSwitchUI();' 'AR_MAIN["TextureSwitch"] = arTextureSwitch;\ntry:arTextureSwitch.close();\nexcept:pass;\narTextureSwitch.dockUI(init = True);') pm.menuItem(p = arMenu, l = 'Material ID Manager', c = 'import arutils.ui.generalUI;arMaterialIdManager = arutils.ui.generalUI.MaterialIdManager().showUi();AR_MAIN["MaterialIdManager"] = arMaterialIdManager') pm.menuItem(p = arMenu, l = 'Light/Geo Control', c = 'import arutils.ui.generalUI;arLightGeoControl = arutils.ui.generalUI.LightGeoControl();AR_MAIN["LightGeoControl"] = arLightGeoControl;arLightGeoControl.showUi()') """ assetsMenu = pm.menuItem(p = arMenu, l = 'Assets', to = True, sm = True) pm.menuItem(p = assetsMenu, l = 'Asset Libary', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);arutils.ui.generalUI.AssetLibrary().showUi()') pm.menuItem(p = assetsMenu, l = 'Asset Publish', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);arutils.ui.generalUI.AssetPublish().showUi()') pm.menuItem(p = assetsMenu, l = 'Asset Manager', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);arutils.ui.generalUI.AssetManager().showUi()') """ toolMenu = pm.menuItem(p = arMenu, l = 'Utilities', to = True, sm = True) """ pm.menuItem(p = toolMenu, l = 'Consolidate Scene Textures', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);' 'arConsolidateSceneTextures = arutils.ui.generalUI.ConsolidateTextures();' 'AR_MAIN["ConsolidateTextures"] = arConsolidateSceneTextures;arConsolidateSceneTextures.showUi()') """ pm.menuItem(p = toolMenu, l = 'Dock Output Window', c = 'import arutils.ui.generalUI;arutils.ui.generalUI.dockableOutputWindow()') pm.menuItem(p = toolMenu, l = 'Search UI Elements', c = 'import arutils.ui.generalUI;arutils.ui.generalUI.SearchUI().create()') """ pm.menuItem(p = toolMenu, l = 'Dock Script Editor', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);arutils.ui.generalUI.openCustomScriptEditor()') pm.menuItem(p = toolMenu, l = 'Light Control', c = 'import arutils.ui.generalUI;reload(arutils.ui.generalUI);arutils.ui.generalUI.LightControl().create(winValue = True)') """ pm.menuItem(p = toolMenu, l = 'FPS Drop Down', c = 'import arutils.ui.generalUI;arutils.ui.generalUI.fpsDropDown()') pm.menuItem(p = arMenu, d = True) pm.menuItem(p = arMenu, l = 'About', c = pm.Callback(about)) ''' ChannelBox CopyPaste Menu items ''' mel.eval('generateChannelMenu "popupMenu1" 1;') pm.menuItem('realCopy', l = 'Copy', p = 'popupMenu1', ia = 'cutItem', bld = True, c = 'x = arutils.src.arUtilitiesMaya.Attributes(); pm.Callback(x.copyCmd())') pm.menuItem('realPaste', l = 'Paste', p = 'popupMenu1', ia = 'copyItem', bld = True, c = 'pm.Callback(x.pasteCmd())') ''' Outliner Set Menu Item''' try: Scenes = arutils.src.arUtilitiesMaya.Scenes() setMenu = pm.menuItem('customSetMenu', l = 'Sets', bld = True, sm = True, p = 'outlinerPanel1Popup') pm.menuItem('setMenuItemA', l = 'Add Selection to Set', c = pm.Callback(Scenes.addRemoveSetMembers,'add'), p = setMenu) pm.menuItem('setMenuItemB', l = 'Remove Members from Set', c = pm.Callback(Scenes.addRemoveSetMembers,'remove'), p = setMenu) except: pm.displayWarning('[arutils]: Could not create outliner menu')
def saveScene(**kwargs): sSceneType = "" sCurScnPath = pm.sceneName() if not sCurScnPath: sCurScnPath = "untitled" sSceneName = "untitled scene" sSceneTypeList = ['mayaAscii', 'mayaBinary'] else: sSceneName = sCurScnPath sExt = osp.splitext(sCurScnPath)[1].lower() sSceneTypeList = [] if sExt: if sExt == ".ma": sSceneTypeList = ['mayaAscii'] elif sExt == ".mb": sSceneTypeList = ['mayaBinary'] if not sSceneTypeList: raise ValueError("Invalid maya scene extension: '{}'".format(sExt)) #sSceneTypeList = mc.file(q=True, type=True) if len(sSceneTypeList) > 1: raise RuntimeError, 'Saving "{0}" : More than one type matches this file : {1}'\ .format(sCurScnPath, sSceneTypeList) else: sSceneType = sSceneTypeList[0] sWantedSceneType = kwargs.get('fileType', kwargs.get('ft', '')) if sWantedSceneType and (sWantedSceneType != sSceneType): if sWantedSceneType not in ('mayaAscii', 'mayaBinary'): raise ValueError('Invalid file type: "{0}"'.format(sWantedSceneType)) sSceneType = sWantedSceneType else: if not mc.file(q=True, modified=True): pm.displayWarning("Current scene has NO changes to save: '{}'.".format(sSceneName)) return sCurScnPath bPrompt = kwargs.get("prompt", True) if bPrompt: if kwargs.get("discard", True): buttonList = ("Save", "Don't Save", "Cancel") sDismiss = "Don't Save" sConfirmEnd = "?" else: buttonList = ("Save", "Cancel") sDismiss = "Cancel" sConfirmEnd = "!" sMsg = 'Save changes to :\n\n{0} {1}'.format(sSceneName, sConfirmEnd) sConfirm = pm.confirmDialog(title="DO YOU WANT TO...", message=sMsg, button=buttonList, defaultButton="Cancel", cancelButton="Cancel", dismissString=sDismiss, icon="question", ) else: sConfirm = "Save" if sConfirm == "Cancel": logMsg("Cancelled !" , warning=True) return "" elif sConfirm == "Don't Save": return sCurScnPath elif sConfirm == "Save": bNoFileCheck = kwargs.pop("noFileCheck", True) if (not sCurScnPath) or sCurScnPath == "untitled": sFileList = chooseMayaScene(ff=sSceneTypeList) if not sFileList: return "" if bNoFileCheck: pmu.putEnv("DAVOS_FILE_CHECK", "") return pm.saveAs(sFileList[0], force=True) else: if bNoFileCheck: pmu.putEnv("DAVOS_FILE_CHECK", "") if kwargs.get("checkError", True): try: assertCurrentSceneReadWithoutDataLoss() except AssertionError: return "" if sSceneType: return pm.saveFile(force=True, type=sSceneType) else: return pm.saveFile(force=True)
bFail = kwargs.pop("fail", True) res = None try: res = pm.openFile(sScenePath, **kwargs) except RuntimeError, e: if bFail: raise else: pm.displayError(toStr(e.message)) if bAddToRecent and (not mc.about(batch=True)): try: pm.mel.addRecentFile(sScenePath, mc.file(sScenePath, q=True, type=True)[0]) except Exception as e: pm.displayWarning(toStr(e.message)) return sScenePath if res is None else res _toBool = lambda x: int(bool(int(x))) ATOM_EXPORT_OPTS = OrderedDict(( ("animExportSDK", _toBool), ("animExportConstraints", _toBool), ("animExportAnimLayers", _toBool), ("animExportStatics", _toBool), ("animExportBaked", _toBool), ("animExportPoints", _toBool), ("animExportHierarchy", {"selected":1, "below":2}), ("animExportChannels", {"all_keyable":1, "from_channel_box":2}), ("animExportTimeRange", {"all":1, "time_slider":2, "single_frame":3, "start_end":4}),
def bakeDiffuseToVertexColor(**kwargs): bOnRefs = kwargs.pop("onReferences", kwargs.pop("onRefs", False)) fAmbient = kwargs.pop("ambient", 1.0) sCamShape = "" if mc.about(batch=True): sCamShape = kwargs["camera"] if "meshes" not in kwargs: sMeshList = lsNodes(sl=True, dag=True, ni=True, type="mesh", not_referencedNodes=not bOnRefs, nodeNames=True) if not sMeshList: logMsg("No meshes found in selection !" , warning=True) return False else: sMeshList = kwargs.pop("meshes") if not sMeshList: return False mc.polyOptions(sMeshList, colorShadedDisplay=False) sLightList = tuple(sLight for sLight in mc.ls(type=mc.listNodeTypes('light')) if myapi.getDagPath(sLight).isVisible()) for sLight in sLightList: try: mc.setAttr(sLight + ".visibility", False) except RuntimeError as e: pm.displayWarning(e) ambLight = pm.shadingNode("ambientLight", asLight=True) ambLight.setAttr("intensity", fAmbient) ambLight.setAmbientShade(0.0) ambLight.setAttr("color", (1.0, 1.0, 1.0)) ambLight.setAttr("shadowColor", (0.0, 0.0, 0.0)) ambLight.setAttr("useRayTraceShadows", False) pm.refresh() ##Storing if exist, reflectivity connection or value before applying the bakeTexture, ##as it could affects the "rendering/baking" aspect of the object. ##After bake, reapply the value. oReflDct = {} for oMat in lsNodes(type=mc.listNodeTypes('shader', ex="texture"), not_referencedNodes=not bOnRefs): if oMat.hasAttr("reflectivity"): oReflAttr = oMat.attr("reflectivity") oInputs = oReflAttr.inputs(sourceFirst=True, c=True, plugs=True) if oInputs: oReflDct[oMat] = dict(oInputs) pm.disconnectAttr(*oInputs) else: try: value = oReflAttr.get() except RuntimeError as e: pm.displayInfo(u"{}: {}".format(e.message.strip(), oReflAttr)) continue oReflDct[oMat] = value oReflAttr.set(0.0) if sCamShape: sMeshList.append(sCamShape) try: mc.polyGeoSampler(sMeshList, ignoreDoubleSided=True, scaleFactor=1.0, shareUV=True, colorDisplayOption=True, colorBlend="overwrite", alphaBlend="overwrite", flatShading=False, lightingOnly=False, averageColor=True, clampAlphaMin=1.0, clampAlphaMax=1.0) mc.polyOptions(sMeshList, colorMaterialChannel="ambientDiffuse") finally: for sLight in sLightList: try: mc.setAttr(sLight + ".visibility", True) except RuntimeError as e: pm.displayWarning(e) for oMat, oValues in oReflDct.items(): if isinstance(oValues, dict): for k, v in oValues.items(): pm.connectAttr(k, v) else: oMat.setAttr("reflectivity", oValues) if ambLight: pm.delete(ambLight) return True