Exemplo n.º 1
0
	def validate_form(self, skip_replace_with=False):
		search_for = str(self.searchFor.text())
		if not search_for:
			error('"Search for" field is empty.')
		if not skip_replace_with:
			replace_with = str(self.replaceWith.text())
			if not replace_with:
				error('"Replace with" field is empty.')
			return search_for, replace_with
		return search_for
Exemplo n.º 2
0
 def validate_form(self, skip_replace_with=False):
     search_for = str(self.searchFor.text())
     if not search_for:
         error('"Search for" field is empty.')
     if not skip_replace_with:
         replace_with = str(self.replaceWith.text())
         if not replace_with:
             error('"Replace with" field is empty.')
         return search_for, replace_with
     return search_for
Exemplo n.º 3
0
	def assign_new_names(self):
		new_name = str(self.newName.text())
		if not new_name:
			return error('New name is empty.')
		
		# Solve naming conflicts by first naming everything foo#.
		for n in self._nodes:
			rename(n, 'foo#')
		
		if not new_name.count('%'):
			new_name += '%d'
		for i, n in enumerate(self._nodes):
			self.rename(n, new_name % (i + 1))
Exemplo n.º 4
0
    def assign_new_names(self):
        new_name = str(self.newName.text())
        if not new_name:
            return error('New name is empty.')

        # Solve naming conflicts by first naming everything foo#.
        for n in self._nodes:
            rename(n, 'foo#')

        if not new_name.count('%'):
            new_name += '%d'
        for i, n in enumerate(self._nodes):
            self.rename(n, new_name % (i + 1))
Exemplo n.º 5
0
	def on_runButton_clicked(self):
		self._nodes = self.get_affected_nodes()
		if not self._nodes:
			return error('No affected nodes to manipulate.')
		
		# Filter-out shape nodes from the list, but only if their
		# parents are also in the list, because they will get renamed
		# automatically.
		for n in [n for n in ls(self._nodes, geometry=True) \
			if n.getParent(1) in self._nodes]:
			del self._nodes[self._nodes.index(n)]
		
		undoInfo(openChunk=True)
		if self.searchReplaceRadio.isChecked():
			self.search_replace_names()
		else:
			self.assign_new_names()
		undoInfo(closeChunk=True)
		
		self.display_renamed_nodes()
Exemplo n.º 6
0
    def on_runButton_clicked(self):
        self._nodes = self.get_affected_nodes()
        if not self._nodes:
            return error('No affected nodes to manipulate.')

        # Filter-out shape nodes from the list, but only if their
        # parents are also in the list, because they will get renamed
        # automatically.
        for n in [n for n in ls(self._nodes, geometry=True) \
         if n.getParent(1) in self._nodes]:
            del self._nodes[self._nodes.index(n)]

        undoInfo(openChunk=True)
        if self.searchReplaceRadio.isChecked():
            self.search_replace_names()
        else:
            self.assign_new_names()
        undoInfo(closeChunk=True)

        self.display_renamed_nodes()
Exemplo n.º 7
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.º 8
0
 def on_renumBy_valueChanged(self, value):
     if self.renumBy.value() == 0:
         self.renumBy.setValue(1)
         error('"By frame" cannot be equal to zero.')
     self.fix_format()
