def saveScreenshot(self, name, directory=DIRECTORY):
path = os.path.join(directory, '%s.jpg' % name)
# We'll fit the view to the objects in our scene or our selection
cmds.viewFit()
# We'll change our render format to jpg
cmds.setAttr("defaultRenderGlobals.imageFormat", 8) # This is the value for jpeg
# Finally we'll save out our image using the playblast module
# There are a lot of arguments here so it's good to use the documentation to know what's going on
cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200,
showOrnaments=False, startTime=1, endTime=1, viewer=False)
# Return the path of the file we saved
return path
# This will be our first Qt UI!
# We'll be creating a dialog, so lets start by inheriting from Qt's QDialog
python类file()的实例源码
def save(self):
# We start off by getting the name in the text field
name = self.saveNameField.text()
# If the name is not given, then we will not continue and we'll warn the user
# The strip method will remove empty characters from the string, so that if the user entered spaces, it won't be valid
if not name.strip():
cmds.warning("You must give a name!")
return
# We use our library to save with the given name
self.library.save(name)
# Then we repopulate our UI with the new data
self.populate()
# And finally, lets remove the text in the name field so that they don't accidentally overwrite the file
self.saveNameField.setText('')
def delete_bookmark(ui, value):
'''
???????????
:param type: ??????????
:param value: ??????
:return:
'''
if ui.radio_bookmark_file.isChecked():
type = 'file'
elif ui.radio_bookmark_directory.isChecked():
type = 'directory'
option_var_name = get_bookmark_option_var_name(type)
ls = cmds.optionVar(q=option_var_name)
if ls != 0:
if value in ls:
ls.remove(value)
cmds.optionVar(ca=option_var_name)
[cmds.optionVar(sva=(option_var_name, i)) for i in ls]
return
def _maintained_selection_context():
"""Maintain selection during context
Example:
>>> scene = cmds.file(new=True, force=True)
>>> node = cmds.createNode("transform", name="Test")
>>> cmds.select("persp")
>>> with maintained_selection():
... cmds.select("Test", replace=True)
>>> "Test" in cmds.ls(selection=True)
False
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
def process(self, name, namespace, context, data):
from maya import cmds
cmds.loadPlugin("AbcImport.mll", quiet=True)
nodes = cmds.file(
self.fname,
namespace=namespace,
# Prevent identical alembic nodes
# from being shared.
sharedReferenceFile=False,
groupReference=True,
groupName=namespace + ":" + name,
reference=True,
returnNewNodes=True
)
self[:] = nodes
def process(self, instance):
from maya import cmds
from avalon import maya
with maya.maintained_selection():
cmds.select(instance, replace=True)
nodes = cmds.file(
constructionHistory=True,
exportSelected=True,
preview=True,
force=True,
)
self.assemblies[:] = cmds.ls(nodes, assemblies=True)
if not self.assemblies:
raise Exception("No assembly found.")
if len(self.assemblies) != 1:
self.assemblies = '"%s"' % '", "'.join(self.assemblies)
raise Exception(
"Multiple assemblies found: %s" % self.assemblies
)
def source_nodes():
cmds.file(new=True, force=True)
source1, _ = pm.polyCube(name="source1")
source2, _ = pm.polyCube(name="source2")
target, _ = pm.polyCube(name="target")
ch1 = att.addAttribute(source1,
"chanName",
"double",
0,
minValue=0,
maxValue=1)
ch2 = att.addAttribute(source2,
"chanName",
"double",
0,
minValue=0,
maxValue=1)
pm.connectAttr(ch1, source1.ty)
pm.connectAttr(ch2, source2.ty)
def source_nodes():
cmds.file(new=True, force=True)
pcs = pm.polyCube(name="armUI_R0_ctl")
pcs2 = pm.polyCube(name="armUI_R1_ctl")
attribute.addAttribute(pcs[0],
"shoulder_ik",
"double",
0,
minValue=0,
maxValue=1)
ch2 = attribute.addAttribute(pcs[0],
"shoulder_rotRef",
"double",
0,
minValue=0,
maxValue=1)
ch3 = attribute.addAttribute(pcs2[0],
"shoulder_rotRef",
"double",
0,
minValue=0,
maxValue=1)
pm.connectAttr(ch2, pcs[0].ty)
pm.connectAttr(ch3, pcs2[0].ty)
def get_temp_filename(cls, file_name):
"""Get a unique filepath name in the testing directory.
The file will not be created, that is up to the caller. This file will be deleted when
the tests are finished.
@param file_name: A partial path ex: 'directory/somefile.txt'
@return The full path to the temporary file.
"""
temp_dir = Settings.temp_dir
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
base_name, ext = os.path.splitext(file_name)
path = '{0}/{1}{2}'.format(temp_dir, base_name, ext)
count = 0
while os.path.exists(path):
# If the file already exists, add an incrememted number
count += 1
path = '{0}/{1}{2}{3}'.format(temp_dir, base_name, count, ext)
cls.files_created.append(path)
return path
def execute(self):
for container in self.files:
operation = container['operation'].value()
file_path = container['file_path'].get_path()
namespace = container['namespace'].value()
flag = 'i' if operation == Component.import_operation else 'r'
kwargs = {
flag: True,
'type': {
'.ma': 'mayaAscii',
'.mb': 'mayaBinary',
'.fbx': 'FBX',
}[os.path.splitext(file_path.lower())[-1]]
}
if namespace:
kwargs['namespace'] = namespace
cmds.file(file_path, **kwargs)
def repath(node, file, project_path):
matches = []
for root, dirnames, filenames in os.walk(project_path):
for x in filenames:
if x == file:
matches.append([root,os.path.join(root, x)])
elif x.split(".")[0] == file.split(".")[0]: #---> this second option is used when a file is useing ##### padding, we can match by name only
x_ext = x.split(".")[len(x.split("."))-1]
file_ext = file.split(".")[len(file.split("."))-1]
if x_ext == file_ext:
matches.append([root,os.path.join(root, x)])
if len(matches)>0:
return cmds.filePathEditor(node, repath=matches[0][0])
return None
def test_texture_sampler():
'''Test the texture_sampler function'''
# Compile and reload plugin modules
from .. import plugins
plugins._import_plugins()
# Get texture_sampler
from ..plugins.textureSampler import texture_sampler
from maya import cmds
cmds.file(new=True, force=True)
plugins.safe_reload('textureSampler')
ramp = cmds.shadingNode('ramp', asTexture=True)
spotlight = cmds.shadingNode('spotLight', asLight=True)
sampler = texture_sampler(ramp, [(0.5, 0.0), (0.5, 0.5), (0.5, 1.0)])
sampler.connect('color', [spotlight])
def exitRigEditMode(self):
global g_rigEditModeFileName
globals.noUpdate = True
cmds.headsUpDisplay(rp=(2,2))
tempDir = mel.eval("getenv TEMP;")
if g_rigEditModeFileName == "":
cmds.file(tempDir+"\\rigModeTemp.ma",f=True,open=True)
else:
cmds.file(g_rigEditModeFileName,f=True,open=True)
self.refreshListWidget()
self.addRigBtn.setEnabled(True)
self.updateAllBtn.setEnabled(True)
self.rigList.setEnabled(True)
self.createRigBtn.setEnabled(True)
self.openNodeBtn.setEnabled(False)
self.exitRigEditBtn.setEnabled(False)
self.versionComboBox.setEnabled(True)
if "Latest" in str(self.versionComboBox.currentText()):
self.forceRigUpdate()
def test_hasattr(self):
print(u"test_hasattr")
cmds.file(new=True, f=True)
cube = cmds.polyCube()[0]
m = mtn.M(u"pCube1")
assert(m.hasAttr(u"t.tx") == True)
assert(m.hasAttr(u"t") == True)
assert(m.hasAttr(u"tx") == True)
assert(m.hasAttr(u"aaa") == False)
assert(m.hasAttr(u"wm") == True)
assert(m.hasAttr(u"wm[0]") == True)
assert(m.hasAttr(m.t) == True)
assert(m.hasAttr(m.tx) == True)
assert(m.hasAttr(m.wm) == True)
assert(m.hasAttr(m.wm[0]) == True)
def test_cached_attribute(self):
print(u"test_cached_attribute")
cmds.file(new=True, f=True)
cube = cmds.polyCube()[0]
m1 = mtn.M(u"pCube1")
# m1._cache = True # default:True
m2 = mtn.M(u"pCube1")
m2._cache = False
assert(m1._cache_attribute == {})
assert(m2._cache_attribute == {})
m1.t
m2.t
assert(u"t" in m1._cache_attribute)
assert(u"t" not in m2._cache_attribute)
assert(m1._cache == True)
assert(m2._cache == False)
assert(m1.t._cache == True)
assert(m2.t._cache == False)
assert(m1.t.tx._cache == True)
assert(m2.t.tx._cache == False)
def test_listconnections(self):
print(u"test_listconnections")
cmds.file(new=True, f=True)
cube = cmds.polyCube()[0]
m = mtn.M(u"pCube1")
cmds.setKeyframe("pCube1.tx", "pCube1.ty", "pCube1.tz",
"pCube1.rx", "pCube1.ry", "pCube1.rz",
"pCube1.sx", "pCube1.sy", "pCube1.sz")
assert(type(m.listConnections()) == list)
assert(m.listConnections(asGenerator=True).__class__.__name__ == "generator")
m.listConnections(asGenerator=True, c=True)
m.listConnections(asGenerator=True, p=True)
m.listConnections(asGenerator=True, c=True, p=True)
m.listConnections(c=True)
m.listConnections(p=True)
m.listConnections(c=True, p=True)
assert(m.listConnections(c=True,s=False) == [])
assert(m.listConnections(p=True,s=False) == [])
def import_animation(*args):
"""imports the anim (from rand selection of list items) onto selected objs"""
lo, hi = cmds.intFieldGrp(widgets["rangeIFG"], q=True, v=True)
rand = cmds.radioButtonGrp(widgets["randRBG"], q=True, sl=True)
clips = cmds.textScrollList(widgets["animTSL"], q=True, si=True)
path = cmds.textFieldButtonGrp(widgets["impPathTFG"], q=True, tx=True)
options = {"targetTime":3, "time": 1, "option":"insert", "connect":1}
delKeys = cmds.checkBoxGrp(widgets["delCBG"], q=True, v1=True)
sel = cmds.ls(sl=True)
for obj in sel:
startF = cmds.currentTime(q=True)
if rand == 1:
startF = random.randint(lo, hi)
cmds.currentTime(startF)
if delKeys:
delete_later_keys(obj, startF)
cmds.select(obj, r=True)
myClip = random.choice(clips)
animPath = "{0}/{1}".format(path, myClip)
cmds.file(animPath, i = True, type = "animImport", ignoreVersion = True, options = "targetTime={0};time={1};copies=1;option={2};pictures=0;connect={3};".format(options["targetTime"], startF, options["option"], options["connect"]), preserveReferences=True)
cmds.select(sel, r=True)
def lock():
"""Lock scene
Add an invisible node to your Maya scene with the name of the
current file, indicating that this file is "locked" and cannot
be modified any further.
"""
if not cmds.objExists("lock"):
with lib.maintained_selection():
cmds.createNode("objectSet", name="lock")
cmds.addAttr("lock", ln="basename", dataType="string")
# Permanently hide from outliner
cmds.setAttr("lock.verticesOnlySet", True)
fname = cmds.file(query=True, sceneName=True)
basename = os.path.basename(fname)
cmds.setAttr("lock.basename", basename, type="string")
def maintained_selection():
"""Maintain selection during context
Example:
>>> scene = cmds.file(new=True, force=True)
>>> node = cmds.createNode("transform", name="Test")
>>> cmds.select("persp")
>>> with maintained_selection():
... cmds.select("Test", replace=True)
>>> "Test" in cmds.ls(selection=True)
False
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
def save(self):
"""
Funcrtion saves the execution times of commands to the file.
"""
i = 0
scores = []
while i < self.target_list.count():
scores.append(self.target_list.item(i).text())
i += 1
path = QtGui.QFileDialog.getExistingDirectory(None, 'Wybierz folder do zapisu pliku wyniki.txt',
'D:/Dane/Projekty/licencjat/')
with open(path + '/wyniki_Maya.txt', 'w') as file_:
for score in scores:
file_.write(score + '\n')
def load(self, name):
path = self[name]['path']
# We tell the file command to import, and tell it to not use any nameSpaces
cmds.file(path, i=True, usingNamespaces=False)
# This function will save a screenshot to the given directory with the given name
def file_context_menu(self, pos):
add_menu_label = ['Add to bookmark']
action = self.build_context_menu(pos, self.view_file, self.file_model, add_menu_label)
if action == add_menu_label[0]:
path = self.get_view_select(self.view_file, self.file_model)
add_bookmark('file', path)
self.setup_view_bookmark()
def get_bookmark_option_var_name(type):
if type == 'file':
return 'SceneExplorer_BookmarkFileList'
elif type == 'directory':
return 'SceneExplorer_BookmarkDirectoryList'
def get_bookmark(ui):
'''
????????????????????
:param ui: ui???????
:return: ????????
'''
if ui.radio_bookmark_file.isChecked():
type = 'file'
elif ui.radio_bookmark_directory.isChecked():
type = 'directory'
option_var_name = get_bookmark_option_var_name(type)
ls = cmds.optionVar(q=option_var_name)
if ls == 0:
ls = []
return ls
def execute(my):
# get the sobject passed in
sobject = my.get_input_value('sobject')
code = sobject.get('code')
search_key = my.get_package_value("search_key")
# get the designated local directory to put temporary files
tmp_dir = my.get_package_value("local_dir")
path = "%s/%s.ma" % (tmp_dir, code)
context = my.get_package_value("asset_context")
# FIXME: ignore subcontext for now
#subcontext = my.get_package_value("asset_sub_context")
#if subcontext:
# context = "%s/%s" % (context, subcontext)
# save out the file
cmds.file( rename=path)
cmds.file( save=True, type='mayaAscii')
# checkin the file that was just saved
my.server.upload_file(path)
snapshot = my.server.simple_checkin(search_key, context, path)
# add a mock dependency
snapshot_code = snapshot.get("code")
my.server.add_dependency(snapshot_code, "C:/tt.pdf")
def open_scene(file_path, dir_path, all_process):
# check if scene need saving
new_scene = mel.eval('saveChanges("file -f -new")')
if bool(new_scene):
print('Opening: ' + file_path)
# set_workspace(dir_path, all_process)
cmds.file(file_path, open=True, force=True)
# cmds.file(q=True, location=True) #prtint current scene path
def import_scene(file_path):
print('Importing: ' + file_path)
cmds.file(file_path, i=True)
def reference_scene(file_path):
print('Referencing: ' + file_path)
cmds.file(file_path, r=True)
def clear():
shutil.rmtree(self._tempdir)
self._tempdir = tempfile.mkdtemp()
cmds.file(new=True, force=True)
cmds.file(rename="temp.ma")
def process(self, name, namespace, context, data):
from maya import cmds
nodes = cmds.file(
self.fname,
namespace=namespace,
reference=True,
returnNewNodes=True,
groupReference=True,
groupName=namespace + ":" + name
)
self[:] = nodes