Esempio n. 1
0
class SceneFile(object):
    """Initialises attributes when class is instantiated"""
    def __init__(self, dir='', descriptor='main', version=1, ext="ma"):
        if pmc.system.isModified():
            self.dir = Path(dir)
            self.descriptor = descriptor
            self.version = version
            self.ext = ext
        else:
            temp_path = Path(pmc.system.sceneName())
            self.dir = temp_path.parent

            file_name = temp_path.name
            file_part = file_name.split("_v")
            if len(file_part) != 2:
                raise RuntimeError("File name must contain _v")
            self.descriptor = file_part[0]

            version = file_part[1].split(".")[0]
            self.version = int(version)

            self.ext = file_part[1].split(".")[1]

    @property
    def dir(self):
        return self._dir

    @dir.setter
    def dir(self, val):
        self._dir = Path(val)

    """Return a scene file name"""

    def basename(self):
        name_pattern = "{descriptor}_v{version:03d}.{ext}"
        name = name_pattern.format(descriptor=self.descriptor,
                                   version=self.version,
                                   ext=self.ext)
        return name

    """Retuns a path to scene file"""

    def path(self):
        return Path(self.dir) / self.basename()

    """Saves the scene file"""

    def save(self):
        try:
            pmc.system.saveAs(self.path())
        except RuntimeError:
            log.warning("Missing directories. Creating directories.")
            self.dir.makedirs_p()
            pmc.system.saveAs(self.path())

    """Increments the version and saves the scene file, incrementing from next largest number available."""

    def increment_and_save(self):
        files_list = self.dir.listdir()
        scene_list = list()
        for file in files_list:
            file_path = Path(file)
            scene = file_path.name
            if self.is_scene_file(scene):
                scene_list.append(scene)
        new_version = self.version

        current_scenes = [
            x for x in scene_list if x.split("_v")[0] == self.descriptor
        ]
        for scene in current_scenes:
            version_name = scene.split("_v")[1].split(".")[0]
            version = int(version_name)
            if version > self.version:
                new_version = version

        self.version = new_version + 1
        self.save()

    def is_scene_file(self, filename):
        file_parts = filename.split("_v")
        if len(file_parts) != 2:
            return False
        file_version = file_parts[1].split(".")
        if len(file_version) != 2:
            return False
        if file_version[1] != "ma":
            return False
        if len(file_version[0]) != 3 or not file_version[0].isdigit():
            return False
        return True
Esempio n. 2
0
def _set_working_drive(working_drive):
    #set the working drive if it's not already
    if not working_drive:
        for c in reversed(get_available_drives()):
            d = Path(c + ':')
            if not (d / 'lavaWorkingDrive').isfile(): continue
            working_drive = d.drive
            break
        if not working_drive: return False
    working_drive = Path(working_drive[0] + ':/')

    #set the maya path
    maya_path = Path(working_drive) / 'maya'
    if not maya_path.isdir(): return False

    #it's too late at this point, unfortunately, to pick up the latest version of pymel,
    #nor does the Maya.env PYTHONPATH seem to work like it should, so,
    #assuming your working drive is Z, your Maya path is z:/maya and you've
    #installed the latest version of pymel in your Maya path, you need to edit the
    #environment variables for your account to include
    #PYTHONPATH: z:/maya/scripts;z:/maya/pymel-1.x.x
    #i wish there was a better way and maybe there is, but i really devoted a lot
    #of time and energy into solving this problem with python scripts and this is
    #the only solution that worked.

    #look for and load the maya/plug-ins folder too.
    env_key = 'MAYA_PLUG_IN_PATH'
    pips = getEnvs(env_key)
    for i, p in enumerate(pips):
        pips[i] = _fix_path(Path(p))
    for f in maya_path.listdir():
        if f.name == 'plug-ins':
            f = _fix_path(f)
            if f in pips:
                del pips[pips.index(f)]
            pips.insert(0, f)
            break
    putEnv(env_key, ';'.join(pips))

    #set the workspace
    workspace(maya_path / 'projects', openWorkspace=True)

    #set the script path
    script_path = maya_path / 'scripts'
    if script_path.isdir():

        #prepare some empty dictionaries to store unique
        #folder paths as keys for script locations.
        mels, pys, pymods = {}, {}, {}

        #put the file's folder path in the appropriate mel, mods
        #or pys dictionary.
        pats = {'__init__.py*': pymods, '*.mel': mels, '*.py': pys}
        for f in script_path.walkfiles():
            for k, v in pats.items():
                if f.fnmatch(k):
                    v[_fix_path(f.dirname())] = None

        #remove any pys keys that are also found in pymods.
        #this is the only reason we made pymods in the first place, so
        #delete pymods to make it clear that we're done with it.
        for k in (k for k in pymods.keys() if k in pys):
            del pys[k]
        del pymods

        #fix all the sys.paths to make them consistent with pys
        #key-searches and add any py leftovers to the sys.paths.
        pys[_fix_path(script_path)] = None
        sp = []
        for p in sys.path:
            p = _fix_path(Path(p))
            if p in pys:
                del pys[p]
            sp.append(p)
        sys.path = [k
                    for k in reversed(sorted(pys.keys(), key=str.lower))] + sp

        #fix all the maya script paths to make them consistent with mels
        #key-searches and add any mel leftovers to the env var.
        mels[_fix_path(script_path)] = None
        env_key = 'MAYA_SCRIPT_PATH'
        sps = getEnvs(env_key)
        for i, p in enumerate(sps):
            sps[i] = _fix_path(Path(p))
            if sps[i] in mels:
                del mels[sps[i]]
        for k in reversed(sorted(mels.keys(), key=str.lower)):
            sps.insert(0, k)
        putEnv(env_key, ';'.join(sps))

        #sourcing the scriptEditorPanel, for some reason, will actually check
        #the pymelScrollFieldReporter.py in the Plug-in Manager. if this is not
        #done, it will throw an error whenever the script editor is opened.
        sep = 'scriptEditorPanel.mel'
        if (script_path / sep).isfile():
            mel.source(sep)

    return True