Exemplo n.º 9
0
    def export_skin_weights(self):

        format, ext = str(self.format.text()), str(self.formatExt.text())
        format = self.name_pat.sub( \
         lambda m: '%(name)' + m.group(1)[1:], format)
        path = Path(self.path.text())

        # Validate selection.
        sel = selected()
        if not sel:
            error('Selection is empty.')

        # Find the skin cluster.
        sc = mel.findRelatedSkinCluster(sel[0])
        skin_cluster = None
        for s in sel:
            sc = mel.findRelatedSkinCluster(s)
            if sc:
                skin_cluster = ls(sc)[0]
                break
        if not skin_cluster:
            error('No skin cluster found.')

        for mesh in sel:

            mesh_element = Element('Mesh', name=mesh)
            xml_tree = ElementTree(mesh_element)

            sc = mel.findRelatedSkinCluster(mesh)
            if not sc: continue
            sc = ls(sc)[0]

            influences = sc.influenceObjects()
            inf_tag = SubElement(mesh_element, 'Influences')
            for i, inf in enumerate(influences):
                SubElement(inf_tag, 'Influence', index=str(i), name=inf)
            #joints = ls(ios, type='joint')
            #if len(joints) < len(ios):
            #	error('Remove non-joint influences before exporting to Massive.')

            # TODO: progress bar

            name = format % dict(name=mesh.name().replace('|', '') \
             .replace(':', '.')) + ext
            with open(path / name, 'w') as f:

                #f.write(os.linesep + '# influences')
                #for i, inf in enumerate(ios):
                #	if inf in influences:
                #		inf_index = influences.index(j)
                #	else:
                #		influences += (inf,)
                #		inf_index = len(influences)
                #f.write('%sdeformer %d %s' % (os.linesep, i, inf))

                #f.write(os.linesep)

                vertices = SubElement(mesh_element, 'Vertices')

                #f.write(os.linesep + '# weights')
                for i, vtx in enumerate(mesh.vtx):
                    vertex = SubElement(vertices,
                                        'Vertex',
                                        pos=str(vtx.getPosition()))
                    #f.write('%s%d: ' % (os.linesep, vi))
                    for ii, inf in enumerate(influences):
                        weight_val = skinPercent(sc,
                                                 '%s.vtx[%d]' % (mesh, i),
                                                 transform=inf,
                                                 query=True)
                        if weight_val:
                            SubElement(vertex,
                                       'Weight',
                                       influence=str(ii),
                                       value=str(weight_val))
                            #f.write(' %d %f' % (ii, weight_val))

                #f.write(os.linesep + ':')
                rough_string = tostring(xml_tree.getroot(), 'utf-8')
                reparsed = minidom.parseString(rough_string)
                f.write(reparsed.toprettyxml(indent='\t'))
Exemplo n.º 10
0
    def export_camera(self):

        start, end = self.start.value(), self.end.value()
        path = Path(self.path.text())

        # Validate the selection.
        sel = ls(selection=True, dagObjects=True, cameras=True)
        if not ls(selection=True):
            return error('No cameras in selection.')

        # Associate the camera shapes with their parents.
        cams = dict((s, s.getParent()) for s in sel)

        # Pull-out only the attributes that are checked.
        shape_atts = []
        for cb in self.cameraChannelsLayout.findChildren(QCheckBox):
            if cb.isChecked():
                [shape_atts.extend(str(cb.property(n).toString()).split('|')) \
                 for n in cb.dynamicPropertyNames() if n == 'shortName']
        cam_atts = (cb.objectName() for cb \
         in self.translation.findChildren(QCheckBox) if cb.isChecked())
        attributes = (shape_atts, cam_atts)

        # Enable any locked or non-keyable channels.
        for shape, cam in cams.items():
            for i, obj in enumerate((shape, cam)):
                for att in attributes[i]:
                    obj.attr(att).set('locked', False)
                    obj.attr(att).set('keyable', True)

        # Initialize the progress bar.
        lc = len(cams)
        self.progress_init(lc + lc * len([
            x
            for x in (self.createStandIn.isChecked(), self.oneFile.isChecked()
                      and self.oneFilePerNode.isChecked) if x
        ]))

        # Bake the keys to the camera shape.
        frame_range = self.animation.isChecked() and (start, end) or (start, )
        for shape, cam in cams.items():
            if self.aborted: return

            info('Baking keys to %s: %d-%d...' % \
             ((shape,) + frame_range))
            bakeResults(shape,
                        time=frame_range,
                        simulation=True,
                        attribute=shape_atts)
            info('%s keys %d-%d baked.' % ((shape, ) + frame_range))

            self.progress_step()

        # Disable the cycle check warning.
        cycleCheck(evaluation=False)

        # Create a null stand-in for the camera and bake keys to it.
        #mel.source('channelBoxCommand.mel')
        if self.createStandIn.isChecked():
            for cam in cams.values():
                if self.aborted: return

                stand_in = Transform(name='standInNull')
                parentConstraint(cam, stand_in, name='nullParentConstraint')
                info('Baking keys to the stand-in null...')
                bakeResults(stand_in,
                            time=frame_range,
                            shape=True,
                            simulation=True,
                            attribute=cam_atts)
                info('Null keys baked.')

                # If the camera is a child, parent it to the world.
                if cam.firstParent2():
                    cam.setParent(world=True)

                # Break existing connections between the rotate or translate
                # attributes.
                for att in cam_atts:
                    if connectionInfo(cam, isExactDestination=True):
                        disconnectAttr(
                            connectionInfo(cam, getExactDestination=True))
                        #mel.CBdeleteConnection(getExactDestination=True)

                # Constrain the camera to the null.
                parentConstraint(stand_in, cam, name='cameraParentConstraint')

                # Bake the camera translate/rotate keys.
                info('Baking keys to the camera...')
                bakeResults(cam,
                            time=frame_range,
                            disableImplicitControl=True,
                            simulation=True,
                            attribute=cam_atts)
                info('Transform keys baked.')

                self.progress_step()

        # Remove excess elements unless optimize has been disabled.
        if self.optimize.isChecked():
            info('Optimizing scene...')
            delete([s for s in ls(dagObjects=True) if s not in cams.keys() + \
             cams.values() + ls(selection=True, type='animCurve')])

        # Save-out the cameras.
        kwargs = dict(force=True,
                      constructionHistory=False,
                      channels=True,
                      constraints=False,
                      expressions=False,
                      shader=False,
                      type='mayaAscii')
        ext = str(self.formatExt.text())
        if self.oneFile.isChecked():
            if self.oneFilePerNode.isChecked():
                for cam in cams.values():
                    if self.aborted: return
                    select(cam)
                    exportSelected(path / cam.name() + ext, **kwargs)
                    self.progress_step()
            else:
                select(cams.values())
                exportSelected(path / 'camera' + ext, **kwargs)
        else:
            error('Not implemented yet. Coming soon...')
