Exemplo n.º 1
0
    def __init__(self, dir="", descriptor="main", version=1, ext="ma"):
        """Initialises our attributes when class is instantiated.
        If the scene has not been saved, initialise the attributes based on 
        the defaults. Otherwise, if the scene is already saved, initialise 
        attributes based on the file name of the opened scene.
        """
        if pmc.system.isModified():
            self._dir = Path(dir)
            self.descriptor = descriptor
            self.version = version
            self.ext = ext
        else:
            open_path = Path(pmc.system.sceneName())

            self.dir = open_path.parent

            fullname = open_path.name

            nameandversion = fullname.split("_v")

            if len(nameandversion) != 2:
                raise RuntimeError("Incorrect naming scheme. Use this format for files: "
                                   "SceneName + _v + VersionNumber")
            self.descriptor = nameandversion[0]
            self.version = int(nameandversion[1].split(".")[0])
            self.ext = nameandversion[1].split(".")[1]
Exemplo n.º 2
0
 def __init__(self, path):
     self.folder_path = Path()
     self.descriptor = 'main'
     self.task = None
     self.ver = 1
     self.ext = '.ma'
     self._init_from_path(path)
Exemplo n.º 3
0
 def _init_from_path(self, path):
     if not path:
         path = ''
     path = Path(path)
     self.folder_path = path.parent
     self.ext = path.ext
     self.descriptor, self.task, ver = path.stripext().split("_")
     self.ver = int(ver.split("v")[-1])
Exemplo n.º 4
0
 def __init__(self, path=None):
     self.folder_path = Path()
     self.descriptor = 'main'
     self.task = None
     self.ext = '.ma'
     scene = pmc.system.sceneName()
     if not path and scene:
         path = scene
     if not path and not scene:
         log.warning("Unable to initialize Scenefile object from a"
                     "new scene. pls, specify a path. FOOL!")
         return
     self._init_from_path(path)
Exemplo n.º 5
0
 def _create_folder_ui(self):
     default_folder = Path(cmds.workspace(rootDirectory=True, query=True))
     default_folder = default_folder / "scenes"
     current_folder = Path(os.getcwd())
     if not pmc.system.sceneName():
         self.folder_le = QtWidgets.QLineEdit(default_folder)
     else:
         self.folder_le = QtWidgets.QLineEdit(current_folder)
     self.folder_browse_btn = QtWidgets.QPushButton("...")
     layout = QtWidgets.QHBoxLayout()
     layout.addWidget(self.folder_le)
     layout.addWidget(self.folder_browse_btn)
     return layout
Exemplo n.º 6
0
 def __init__(self, path=None):
     self._folder_path = Path(cmds.workspace(query=True, rootDirectory=True)) / "scenes"
     self.descriptor = "main"
     self.task = "model"
     self.version = 1
     self.extension = ".ma"
     scene = pmc.system.sceneName()
     if not path and scene:
         path = scene
     elif not path and not scene:
         log.info("Initialized SceneFile object with default properties.")
         return
     self._init_from_path(Path(path))
Exemplo n.º 7
0
 def __init__(self, path=None):
     self.folder_path = Path()
     self.descriptor = 'main'
     self.task = None
     self.ver = 1
     self.ext = '.ma'
     scene = pnc.system.sceneName()
     if not path:
         path = scene
     if not path and not scene:
         log.warning("Unable to initialize SceneFile object from a new"
                     "scene. Please specify a path.")
         return
     self._init_from_path(path)
Exemplo n.º 8
0
 def __init__(self, dir='', descriptor='main', version=1, ext="ma"):
     #Delineates between new scene vs open scene with naming conventions
     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
         self.descriptor = file_name.split("_v")[0]
         version = file_name.split("_v")[1].split(".")[0]
         self.version = int(version)
         self.ext = file_name.split(".")[1]
Exemplo n.º 9
0
class SceneFile(object):
    """An abstract representation of a Scene file."""
    def __init__(self, path=None):
        self.folder_path = Path()
        self.descriptor = 'main'
        self.task = None
        self.ver = 1
        self.ext = '.ma'
        scene = pmc.system.sceneName()
        if not path and scene:
            path = scene
        if not path and not scene:
            log.warning("Unable to initalise SceneFile object from a new"
                        "scene. Please specify a path.")
            return
        self._init_from_path(path)

    @property
    def filename(self):
        pattern = "{descriptor}_{task}_v{ver:03d}{ext}"
        return pattern.format(descriptor=self.descriptor,
                              task=self.task,
                              ver=self.ver,
                              ext=self.ext)

    @property
    def path(self):
        return self.folder_path / self.filename

    def _init_from_path(self, path):
        path = Path(path)
        self.folder_path = path.parent
        self.ext = path.ext
        self.descriptor, self.task, ver = path.name.stripext().split("_")
        self.ver = int(ver.split("v")[-1])

    def save(self):
        """Saves the scene file.

        Returns:
            Path: The path to the scene if successful.
        """
        try:
            return pmc.system.saveAs(self.path)
        except RuntimeError as err:
            log.warning("Missing directories in path. Creating directories...")
            self.folder_path.makedirs_p()
            return pmc.system.saveAs(self.path)