Esempio n. 3
0
def _set_working_drive(working_drive):
	#set the working drive if it's not already
	if not working_drive:
		for c in reversed(get_available_drives()):
			d = Path(c + ':')
			if not (d / 'lavaWorkingDrive').isfile(): continue
			working_drive = d.drive
			break
		if not working_drive: return False
	working_drive = Path(working_drive[0] + ':/')
	
	#set the maya path
	maya_path = Path(working_drive) / 'maya'
	if not maya_path.isdir(): return False
	
	#it's too late at this point, unfortunately, to pick up the latest version of pymel,
	#nor does the Maya.env PYTHONPATH seem to work like it should, so,
	#assuming your working drive is Z, your Maya path is z:/maya and you've
	#installed the latest version of pymel in your Maya path, you need to edit the
	#environment variables for your account to include
	#PYTHONPATH: z:/maya/scripts;z:/maya/pymel-1.x.x
	#i wish there was a better way and maybe there is, but i really devoted a lot
	#of time and energy into solving this problem with python scripts and this is
	#the only solution that worked.
	
	#look for and load the maya/plug-ins folder too.
	env_key = 'MAYA_PLUG_IN_PATH'
	pips = getEnvs(env_key)
	for i, p in enumerate(pips):
		pips[i] = _fix_path(Path(p))
	for f in maya_path.listdir():
		if f.name == 'plug-ins':
			f = _fix_path(f)
			if f in pips:
				del pips[pips.index(f)]
			pips.insert(0, f)
			break
	putEnv(env_key, ';'.join(pips))
	
	#set the workspace
	workspace(maya_path / 'projects', openWorkspace=True)
	
	#set the script path
	script_path = maya_path / 'scripts'
	if script_path.isdir():
		
		#prepare some empty dictionaries to store unique
		#folder paths as keys for script locations.
		mels, pys, pymods = {}, {}, {}
		
		#put the file's folder path in the appropriate mel, mods
		#or pys dictionary.
		pats = {'__init__.py*': pymods, '*.mel': mels, '*.py': pys}
		for f in script_path.walkfiles():
			for k, v in pats.items():
				if f.fnmatch(k):
					v[_fix_path(f.dirname())] = None
		
		#remove any pys keys that are also found in pymods.
		#this is the only reason we made pymods in the first place, so
		#delete pymods to make it clear that we're done with it.
		for k in (k for k in pymods.keys() if k in pys):
			del pys[k]
		del pymods
		
		#fix all the sys.paths to make them consistent with pys
		#key-searches and add any py leftovers to the sys.paths.
		pys[_fix_path(script_path)] = None
		sp = []
		for p in sys.path:
			p = _fix_path(Path(p))
			if p in pys:
				del pys[p]
			sp.append(p)
		sys.path = [k for k in reversed(sorted(pys.keys(), key=str.lower))] + sp
		
		#fix all the maya script paths to make them consistent with mels
		#key-searches and add any mel leftovers to the env var.
		mels[_fix_path(script_path)] = None
		env_key = 'MAYA_SCRIPT_PATH'
		sps = getEnvs(env_key)
		for i, p in enumerate(sps):
			sps[i] = _fix_path(Path(p))
			if sps[i] in mels:
				del mels[sps[i]]
		for k in reversed(sorted(mels.keys(), key=str.lower)):
			sps.insert(0, k)
		putEnv(env_key, ';'.join(sps))
		
		#sourcing the scriptEditorPanel, for some reason, will actually check
		#the pymelScrollFieldReporter.py in the Plug-in Manager. if this is not
		#done, it will throw an error whenever the script editor is opened.
		sep = 'scriptEditorPanel.mel'
		if (script_path / sep).isfile():
			mel.source(sep)
	
	return True