Exemplo n.º 11
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.º 12
0
	def on_renumBy_valueChanged(self, value):
		if self.renumBy.value() == 0:
			self.renumBy.setValue(1)
			error('"By frame" cannot be equal to zero.')
		self.fix_format()
Exemplo n.º 13
0
	def export_skin_weights(self):
		
		format, ext = str(self.format.text()), str(self.formatExt.text())
		format = self.name_pat.sub( \
			lambda m: '%(name)' + m.group(1)[1:], format)
		path = Path(self.path.text())
		
		# Validate selection.
		sel = selected()
		if not sel:
			error('Selection is empty.')
		
		# Find the skin cluster.
		sc = mel.findRelatedSkinCluster(sel[0])
		skin_cluster = None
		for s in sel:
			sc = mel.findRelatedSkinCluster(s)
			if sc:
				skin_cluster = ls(sc)[0]
				break
		if not skin_cluster:
			error('No skin cluster found.')
		
		for mesh in sel:
			
			mesh_element = Element('Mesh', name=mesh)
			xml_tree = ElementTree(mesh_element)
			
			sc = mel.findRelatedSkinCluster(mesh)
			if not sc: continue
			sc = ls(sc)[0]
			
			influences = sc.influenceObjects()
			inf_tag = SubElement(mesh_element, 'Influences')
			for i, inf in enumerate(influences):
				SubElement(inf_tag, 'Influence', index=str(i), name=inf)
			#joints = ls(ios, type='joint')
			#if len(joints) < len(ios):
			#	error('Remove non-joint influences before exporting to Massive.')
			
			# TODO: progress bar
			
			name = format % dict(name=mesh.name().replace('|', '') \
				.replace(':', '.')) + ext
			with open(path / name, 'w') as f:
				
				#f.write(os.linesep + '# influences')
				#for i, inf in enumerate(ios):
				#	if inf in influences:
				#		inf_index = influences.index(j)
				#	else:
				#		influences += (inf,)
				#		inf_index = len(influences)
					#f.write('%sdeformer %d %s' % (os.linesep, i, inf))
				
				#f.write(os.linesep)
				
				vertices = SubElement(mesh_element, 'Vertices')
				
				#f.write(os.linesep + '# weights')
				for i, vtx in enumerate(mesh.vtx):
					vertex = SubElement(vertices, 'Vertex', pos=str(vtx.getPosition()))
					#f.write('%s%d: ' % (os.linesep, vi))
					for ii, inf in enumerate(influences):
						weight_val = skinPercent(sc, '%s.vtx[%d]' % (mesh, i),
							transform=inf, query=True)
						if weight_val:
							SubElement(vertex, 'Weight', influence=str(ii),
								value=str(weight_val))
							#f.write(' %d %f' % (ii, weight_val))
				
				
				
				#f.write(os.linesep + ':')
				rough_string = tostring(xml_tree.getroot(), 'utf-8')
				reparsed = minidom.parseString(rough_string)
				f.write(reparsed.toprettyxml(indent='\t'))