Exemplo n.º 10
0
 def _init_from_path(self, path):
     path = Path(path)
     self.folder_path = path.parent
     self.ext = path.ext
     self.descriptor, self.task, ver = re.findall('([^_]+)+',
                                                  path.name.stripext())
     self.ver = int(ver.split("v")[-1])
Exemplo n.º 11
0
 def path(self):
     """The function returns a path to scene file.
     This includes the drive letter, any directory path and the file name.
     Returns:
         Path: The path to the scene file.
     """
     return Path(self.dir) / self.basename()
Exemplo n.º 12
0
 def __init__(self, path):
     self.folder_path = Path()
     self.descriptor = "main"
     self.task = None
     self.ver = 1
     self.ext = ".ma"
     self._init_from_path(path)
Exemplo n.º 13
0
 def __init__(self):
     '''Constructor'''
     #Makes constructor compatible with both python 2 and 3
     super(modelimport, self).__init__(parent=maya_main_window())
     '''Setup connection to filereader'''
     self.manager = filereader.SceneFile()
     self.validExtensions = ["ma", "obj", "fbx"]
     self.myPath = Path.splitpath(Path(__file__))[0]
     '''Setup new python window'''
     self.setWindowTitle("3D Model Import")
     self.resize(1000, 800)
     self.setWindowFlags(self.windowFlags()
                         ^ QtCore.Qt.WindowContextHelpButtonHint)
     self.create_widgets()
     self.create_layout()
     self.create_connections()
Exemplo n.º 14
0
 def _init_from_path(self, path):
     """creates the necessary variables from a path"""
     path = Path(path)
     self.folder_path = path.parent
     self.ext = path.ext
     self.descriptor, self.task, ver = path.name.stripext().split("_")
     self.ver = int(ver.split("v")[-1])
Exemplo n.º 15
0
 def __init__(self, dir='', descriptor='main', version=1, ext="ma"):
     self._dir = Path(dir)
     self.descriptor = descriptor
     self.version = version
     self.ext = ext
     scene = pmc.system.sceneName()
     if scene:
         self._init_properties_from_path(scene)
Exemplo n.º 16
0
 def __init__(self,
              dir=pmc.system.sceneName(),
              descriptor='main',
              version=1,
              ext="ma"):
     self._dir = Path(dir)
     if self._dir == '':
         self.descriptor = descriptor
         self.version = version
         self.ext = ext
         self._dir = Path(pmc.system.sceneName())
     else:
         file_name = self._dir.split('/')[-1]
         attributes = parse_name(file_name)
         self.descriptor = attributes['descriptor']
         self.version = attributes['version']
         self.ext = attributes['ext']
Exemplo n.º 17
0
 def _create_folder_ui(self):
     default_folder = Path(cmds.workspace(rootDirectory=True, query=True))
     default_folder = default_folder / "scenes"
     self.folder_le = QtWidgets.QLineEdit(default_folder)
     self.folder_browse_btn = QtWidgets.QPushButton("...")
     layout = QtWidgets.QHBoxLayout()
     layout.addWidget(self.folder_le)
     layout.addWidget(self.folder_browse_btn)
     return layout
Exemplo n.º 18
0
 def _create_folder_ui(self):
     default_folder = Path(os.getcwd())
     default_folder = default_folder / "scenes"
     self.folder_le = QtWidgets.QLineEdit(default_folder)
     self.folder_browse_btn = QtWidgets.QPushButton("...")
     layout = QtWidgets.QHBoxLayout()
     layout.addWidget(self.folder_le)
     layout.addWidget(self.folder_browse_btn)
     return layout
Exemplo n.º 19
0
 def _init_from_path(self, path):
     path = Path(path)
     self._folder_path = path.parent
     try:
         property_list = re.findall(r"([^\W_v]+|\.[A-Za-z0-9]+)", path.name)
         self.descriptor, self.task, ver, self.ext = property_list
         self.ver = int(ver.lstrip("0"))
     except ValueError as error:
         log.warning("File does not match naming convention. "
                     "Using default values...")
Exemplo n.º 20
0
 def save(self):
     """Saves the scene file.
     Returns:
         Path: The path to the scene file if successful, None, otherwise.
     """
     try:
         pmc.system.saveAs(self.path())
     except RuntimeError:
         log.warning("Missing Directories... Creating Directories.")
         Path(self.dir).makedirs_p()
         pmc.system.saveAs(self.path())
