def run(self): selection_state_text = 'all joints' confirm_result = 'Yes' if self.options.selection_only: nodes = pm.selected() selection_state_text = 'selected joints' else: confirm_result = pm.confirmDialog( title='Confirm', message='This will replace the entire {}, Are you sure?'.format(self.POSE_NAME), button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) nodes = pm.ls('%s_*' % crab.config.SKELETON, type='joint', r=True) nodes.extend(pm.ls('%s_*' % crab.config.GUIDE, type='transform', r=True)) if confirm_result == 'Yes': with crab.utils.contexts.UndoChunk(): for joint in nodes: if not joint.hasAttr(self.POSE_NAME): joint.addAttr(self.POSE_NAME, at='matrix') joint.attr(self.POSE_NAME).set(joint.getMatrix()) pm.displayInfo('Updated: {} on {}'.format(self.POSE_NAME, selection_state_text)) else: pm.displayInfo('Action Cancelled: {}'.format(self.POSE_NAME))
def name_rule_validator(rule, valid_tokens, log=True): """Validate name rule Args: rule (str): Rule to validadte valid_tokens (list): Valid tokens for the rule log (bool, optional): if True will display warnings Returns: bool: True if the rule is valid """ invalid_tokens = [] for token in string.Formatter().parse(rule): if token[1] and token[1] in valid_tokens: continue # compare to None to avoid errors with empty token elif token[1] is None and token[0]: continue else: invalid_tokens.append(token[1]) if invalid_tokens: if log: pm.displayWarning("{} not valid token".format(invalid_tokens)) pm.displayInfo("Valid tokens are: {}".format(NAMING_RULE_TOKENS)) return else: return True
def bake(self): opmTxt = self.hsysOPM.getValue() isAll = self.alhsCBX.getValue() if isAll: hsList = pm.ls(type='hairSystem') else: hsList = pm.ls(opmTxt, r=True)[0].getShapes() for hs in hsList: if isAll: topList = [self.getTopGroupFromHair(hs)] else: topList = self.getTopJointFromHair(hs, True) if not topList: pm.displayError('The top node not found.') return False else: dagList = pm.ls(topList, dag=True) allMixJntList = pm.ls('*mix*', type='joint', r=True) mixJntList = list(set(dagList) & set(allMixJntList)) if not mixJntList: continue ncls = hs.inputs(type='nucleus')[0] for mixJnt in mixJntList: simJnt = mixJnt.attr('tx').inputs() if simJnt: simJnt = simJnt[0] if simJnt.nodeType() == 'joint': simJnt.attr('radius') >> mixJnt.attr( 'radius') # This is for the unbaking if self.tmrgRBG.getSelect() == 1: min = pm.env.getMinTime() max = pm.env.getMaxTime() else: min = self.stedIFG.getValue1() max = self.stedIFG.getValue2() ncls.attr('enable').set(True) pm.bakeResults(mixJntList, sm=True, t=[min, max], ral=False, mr=True, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) ncls.attr('enable').set(False) pm.displayInfo('Successfully baked.')
def remove_selected_channels(self): """Remove selected channels from the current channel master table """ # check that main tab is not edited cur_idx = self.tab_widget.currentIndex() if cur_idx >= 1: # get table config table = self.get_current_table() config = table.get_table_config() # promp before remove the channel button_pressed = QtWidgets.QMessageBox.question( self, "Remove Channels", "Confirm Remove Selected Channels?") if button_pressed == QtWidgets.QMessageBox.Yes: # get keys to remove for item in table.selectedItems(): fullName = item.data(QtCore.Qt.UserRole)["fullName"] pm.displayInfo("Removed channel: {}".format(fullName)) config["channels"].remove(fullName) config["channels_data"].pop(fullName, None) # update table with new config table.set_table_config(config) # self.save_node_data() else: pm.displayWarning("Main Tab Can't be Edited!")
def hotkeys(): """ Creates hotkeys that make use of piper scripts. """ # make a custom key set since Maya's default is locked. if not pm.hotkeySet(pcfg.hotkey_set_name, exists=True): pm.hotkeySet(pcfg.hotkey_set_name, source='Maya_Default') # set the current hotkey set to be piper's hotkey set pm.hotkeySet(pcfg.hotkey_set_name, current=True, edit=True) # CLEAR EXISTING HOTKEY(s) # if key is being used, clear it so we can assign a new one. if pm.hotkeyCheck(key='c', alt=True): pm.hotkey(k='c', alt=True, n='', rn='') # ASSIGN NEW HOTKEY(s) # create command and assign it to a hotkey python_command = 'python("import piper.mayapy.util as myu; myu.cycleManipulatorSpace()")' command = pm.nameCommand('cycleManipulator', command=python_command, annotation='Cycles Manipulator Space') pm.hotkey(keyShortcut='c', alt=True, name=command) pm.displayInfo('Assigned Piper Hotkeys')
def jointStructure(self): """ Handle the building of the joint structure, when we select jnt_org option. """ #get parent component joint if self.settings["useIndex"]: try: self.active_jnt = self.parent_comp.jointList[self.settings["parentJointIndex"]] except: pm.displayWarning("The parent component for: %s don't have any joint with the index: %s."%(self.fullName, str(self.settings["parentJointIndex"]))) else: parent_name = "none" if self.guide.parentComponent is not None: parent_name = self.guide.parentComponent.getName(self.guide.parentLocalName) relative_name = self.rig.getRelativeName(parent_name) oParent_comp = self.parent_comp while oParent_comp: try: self.active_jnt = oParent_comp.jointList[oParent_comp.jointRelatives[relative_name]] # when we search in the parent component for a active jnt we also store it for later retrive self.parent_relative_jnt = self.active_jnt break except: if oParent_comp.parent_comp: parent_name = oParent_comp.guide.parentComponent.getName(oParent_comp.guide.parentLocalName) relative_name = oParent_comp.rig.getRelativeName(parent_name) else: pm.displayInfo("The parent components for: %s don't have joint List in any of them use the root off guide."%self.fullName) oParent_comp = oParent_comp.parent_comp # Joint creation for jpo in self.jnt_pos: if len(jpo)>=3 and self.options["joint_rig"]: if jpo[2] == "component_jnt_org": newActiveJnt = self.component_jnt_org elif jpo[2] == "parent_relative_jnt": # this option force the active jnt always to the parent relative jnt. # if None the active jnt will be updated to the latest in each jnt creation newActiveJnt = self.parent_relative_jnt else: try: # here jpo[2] is also the string name of the jnt inside the component. IE: "root" newActiveJnt = self.jointList[self.jointRelatives[jpo[2]]] except: if jpo[2]: pm.displayWarning( "Joint Structure creation: The object %s can't be found. Joint parent is NONE for %s, from %s"%(jpo[2], jpo[0], self.fullName)) newActiveJnt = None else: newActiveJnt = None # Handle the uniform scale if len(jpo)==4 and self.options["joint_rig"]: uniScale = jpo[3] else: uniScale = True self.jointList.append(self.addJoint(jpo[0], jpo[1], newActiveJnt, uniScale))
def ui2py(filePath=None, *args): """Convert qtDesigner .ui files to .py""" if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter='PyQt Designer (*%s)' % UI_EXT, okc="Compile to .py") if not filePath: return False filePath = filePath[0] if not filePath: return False if not filePath.endswith(UI_EXT): filePath += UI_EXT compiledFilePath = filePath[:-2] + "py" pyfile = open(compiledFilePath, 'w') compileUi(filePath, pyfile, False, 4, False) pyfile.close() info = "PyQt Designer file compiled to .py in: " pm.displayInfo(info + compiledFilePath)
def spaceJump(ref=None, space=None, *args): """ This function create a local reference space from another space in the hierarchy Args: ref (None, optional): Transform reference space (None, optional): Space reference *args: Maya dummy Returns: pyNode: Transform """ if not ref and not space: if len(pm.selected())==2: ref = pm.selected()[0] space = pm.selected()[1] else: pm.displayWarning("Please select 2 objects. Reference Space and Jump Space") return refLocal = pri.addTransform(ref, ref.name()+"_SPACE_"+space.name(), space.getMatrix(worldSpace=True)) spaceLocal = pri.addTransform(space, ref.name()+"_JUMP_"+space.name(), space.getMatrix(worldSpace=True)) aop.gear_mulmatrix_op(refLocal.attr("worldMatrix"), spaceLocal.attr("parentInverseMatrix[0]"), spaceLocal) pm.displayInfo("Jump Space for local space: " + space.name() + "created") return spaceLocal
def createInterpolateTransform(objects=None, blend=.5, *args): """ Create space locator and apply gear_intmatrix_op, to interpolate the his pose between 2 selected objects. Args: objects (None or list of 2 dagNode, optional): The 2 dagNode to interpolate the transform. blend (float, optional): The interpolation blend factor. *args: Maya's dummy Returns: pyNode: The new transformation witht the interpolate matrix node applied. """ if objects or len(pm.selected()) >= 2: if objects: refA = objects[0] refB = objects[1] else : refA = pm.selected()[0] refB = pm.selected()[1] intMatrix = aop.gear_intmatrix_op(refA.attr("worldMatrix"), refB.attr("worldMatrix"), blend) intTrans = pri.addTransform(refA, refA.name()+"_INTER_"+refB.name(), dt.Matrix()) aop.gear_mulmatrix_op(intMatrix.attr("output"), intTrans.attr("parentInverseMatrix[0]"), intTrans) pm.displayInfo("Interpolated Transform: " + intTrans.name() + " created") else: pm.displayWarning("Please select 2 objects. ") return return intTrans
def assignBindAttributes(joints=None): """ Assigns the bind matrix attribute to the given joints. Args: joints (list): Joints to assign bind matrix attribute to. If None given, will use selected or all joints. """ joints = myu.validateSelect(joints, find='joint') for joint in joints: if not joint.hasAttr(pcfg.length_attribute): joint.addAttr(pcfg.length_attribute, s=True, w=True, r=True, dv=0.001, min=0.001) joint_parent = joint.getParent() if joint_parent and isinstance(joint_parent, pm.nodetypes.Joint): distance_name = joint.name() + '_to_' + joint_parent.name( ) + pcfg.distance_suffix if pm.objExists(distance_name): pm.delete(distance_name) distance = pm.createNode('distanceBetween', n=distance_name) joint.worldMatrix >> distance.inMatrix1 joint_parent.worldMatrix >> distance.inMatrix2 distance.distance >> joint.attr(pcfg.length_attribute) pm.displayInfo('Finished assigning Piper joint attributes to ' + str(len(joints)) + ' joints.')
def doritosMagic(mesh, joint, jointBase, parent=None): # magic of doritos connection skinCluster = skin.getSkinCluster(mesh) if not skinCluster: if pm.objExists('static_jnt') is not True: static_jnt = primitive.addJoint(parent, "static_jnt", m=datatypes.Matrix(), vis=True) static_jnt = pm.PyNode("static_jnt") # apply initial skincluster skinCluster = pm.skinCluster(static_jnt, mesh, tsb=True, nw=2, n='%s_skinCluster' % mesh.name()) try: # we try to add the joint to the skin cluster. Will fail if is already # in the skin cluster pm.skinCluster(skinCluster, e=True, ai=joint, lw=True, wt=0) except Exception: pm.displayInfo("The Joint: %s is already in the %s." % (joint.name(), skinCluster.name())) pass cn = joint.listConnections(p=True, type="skinCluster") for x in cn: if x.type() == "matrix": if x.name().split(".")[0] == skinCluster.name(): # We force to avoid errors in case the joint is already # connected pm.connectAttr(jointBase + ".worldInverseMatrix[0]", skinCluster + ".bindPreMatrix[" + str(x.index()) + "]", f=True)
def export_uv(type, directory, objects): if type in ['selected', 'all']: polygons = get_polygons(type) elif objects: strips = objects.replace(' ', '') polygons = strips.split(',') else: core.displayWarning('wrong arguments or inputs!...') return if not polygons: core.displayWarning('wrong arguments %s!...' % objects) return studio_maya = studioMaya.Connect() uv_data_bundle = {} exported_polygons = [] result = True for index, polygon in enumerate(polygons): exported_polygons.append(polygon) if not core.objExists(polygon): core.displayWarning('not found the object called <%s>!...' % polygon) result = False continue studio_maya.node = polygon mdag_path = studio_maya.getDagPath() data = studio_maya.getData(mdag_path) uv_data_bundle.setdefault(index, data) studio_maya.write(directory, uv_data_bundle, result=False) print '\npolygons\n\t', '\n\t'.join(exported_polygons) if not result: core.displayWarning('export not completed!...') return core.displayInfo('export success!... // Result: %s' % directory)
def mouseReleaseEvent_(self, event): # type: (QtGui.QMouseEvent) -> None if not self.origin: self.origin = event.pos() selected = [] rect = QtCore.QRect(self.origin, event.pos()).normalized() for child in self.findChildren(widgets.SelectButton): # if rect.intersects(child.geometry()): if rect.intersects(self._getButtonAbsoluteGeometry(child)): selected.append(child) if selected: firstLoop = True with pm.UndoChunk(): for wi in selected: wi.rectangleSelection(event, firstLoop) firstLoop = False else: if event.modifiers() == QtCore.Qt.NoModifier: pm.select(cl=True) pm.displayInfo("Clear selection") self.origin = None QtWidgets.QWidget.mouseReleaseEvent(self, event)
def buildFromDict(self, conf_dict): log_window() startTime = datetime.datetime.now() mgear.log("\n" + "= SHIFTER RIG SYSTEM " + "=" * 46) self.stopBuild = False self.guide.set_from_dict(conf_dict) endTime = datetime.datetime.now() finalTime = endTime - startTime mgear.log("\n" + "= SHIFTER FILE READ {} [ {} ] {}".format( "=" * 16, finalTime, "=" * 7)) # Build mgear.log("\n" + "= BUILDING RIG " + "=" * 46) self.from_dict_custom_step(conf_dict, pre=True) self.build() self.from_dict_custom_step(conf_dict, pre=False) endTime = datetime.datetime.now() finalTime = endTime - startTime pm.flushUndo() pm.displayInfo("Undo history have been flushed to avoid " "possible crash after rig is build. \n" "More info: " "https://github.com/miquelcampos/mgear/issues/72") mgear.log("\n" + "= SHIFTER BUILD RIG DONE {} [ {} ] {}".format( "=" * 16, finalTime, "=" * 7))
def exportSkin(filePath=None, objs=None, *args): if not objs: if pm.selected(): objs = pm.selected() else: pm.displayWarning("Please Select One or more objects") return False packDic = {"objs": [], "objDDic": [], "bypassObj": []} if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=0, startingDirectory=startDir, fileFilter='mGear Skin (*%s)' % FILE_EXT) filePath = filePath[0] if not filePath: return False if not filePath.endswith(FILE_EXT): filePath += FILE_EXT # object parsing for obj in objs: skinCls = getSkinCluster(obj) if not skinCls: pm.displayWarning(obj.name() + ": Skipped because don't have Skin Cluster") pass else: dataDic = { 'weights': {}, 'blendWeights': [], 'skinClsName': "", 'objName': "", 'nameSpace': "" } dataDic["objName"] = obj.name() dataDic["nameSpace"] = obj.namespace() collectData(skinCls, dataDic) packDic["objs"].append(obj.name()) packDic["objDDic"].append(dataDic) pm.displayInfo("Exported skinCluster %s (%d influences, %d " "points) %s" % (skinCls.name(), len(dataDic['weights'].keys()), len(dataDic['blendWeights']), obj.name())) if packDic["objs"]: fh = open(filePath, 'wb') pickle.dump(packDic, fh, pickle.HIGHEST_PROTOCOL) fh.close() return True
def print_select_yuansu(self): items = self.list_widgets.selectedItems() select_labels = [] for item in items: select_labels.append(item.text()) pm.displayInfo(u'é€‰æ‹©çš„å…ƒç´ ä¸ºï¼š{}'.format(' '.join([select_label for select_label in select_labels])))
def emit(self, record): msg = self.format(record) if record.levelname in ["DEBUG", "INFO"]: pm.displayInfo(msg) elif record.levelname == "WARNING": pm.displayWarning(msg) elif record.levelname in ["ERROR", "CRITICAL"]: pm.displayError(msg)
def createAssetAssembly(filePath=None, reference=False): """Create the asset assembly. The assets for asset assembly can be imported o referenced. The namespace will be the name of the asset. Args: filePath (str, optional): Path to the connection dictionary reference (bool, optional): If True will create references Returns: None: None """ if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter=' Shifter joint cnx matrix ' ' .jmm (*%s)' % ".jmm") if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] asset_name = os.path.basename(filePath).split(".")[0] dir_path = os.path.dirname(filePath) for part in ["model.ma", "rig.ma"]: asset_path = os.path.join(dir_path, "_".join([asset_name, part])) if reference: ref = True imp = False message = "Reference" else: ref = False imp = True message = "Import" pm.displayInfo("{} asset: {} ".format(message, asset_path)) cmds.file(asset_path, i=imp, reference=ref, type="mayaAscii", ignoreVersion=True, mergeNamespacesOnClash=True, namespace=asset_name) # import cnx pm.displayInfo("Import connections dictionary ".format(filePath)) importConnections(filePath, nsRig=asset_name, nsSkin=asset_name) # reconnect jont_vis root = [x for x in pm.ls(type="transform") if x.hasAttr("is_rig")] if root: jnt_org = pm.PyNode(asset_name + ":jnt_org") pm.connectAttr(root[0].jnt_vis, jnt_org.visibility)
def set_template(self, template): """ Set which template to use """ pm.displayInfo( 'Setting template to: {template}'.format(template=template)) with open(template) as json_file: self.template = json.load(json_file) self.help.setText(self.template.get('help'))
def load_cvwrap(self): # wrap face to head rig try: if not pm.pluginInfo("cvwrap", q=True, loaded=True): pm.loadPlugin("cvwrap") pm.displayInfo("cvrap plugin loaded!") except RuntimeError: pm.displayError("You need the cvWrap plugin!") raise
def run(self): # -- Ensure all rigs are editable for rig in crab.Rig.all(): if not rig.is_editable(): confirmation = qute.utilities.request.confirmation( title='%s is not editable' % rig.node().name(), label='To assign a pose, the rig needs to be editable. Would you like to put the rig into an editable state?', ) if confirmation: rig.edit() else: # -- If any rig is not intended to be editable, exit return selection_state_text = 'all joints' rotation_only_text = '' if self.options.selection_only: nodes = pm.selected() selection_state_text = 'selected joints' else: nodes = pm.ls('%s_*' % crab.config.SKELETON, type='joint', r=True) nodes.extend(pm.ls('%s_*' % crab.config.GUIDE, type='transform', r=True)) with crab.utils.contexts.UndoChunk(): for joint in nodes: if joint.hasAttr(self.POSE_NAME): pos = None if self.options.rotate_only: pos = joint.getTranslation() rotation_only_text = 'rotation only' rot = None if self.options.translate_only: rot = joint.getRotation() rotation_only_text = 'translation only' joint.setMatrix(joint.attr(self.POSE_NAME).get()) if pos: joint.setTranslation(pos) if rot: joint.setRotation(rot) pm.displayInfo('Loaded: {} to {} {}'.format( self.POSE_NAME, selection_state_text, rotation_only_text ))
def clear_uvs(entity, objects): if not objects: objects = get_polygons(entity) if not objects: core.displayWarning('not found any input polygons!...') studio_maya = studioMaya.Connect() for object in objects: studio_maya.node = object studio_maya.clear() core.displayInfo('// Result: clear success!...')
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 constrain_to_rig(self, nothing): """Constrain the plebe to the mGear rig using constraints """ # Sanity checking if not pm.objExists(self.template.get('root')): pm.warning("Unable to find '{character}' in scene! ".format( character=self.template.get('root') ), "Check that you have the correct template selected") return False if not pm.objExists('global_C0_ctl'): pm.warning("You need to build the rig first!") return False warnings = False for pairs in self.template.get('joints'): for source, target in pairs.items(): if not pm.objExists(target.get('joint')): warnings = True pm.warning("Joint '{joint}' not found, so it won't be " "connected to the rig.".format( joint=target.get('joint') ) ) continue self.clear_transforms(target.get('joint')) if target.get('constrain')[0] == "1" and target.get('constrain')[1] == "1": pm.parentConstraint( source, target.get('joint'), maintainOffset=True, decompRotationToChild=True ) elif target.get('constrain')[0] == "1": pm.pointConstraint( source, target.get('joint'), maintainOffset=True ) elif target.get('constrain')[1] == "1": pm.orientConstraint( source, target.get('joint'), maintainOffset=True ) if target.get('constrain')[2] == "1": pm.scaleConstraint( source, target.get('joint'), maintainOffset=True ) pm.displayInfo("Done attaching the character to the rig") if warnings: pm.warning("Some joints failed to attach to the rig. " "See the script editor for details!")
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 buildFromSelection(self): """Build the rig from selected guides.""" startTime = datetime.datetime.now() mgear.log("\n" + "= SHIFTER RIG SYSTEM " + "=" * 46) self.stopBuild = False selection = pm.ls(selection=True) if not selection: mgear.log( "Select one or more guide root or a guide model", mgear.sev_error, ) return # check if is partial build or full guide build ismodel = False if selection[0].hasAttr("ismodel"): self.preCustomStep(selection) ismodel = True if not self.stopBuild: mgear.log("\n" + "= GUIDE VALIDATION " + "=" * 46) # Check guide is valid self.guide.setFromSelection() if not self.guide.valid: return # Build mgear.log("\n" + "= BUILDING RIG " + "=" * 46) self.build() if ismodel: self.postCustomStep() # Collect post-build data build_data = self.collect_build_data() endTime = datetime.datetime.now() finalTime = endTime - startTime pm.flushUndo() pm.displayInfo( "Undo history have been flushed to avoid " "possible crash after rig is build. \n" "More info: " "https://github.com/miquelcampos/mgear/issues/72" ) mgear.log( "\n" + "= SHIFTER BUILD RIG DONE {} [ {} ] {}".format( "=" * 16, finalTime, "=" * 7 ) ) return build_data
def exportSkinPack(packPath=None, objs=None, use_json=False, *args): if use_json: file_ext = FILE_JSON_EXT else: file_ext = FILE_EXT if not objs: if pm.selected(): objs = pm.selected() else: pm.displayWarning("Please Select Some Objects") return packDic = { "packFiles": [], "rootPath": [] } if packPath is None: startDir = pm.workspace(q=True, rootDirectory=True) packPath = pm.fileDialog2(dialogStyle=2, fileMode=0, startingDirectory=startDir, fileFilter='mGear skinPack (*%s)' % PACK_EXT) if not packPath: return packPath = packPath[0] if not packPath.endswith(PACK_EXT): packPath += PACK_EXT if not packPath.endswith(PACK_EXT): pm.displayWarning("Not valid file extension for: {}".format(packPath)) return packDic["rootPath"], packName = os.path.split(packPath) for obj in objs: fileName = obj.stripNamespace() + file_ext filePath = os.path.join(packDic["rootPath"], fileName) if exportSkin(filePath, [obj], use_json): packDic["packFiles"].append(fileName) pm.displayInfo(filePath) else: pm.displayWarning( obj.name() + ": Skipped because don't have Skin Cluster") if packDic["packFiles"]: data_string = json.dumps(packDic, indent=4, sort_keys=True) with open(packPath, 'w') as f: f.write(data_string + "\n") pm.displayInfo("Skin Pack exported: " + packPath) else: pm.displayWarning("Any of the selected objects have Skin Cluster. " "Skin Pack export aborted.")
def import_fbx(self, nothing): """Import a FBX """ fbx_filter = "FBX (*.fbx)" fbx = pm.fileDialog2(fileFilter=fbx_filter, caption='Import FBX', okCaption='Import', fileMode=1) if fbx: pm.displayInfo("Importing: {fbx}".format(fbx=fbx)) pm.importFile(fbx[0])
def wrapper(*args, **kwargs): # pm.displayInfo('Profiling Started : {}'.format(func.__name__)) directory = os.path.dirname(os.path.abspath(__file__)) export_filename = func.__name__ + ".pfl" export_path = os.path.join(directory, export_filename) profiler = cProfile.Profile() result = profiler.runcall(func, *args, **kwargs) profiler.dump_stats(export_path) pm.displayInfo('Profile Saved to : {}'.format(export_path)) return result
def onFinished(export_path): """ Called when the export is finished, after writing the file. Args: export_path (string): Path exported to, supposedly. """ if not os.path.exists(export_path): pm.error(export_path + ' does not exist! Did you specify the export_method of the class?') size = pcu.getFileSize(export_path) pm.displayInfo(size + ' exported to: ' + export_path)
def load_plugin(): """ Looks for and loads Sol Handle plugin. :return True if the plugin was loaded, False otherwise. """ # Simple look up if is_plugin_loaded(): return True # Try to get at this location path = "{}/{}".format(os.path.dirname(__file__), Vars.PLUGIN_FILE) if os.path.isfile(path): pmc.loadPlugin(path) if is_plugin_loaded(): pmc.displayInfo("[SOL] SolHandle plugin loaded from " + path) return True # Try user prompt q = QtGui.QMessageBox.question( None, "Sol", "Sol Handle plugin was not found. Would you like to look for it ?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No ) if q == "Yes": f, _ = QtGui.QFileDialog.getOpenFileName( None, "Load Sol Handle Plugin", Vars.PLUGIN_FILE, "*.py" ) if f: pmc.loadPlugin(f) return is_plugin_loaded() # If nothing worked return False
def switch_viewport_renderer(v): """Switches the current viewport to the legacy opengl renderer.""" v.setRendererName("base_OpenGL_Renderer") pmc.displayInfo("[SOL] Active viewport switched to Legacy Viewport.")
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