Exemplo n.º 14
0
	def export_camera(self):
		
		start, end = self.start.value(), self.end.value()
		path = Path(self.path.text())
		
		# Validate the selection.
		sel = ls(selection=True, dagObjects=True, cameras=True)
		if not ls(selection=True):
			return error('No cameras in selection.')
		
		# Associate the camera shapes with their parents.
		cams = dict((s, s.getParent()) for s in sel)
		
		# Pull-out only the attributes that are checked.
		shape_atts = []
		for cb in self.cameraChannelsLayout.findChildren(QCheckBox):
			if cb.isChecked():
				[shape_atts.extend(str(cb.property(n).toString()).split('|')) \
					for n in cb.dynamicPropertyNames() if n == 'shortName']
		cam_atts = (cb.objectName() for cb \
			in self.translation.findChildren(QCheckBox) if cb.isChecked())
		attributes = (shape_atts, cam_atts)
		
		# Enable any locked or non-keyable channels.
		for shape, cam in cams.items():
			for i, obj in enumerate((shape, cam)):
				for att in attributes[i]:
					obj.attr(att).set('locked', False)
					obj.attr(att).set('keyable', True)
		
		# Initialize the progress bar.
		lc = len(cams)
		self.progress_init(lc + lc * len([x for x in (self.createStandIn.isChecked(),
			self.oneFile.isChecked() and self.oneFilePerNode.isChecked) if x]))
		
		# Bake the keys to the camera shape.
		frame_range = self.animation.isChecked() and (start, end) or (start,)
		for shape, cam in cams.items():
			if self.aborted: return
			
			info('Baking keys to %s: %d-%d...' % \
				((shape,) + frame_range))
			bakeResults(shape, time=frame_range, simulation=True,
				attribute=shape_atts)
			info('%s keys %d-%d baked.' % ((shape,) + frame_range))
			
			self.progress_step()
		
		# Disable the cycle check warning.
		cycleCheck(evaluation=False)
		
		# Create a null stand-in for the camera and bake keys to it.
		#mel.source('channelBoxCommand.mel')
		if self.createStandIn.isChecked():
			for cam in cams.values():
				if self.aborted: return
				
				stand_in = Transform(name='standInNull')
				parentConstraint(cam, stand_in, name='nullParentConstraint')
				info('Baking keys to the stand-in null...')
				bakeResults(stand_in, time=frame_range, shape=True,
					simulation=True, attribute=cam_atts)
				info('Null keys baked.')
				
				# If the camera is a child, parent it to the world.
				if cam.firstParent2():
					cam.setParent(world=True)
				
				# Break existing connections between the rotate or translate
				# attributes.
				for att in cam_atts:
					if connectionInfo(cam, isExactDestination=True):
						disconnectAttr(connectionInfo(cam,
							getExactDestination=True))
						#mel.CBdeleteConnection(getExactDestination=True)
				
				# Constrain the camera to the null.
				parentConstraint(stand_in, cam, name='cameraParentConstraint')
				
				# Bake the camera translate/rotate keys.
				info('Baking keys to the camera...')
				bakeResults(cam, time=frame_range, disableImplicitControl=True,
					simulation=True, attribute=cam_atts)
				info('Transform keys baked.')
				
				self.progress_step()
				
		# Remove excess elements unless optimize has been disabled.
		if self.optimize.isChecked():
			info('Optimizing scene...')
			delete([s for s in ls(dagObjects=True) if s not in cams.keys() + \
				cams.values() + ls(selection=True, type='animCurve')])
		
		# Save-out the cameras.
		kwargs = dict(force=True, constructionHistory=False, channels=True,
			constraints=False, expressions=False, shader=False,
			type='mayaAscii')
		ext = str(self.formatExt.text())
		if self.oneFile.isChecked():
			if self.oneFilePerNode.isChecked():
				for cam in cams.values():
					if self.aborted: return
					select(cam)
					exportSelected(path / cam.name() + ext, **kwargs)
					self.progress_step()
			else:
				select(cams.values())
				exportSelected(path / 'camera' + ext, **kwargs)
		else:
			error('Not implemented yet. Coming soon...')