Exemplo n.º 21
0
    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]
Exemplo n.º 22
0
 def __init__(self, dir="", descriptor="main", version=1, ext="ma"):
     #how do I find the open file
     try:
         self._dir = self.isolate_filepath()
         self.descriptor = self.isolate_descriptor()
         self.version = self.isolate_version()
         self.ext = self.isolate_ext()
     except Exception:
         self._dir = Path(dir)
         self.descriptor = descriptor
         self.version = version
         self.ext = ext
Exemplo n.º 23
0
    def __init__(self,
                 dir='',
                 descriptor='main',
                 version=1,
                 ext="ma",
                 current_scene=False):
        """Constructs SceneFile from the directory, descriptor, version, and extension

        Other Params:
            current_scene: Construct SceneFile from getting the current scene info instead if True, otherwise use
                provided parameters
        """
        if current_scene:
            scene_name = pmc.system.sceneName()

            # If file has never been saved, use defaults instead
            if scene_name:
                # Get directory and extension from the path
                full_path = Path(scene_name)
                dir = full_path.dirname()
                ext = full_path.ext[1:]

                # Remove extension from base name and check for a version number
                back_offset = -1 * (len(ext) + 1)
                base_name = full_path.basename()[:back_offset]
                regex_str = ".*_v[0-9]{3}$"
                regex = re.compile(regex_str)

                if regex.match(base_name):
                    # The file already has a version number, use it
                    descriptor = base_name[:-5]
                    version = int(base_name[-3:])
                else:
                    # Otherwise use defaults
                    log.warning("Invalid naming format, using defaults.")

        self._dir = Path(dir)
        self.descriptor = descriptor
        self.version = version
        self.ext = ext
Exemplo n.º 24
0
 def __init__(self, path=None):
     self._folder_path = Path(os.getcwd()) / "scenes"
     self.descriptor = 'main'
     self.task = 'model'
     self.ver = 1
     self.ext = '.ma'
     scene = pmc.system.sceneName()
     if not path and scene:
         path = scene
     if not path and not scene:
         log.info("Initialize with default properties.")
         return
     self._init_from_path(path)
Exemplo n.º 25
0
	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:
		    current_path = Path(pmc.system.sceneName())
		    self.dir = current_path.parent
		    file_name = current_path.name
		    try:
		        self.descriptor = file_name.split("_v")[0]
		        file_version = file_name.split("_v")[1]
		        file_version_final = file_version.split(".")[0]
		        self.version = int(file_version_final)
		        self.ext = file_version.split(".")[1]
		    except IndexError:
		        self.descriptor = file_name.split("_")[0]
		        file_version = file_name.split("_")[1]
		        file_version_final = file_version.split(".")[0]
		        self.version = int(file_version_final)
		        self.ext = file_version.split(".")[1]
Exemplo n.º 26
0
 def __init__(self, dir='', descriptor='main', version=1, ext="ma"):
     """Defines class properties when created (like constructor)"""
     filePath = Path(
         os.path.normpath(
             cmds.file(query=True,
                       sn=True,
                       shortName=False,
                       withoutCopyNumber=True)))
     filePathSplit = os.path.split(filePath)
     regex = r'([a-zA-Z]+)_v([0-9]+).([a-z]+)'
     if (re.match(regex, filePathSplit[1])):
         filePathDescriptor = filePathSplit[1].split("_")
         filePathVersion = filePathDescriptor[1].split(".")
         filePathNum = self._extractNum(filePathVersion[0])
         self._dir = Path(filePathSplit[0])
         self.descriptor = filePathDescriptor[0]
         self.version = filePathNum
         self.ext = filePathVersion[1]
     else:
         self._dir = dir
         self.descriptor = descriptor
         self.version = version
         self.ext = ext
Exemplo n.º 27
0
 def __init__(self, path=None):
     self._folder_path = Path(cmds.workspace(query=True,
                                             rootDirectory=True)) / "scenes"
     self.descriptor = 'main'
     self.task = 'model'
     self.ver = 1
     self.ext = '.ma'
     scene = pmc.system.sceneName()
     if not path and scene:
         path = scene
     if not path and not scene:
         log.info("Initialize with default properties.")
         return
     self._init_from_path(path)
Exemplo n.º 28
0
 def __init__(self, dir="", descriptor='main', version=1, ext="ma"):
     FilePath = cmds.file(q=True, sn=True)
     if (FilePath == ""):
         self._dir = Path(dir)
         self.descriptor = descriptor
         self.version = version
         self.ext = ext
     else:
         parts = os.path.split(FilePath)
         self._dir = parts[0]
         Name = parts[1].split('_v')
         self.descriptor = Name[0]
         Split2 = Name[1].split('.')
         self.version = int(Split2[0])
         self.ext = Split2[1]
Exemplo n.º 29
0
    def _update_filename_display(self):
        if self.ver_sbx.value() is not self.current_ui_ver:
            self.ver_sbx.setValue(self.current_ui_ver)
        next_ver = self.scene_file.next_avail_ver(
            search_desc=self.current_ui_desc,
            search_task=self.current_ui_task,
            search_ext=self.scene_file.ext,
            search_path=Path(self.folder_le.text()))
        name_str = "{desc}_{task}".format(desc=self.current_ui_desc,
                                          task=self.current_ui_task)
        save_str = "_v{ver:03d}.ma".format(ver=self.current_ui_ver)
        inc_str = "_v{ver:03d}.ma".format(ver=next_ver)

        self.save_btn.setText("Save as: \n" + name_str + save_str)
        self.save_increment_btn.setText("Increment save as: \n" + name_str +
                                        inc_str)
Exemplo n.º 30
0
    def __init__(self, dir='', descriptor="main", version=1, ext="ma"):
        """Initialises our attributes when class is instantiated.

        If the scene has not been saved, initialise the attributes based on
        the defaults. Otherwise, if the scene is already saved, initialise
        attributes based on the file name of the opened scene

        """

        self._dir = Path(dir)
        self.descriptor = descriptor
        self.version = version
        self.ext = ext
        scene = pmc.system.sceneName()
        if scene:
            self._init_properties_from_path(scene)
Exemplo n.º 31
0
	def on_exportButton_clicked(self):
		
		if not ls(selection=True):
			return error('Nothing is currently selected.')
		
		# Load the objExport plug-in if it hasn't been already.
		kwargs = {}
		if self.formatExt.text() == '.obj':
			mll = 'objExport.mll'
			if not pluginInfo(mll, query=True, loaded=True):
				try:
					loadPlugin(mll)
					info('Loaded plug-in: ' + mll)
				except:
					return error('Failed loading plug-in: ' + mll)
			#kwargs = dict(force=True, constructionHistory=False,
			#	channels=False, constraints=False, expressions=True,
			#	shader=False, preserveReferences=False, type='OBJexport')
			options = dict(groups=self.groups, ptgroups=self.pointGroups,
				materials=self.materials, smoothing=self.smoothing,
				normals=self.normals)
			options = ';'.join('%s=%d' % (k, cb.isChecked()) \
				for k, cb in options.items())
			kwargs = dict(exportSelected=True, type='OBJexport', force=True,
				options=options)
		elif self.exportCombo.currentIndex() == 2:  # mesh
			return error('Unsupported extension: %s.' % self.formatExt.text())
		
		# Validate the output path.
		output_path = Path(self.path.text())
		if not output_path.exists():
			output_path = Path(self.set_path(workspace.getPath()))
			if not output_path.exists():
				return
		
		# Validate the frame range.
		start, end, by = self.start.value(), self.end.value(), self.by.value()
		remainder = (end - start) % by
		if remainder:
			click_result = confirmDialog(title='Confirm',
				message=os.linesep.join(( \
				'The end frame will not be exported because',
				'the "by frame" overshoots it by %.2f.' % remainder)),
				button=('OK', 'Cancel'), cancelButton='Cancel',
				defaultButton='OK', dismissString='Cancel')
			if click_result == 'Cancel':
				return
		
		# Validate the format.
		format = str(self.format.text())
		try:
			format % (start + by)
		except TypeError:
			return error('Invalid format: "%s". ' % format + \
				'Click the \'...\' tool button for help.' % format)
		
		# Disable UI elements while running.
		[o.show() for o in self.run_showers]
		[o.setEnabled(False) for o in self.run_disablers]
		
		# Set the range.
		if self.renumFrames.isChecked():
			renum_start = self.renumStart.value()
			self.renum_by = self.renumBy.value()
		else:
			renum_start = start
			self.renum_by = by
		self.frame, self.renum_frame = start, renum_start
		
		# Set loop vars.
		self.aborted = False
		self.export_count = 0
		self.copy_and_replace_all = False
		
		# Call the appropriate export function.
		(self.export_skeleton, self.export_camera, self.export_mesh,
			self.export_skin_weights)[self.exportCombo.currentIndex()](**kwargs)
		
		self.main_progress.endProgress()
		
		# Enable UI elements back.
		[o.hide() for o in self.run_showers]
		[o.setEnabled(True) for o in self.run_disablers]
		
		# Report results.
		if self.aborted:
			msg = 'Aborted with %s exported'
		else:
			msg = 'Successfully exported %s'
		plural = self.export_count != 1 and 's' or ''
		frames = '%d frame' % self.export_count + plural
		result(msg % frames + ' to: %s.' % output_path)
Exemplo n.º 32
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