def create_scaled_ncloth_auto(**kwargs): transforms = selected(transforms=True) kwargs['shared_transforms'] = transforms result = [ScaledNCloth(s, **kwargs) for s in selected() \ if not isinstance(s, PolyBase)] select(result) return result
def fk_ik_switch(sender, receiver, killjob): fk, ik = get_fk_ik_joints([sender, receiver]) scriptJob(kill=killjob) ik_mode = sender.attr('FkIkMode').get() if ik_mode == receiver.attr('FkIkMode').get(): # Attribute wasn't even changed. create_fk_ik_sj([sender, receiver]) return if ik_mode: snap(sender, receiver) if ik['sj'] == ik['collar']: snap(fk['collar'], ik['collar'], translate=False) ik['pvc'] = ik['h'].attr('poleVectorX').connections()[0] \ .attr('target[0].targetTranslate').connections()[0] ik['pvc'].setTranslation(calc_pv_loc(hand_joint=sender), space='world') else: # FK mode jtypes = fk['sj'] == fk['collar'] and ('collar',) or () jtypes += ('shoulder', 'elbow', 'hand') [snap(ik[jtype], fk[jtype], translate=False) for jtype in jtypes] receiver.attr('FkIkMode').set(ik_mode) select(receiver) create_fk_ik_sj([sender, receiver])
def fk_ik_switch(sender, receiver, killjob): fk, ik = get_fk_ik_joints([sender, receiver]) scriptJob(kill=killjob) ik_mode = sender.attr('FkIkMode').get() if ik_mode == receiver.attr('FkIkMode').get(): # Attribute wasn't even changed. create_fk_ik_sj([sender, receiver]) return if ik_mode: snap(sender, receiver) if ik['sj'] == ik['collar']: snap(fk['collar'], ik['collar'], translate=False) ik['pvc'] = ik['h'].attr('poleVectorX').connections()[0] \ .attr('target[0].targetTranslate').connections()[0] ik['pvc'].setTranslation(calc_pv_loc(hand_joint=sender), space='world') else: # FK mode jtypes = fk['sj'] == fk['collar'] and ('collar', ) or () jtypes += ('shoulder', 'elbow', 'hand') [snap(ik[jtype], fk[jtype], translate=False) for jtype in jtypes] receiver.attr('FkIkMode').set(ik_mode) select(receiver) create_fk_ik_sj([sender, receiver])
def on_axesToggleButton_clicked(self): undoInfo(openChunk=True) sel = selected() select(self.get_affected_joints()) toggle(localAxis=True) select(sel) undoInfo(closeChunk=True)
def on_handlesToggleButton_clicked(self): undoInfo(openChunk=True) sel = selected() select(self.get_affected_joints()) toggle(selectHandle=True) select(sel) undoInfo(closeChunk=True)
def on_orientJointsButton_clicked(self): undoInfo(openChunk=True) sel = selected() kwargs = {} if self.zeroScaleOrientCB.isChecked(): kwargs.update({'zeroScaleOrient': True}) if self.aimAxisNoneRadio.isChecked(): val = 'none' else: for i, radio in enumerate((self.aimAxisXRadio, self.aimAxisYRadio, self.aimAxisZRadio)): if radio.isChecked(): xyz = 'xyz' if self.upAxisNoneRadio.isChecked(): val = xyz[i:] + xyz[:i] else: val = str(radio.text()).lower() for up_radio in (self.upAxisXRadio, self.upAxisYRadio, self.upAxisZRadio): if up_radio.isChecked(): val += str(up_radio.text()).lower() break for c in xyz: if c not in val: val += c break sao = self.worldUpYRadio.isChecked() and 'y' \ or self.worldUpZRadio.isChecked() and 'z' \ or upAxis(query=True, axis=True) sao += self.worldUpReverseCB.isChecked() \ and 'down' or 'up' kwargs.update({'secondaryAxisOrient': sao}) break reverse_aim = self.aimAxisReverseCB.isChecked() \ and Vector([val[1] == c for c in 'xyz']) * 180 or None reverse_up = self.upAxisReverseCB.isChecked() \ and Vector([val[0] == c for c in 'xyz']) * 180 or None for j in self.get_affected_joints(): if j.numChildren(): j.orientJoint(val, **kwargs) else: p = j.getParent() if p: delete(orientConstraint(p, j)) else: self.freeze(j, jointOrient=True) if self.zeroScaleOrientCB.isChecked(): j.zeroScaleOrient() if reverse_aim: self.tweak_joint_orientation(1, rotateAxis=reverse_aim) if reverse_up: self.tweak_joint_orientation(1, rotateAxis=reverse_up) select(sel) undoInfo(closeChunk=True)
def on_orientJointsButton_clicked(self): undoInfo(openChunk=True) sel = selected() kwargs = {} if self.zeroScaleOrientCB.isChecked(): kwargs.update({'zeroScaleOrient': True}) if self.aimAxisNoneRadio.isChecked(): val = 'none' else: for i, radio in enumerate( (self.aimAxisXRadio, self.aimAxisYRadio, self.aimAxisZRadio)): if radio.isChecked(): xyz = 'xyz' if self.upAxisNoneRadio.isChecked(): val = xyz[i:] + xyz[:i] else: val = str(radio.text()).lower() for up_radio in (self.upAxisXRadio, self.upAxisYRadio, self.upAxisZRadio): if up_radio.isChecked(): val += str(up_radio.text()).lower() break for c in xyz: if c not in val: val += c break sao = self.worldUpYRadio.isChecked() and 'y' \ or self.worldUpZRadio.isChecked() and 'z' \ or upAxis(query=True, axis=True) sao += self.worldUpReverseCB.isChecked() \ and 'down' or 'up' kwargs.update({'secondaryAxisOrient': sao}) break reverse_aim = self.aimAxisReverseCB.isChecked() \ and Vector([val[1] == c for c in 'xyz']) * 180 or None reverse_up = self.upAxisReverseCB.isChecked() \ and Vector([val[0] == c for c in 'xyz']) * 180 or None for j in self.get_affected_joints(): if j.numChildren(): j.orientJoint(val, **kwargs) else: p = j.getParent() if p: delete(orientConstraint(p, j)) else: self.freeze(j, jointOrient=True) if self.zeroScaleOrientCB.isChecked(): j.zeroScaleOrient() if reverse_aim: self.tweak_joint_orientation(1, rotateAxis=reverse_aim) if reverse_up: self.tweak_joint_orientation(1, rotateAxis=reverse_up) select(sel) undoInfo(closeChunk=True)
def create_rig_controls(shape=shapes.Plus, driven=[], **kwargs): if not driven: driven = ls(selection=True, transforms=True) assert driven, "Must supply one or more transforms to drive." assert len(driven) == len(ls(driven, transforms=True)), \ "Rig controls can only drive transforms." rcs = [RigControl(shape, d, **kwargs) for d in driven] select([rc.get_transform() for rc in rcs]) return rcs
def __new__(cls, transform, **kwargs): if not isinstance(transform, Transform): transform = transform.getParent() select(transform, replace=True) nClothCreate() shape = selected()[0] nc_xform = shape.getParent() rename(nc_xform, transform.namespace() + 'snCloth' + \ _util.capitalize(transform.name().split(':')[-1])) shape.__class__ = cls return shape
def create_shapes(shape_cls=Plus, snaps=[], **kwargs): if not snaps: snaps = ls(selection=True, transforms=True) if snaps: return [shape_cls(snap_to=s) for s in snaps] verts = [v for v in ls(selection=True, flatten=True) if isinstance(v, MeshVertex)] [verts.extend(e.connectedVertices()) for e in ls(selection=True, flatten=True) \ if isinstance(e, MeshEdge)] if verts: verts = uniquify(verts) select(verts, replace=True) transform = cluster()[1] shape = shape_cls(snap_to=transform) delete(transform) return [shape] return [shape_cls()]
def freeze(self, node, **kwargs): sel = selected() kwargs['rotate'] = kwargs.pop('r', kwargs.pop('rotate', True)) kwargs['scale'] = kwargs.pop('s', kwargs.pop('scale', True)) skip_locked = kwargs.pop('skip_locked', True) # Unparent all the joint's children to prevent any locked # attribute errors. children = dict([(c, c.listRelatives(allParents=True)) \ for c in node.getChildren(type=['transform', 'joint'])]) [c.setParent(world=True) for c in children.keys()] # Unlock any locked rotate or scale attributes, save their # values for later and set them to zero for now, so they # aren't affected by the freeze. atts = {} for rs in ('rotate', 'scale'): if not kwargs[rs]: continue for axis in 'xyz': a = node.attr(rs[0] + axis) if a.isLocked(): atts[a] = a.get() a.unlock() if skip_locked: a.set(0) # Perform the freeze. select(node) makeIdentity(apply=True, **kwargs) # Restore and lock any rotate or scale attributes that # were locked before. for a, v in atts.items(): if skip_locked: a.set(v) a.lock() # Restore children to their original parents and delete any # automatically-generated parent buffers. for c, parents in children.items(): p = c.getParent() c.setParent(parents) if p: delete(p) select(sel)
def create_shapes(shape_cls=Plus, snaps=[], **kwargs): if not snaps: snaps = ls(selection=True, transforms=True) if snaps: return [shape_cls(snap_to=s) for s in snaps] verts = [ v for v in ls(selection=True, flatten=True) if isinstance(v, MeshVertex) ] [verts.extend(e.connectedVertices()) for e in ls(selection=True, flatten=True) \ if isinstance(e, MeshEdge)] if verts: verts = uniquify(verts) select(verts, replace=True) transform = cluster()[1] shape = shape_cls(snap_to=transform) delete(transform) return [shape] return [shape_cls()]
def on_createSplineIKSystemButton_clicked(self): self.bottomWidget.show() self.topWidget.setEnabled(False) dj_chains, output_curves = (), () for root in selected(): dj_chain = (root, ) while dj_chain[-1].numChildren(): dj_chain += (dj_chain[-1].getChildren()[0], ) dj_chains += (dj_chain, ) # Assign a hair system to the driver joint chain. output_curves += ( \ curve(p=[dj.getTranslation(space='world').get() \ for dj in dj_chain]),) select(output_curves) mel.eval('assignNewHairSystem') follicle_curves = selected() hs = follicle_curves[0].getParent().getShape().attr('outHair') \ .outputs()[0] [hs.attr(x).set(0) for x in \ ('drag', 'friction', 'mass', 'gravity', 'dynamicsWeight')] hs.attr('startCurveAttract').set(0.25) for i, dj_chain in enumerate(dj_chains): oc = output_curves[i] select(dj_chain + (oc, )) SmoothBindSkin() bjs = [dj.attr('rotate').outputs()[0].attr('constraintRotateZ') \ .outputs()[0] for dj in (dj_chain[0], dj_chain[-1])] ikHandle(startJoint=bjs[0], endEffector=bjs[1], curve=oc, solver='ikSplineSolver', parentCurve=False, createCurve=False) self.topWidget.setEnabled(True) self.bottomWidget.hide()
def __init__(self, **kwargs): """ Merge all shape nodes under a single transform and trash any left-over (empty) transforms. """ shapes = [n for n in self if not isinstance(n, nt.Joint)] empty_transforms = [s.getParent() for s in shapes if not \ [sib for sib in s.getSiblings() if sib not in self]] self._transform = nt.Transform() parent(self, self._transform, relative=True, shape=True) #if empty_transforms: # print('empty transforms:', empty_transforms) # delete(empty_transforms) select(self) DeleteHistory() snap_to = kwargs.pop('st', kwargs.pop('snap_to', None)) if snap_to: snap(self._transform, snap_to)
def on_createSplineIKSystemButton_clicked(self): self.bottomWidget.show() self.topWidget.setEnabled(False) dj_chains, output_curves = (), () for root in selected(): dj_chain = (root,) while dj_chain[-1].numChildren(): dj_chain += (dj_chain[-1].getChildren()[0],) dj_chains += (dj_chain,) # Assign a hair system to the driver joint chain. output_curves += ( \ curve(p=[dj.getTranslation(space='world').get() \ for dj in dj_chain]),) select(output_curves) mel.eval('assignNewHairSystem') follicle_curves = selected() hs = follicle_curves[0].getParent().getShape().attr('outHair') \ .outputs()[0] [hs.attr(x).set(0) for x in \ ('drag', 'friction', 'mass', 'gravity', 'dynamicsWeight')] hs.attr('startCurveAttract').set(0.25) for i, dj_chain in enumerate(dj_chains): oc = output_curves[i] select(dj_chain + (oc,)) SmoothBindSkin() bjs = [dj.attr('rotate').outputs()[0].attr('constraintRotateZ') \ .outputs()[0] for dj in (dj_chain[0], dj_chain[-1])] ikHandle(startJoint=bjs[0], endEffector=bjs[1], curve=oc, solver='ikSplineSolver', parentCurve=False, createCurve=False) self.topWidget.setEnabled(True) self.bottomWidget.hide()
def createGizmo(self): ##All this needs to do is create a control square comprised of one transform and a bunch of shape objects parented to it. #First check to see if a gizmo exists that maybe got messed up or something. Delete that and recreate it if general.objExists("WaffleSliceGizmo"): general.delete("WaffleSliceGizmo") general.group(n = "WaffleSliceGizmo", em = True) _deleteArray = [] _shapesArray = [] _c = [] _c.append(modeling.nurbsSquare(n = "gizmoSquare1", nr = [0,0,1] ,c = [0, 0, 0], sl1 = 50, sl2 = 100)) _c.append(modeling.nurbsSquare(n = "gizmoSquare2", nr = [0,1,0] ,c = [0, 0, 0], sl1 = 100, sl2 = 50)) [general.parent(child, "WaffleSliceGizmo", r = True) for child in _c] for child in general.listRelatives("WaffleSliceGizmo", ad = True): if general.objectType(child)=="nurbsCurve": general.parent(child, "WaffleSliceGizmo", r = True, s = True) else: [general.delete(child) for child in general.listRelatives("WaffleSliceGizmo", type = "transform")] #WaffleSliceGizmo is the group that is created. Iterate through it, find a useable transform, get all the shapes, and assign #All the shapes to a transform general.delete("WaffleSliceGizmo", ch = True) general.select("WaffleSliceGizmo")
def export_mesh(self, **kwargs): format, ext = str(self.format.text()), str(self.formatExt.text()) format = self.name_pat.sub( \ lambda m: '%(name)' + m.group(1)[1:], format) format = self.frame_pat.sub( \ lambda m: '%(frame)' + m.group(1)[1:], format) path = Path(self.path.text()) if not self.animation.isChecked() and self.oneFilePerNode.isChecked(): sel = ls(selection=True) for s in sel: select(s) name = format % dict(name=s.name().replace('|', '')) + ext self.write_mesh(path, name, **kwargs) select(sel) else: end, by = self.end.value(), self.by.value() frame, renum_frame, renum_by = (self.frame, self.renum_frame, self.renum_by) info('Exporting frames... Press Esc to cancel.') self.progress_init(1) while (by > 0 and frame <= end) or (by < 0 and frame >= end): if self.aborted: return setCurrentTime(frame) if self.oneFilePerNode.isChecked(): sel = ls(selection=True) for s in sel: select(s) name = format % dict(name=s.shortName(), frame=renum_frame) + ext if not self.write_mesh(path, name): break else: name = format % dict(frame=renum_frame) + ext if not self.write_mesh(path, name, **kwargs): break # Prepare for the next iteration. frame += by renum_frame += renum_by self.export_count += 1 self.progress_step()
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...')
def on_selectButton_clicked(self): select(self.get_affected_joints())
def __init__(self, driver=shapes.Plus, driven=None, **kwargs): # Driver if not isinstance(driver, shapes.Shape) and issubclass( driver, shapes.Shape): driver = driver() assert isinstance(driver, shapes.Shape), \ ("Parameter 'driver' must be an instance or subclass of %s." % shapes.Shape.__name__) self._driver = driver self._transform = driver.get_transform() self._shapes = self._transform.getShapes() # Driven if not driven: driven = ls(selection=True, transforms=True) assert len( driven ) == 1, "Parameter 'driven' requires exactly one transform." driven = driven[0] self._driven = driven # Face Axis face_x = kwargs.pop('fx', kwargs.pop('faceX', False)) face_y = kwargs.pop('fy', kwargs.pop('faceY', False)) face_z = kwargs.pop('fz', kwargs.pop('faceZ', False)) face_sum = sum([face_x, face_y, face_z]) if not face_sum: face_x = True face_sum = 1 else: assert face_sum == 1, "Rig control can only face one axis." rotate(self._transform, [face_z and 90 or 0, 0, face_x and -90 or 0]) select(self._transform) FreezeTransformations() # Constraints do_parent_constraint = kwargs.pop( 'pc', kwargs.pop('parentConstraint', False)) do_point_constraint = kwargs.pop('xc', kwargs.pop('pointConstraint', False)) do_orient_constraint = kwargs.pop( 'oc', kwargs.pop('orientConstraint', False)) do_scale_constraint = kwargs.pop('sc', kwargs.pop('scaleConstraint', False)) if do_parent_constraint or do_point_constraint or do_orient_constraint or \ do_scale_constraint: self._buffer = Transform() snap(self._buffer, self._driven, scale=True) select(self._buffer) parent(self._transform, self._buffer) if do_parent_constraint: parentConstraint(self._transform, self._driven) else: if do_point_constraint: pointConstraint(self._transform, self._driven) if do_orient_constraint: orientConstraint(self._transform, self._driven) if do_scale_constraint: scaleConstraint(self._transform, self._driven) elif isinstance(self._driven, Joint): # Parent the drivers directly underneath the driven joint. parent(self._driver, self._driven, relative=True, shape=True) delete(self._transform) self._transform = self._driven elif isinstance(self._driven, IkHandle): self._buffer = self._transform self._transform = self._driven snap(self._ebuffer, self._transform) parent(self._transform, self._buffer) parent(self._driver, self._transform, relative=True, shape=True) else: # Parent the drivers underneath a new buffered transform. self._buffer = self._driven parent(self._transform, self._buffer) parent(self._buffer.getShapes(), self._transform, relative=True, shape=True) # Pop the shape nodes out and back in to reorder the driven shape(s) to # the top. This way, the Outliner icons for this transform will reflect the # appropriate first-child shape node. parent(self._driver, self._buffer, relative=True, shape=True) parent(self._driver, self._transform, relative=True, shape=True) if self._buffer: select(self._transform) ResetTransformations() for trs in 'trs': for xyz in 'xyz': self._buffer.attr(trs + xyz).lock() if isinstance(self._driven, IkHandle): self.__class__ = IkRigControl self.__init__()
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...')
def saveFile(self, type=0): #So this function needs to look into the proper component folder (if it exists), find the Working folder (if it exists, if not make it) #Then save an iteration of this file. project = self.getSelectedProject() if project!="None": if windows.optionMenu("partOptionMenu", q=True, v=True)!="None": part_index = int(windows.optionMenu("partOptionMenu", q=True, v=True).split(":")[0]) - 1 part_directory, part_name, part_numname = project.modelingComponents[part_index] if os.path.isdir(part_directory): #part_name = project.modelingComponents[part_index][1] working_dir = os.path.join(part_directory, "Working") qa_dir = os.path.join(part_directory, "QA") publish_dir = os.path.join(part_directory, "Publish") if os.path.isdir(working_dir)==False: os.makedirs(working_dir) if os.path.isdir(qa_dir)==False: os.makedirs(qa_dir) if os.path.isdir(publish_dir)==False: os.makedirs(publish_dir) #If save type is 0 (which is a regular work file incremental save) #Save format: part_modeler_v001.mb if type==0: if self.username!="": files = glob.glob(working_dir+"/*") if len(files)>0: highest_num=0 for file in files: if os.path.isfile(file): filenum = int(os.path.split(file)[1].split(".")[0][-3:]) if filenum>highest_num: highest_num = filenum else: highest_num+=1 num = ("0"*max(0,3-len(str(highest_num)))+str(highest_num)) print("Num: " + num) else: num = "001" if num=="001": if windows.confirmDialog(title = "Save Part File?", message = "Save the first version of this part? You will not be prompted when saving new versions after this.", button = ['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No')=='Yes': file_name = os.path.join(working_dir , part_name + "_" + self.username + "_" + "v" + num + ".mb") system.saveAs(file_name) else: file_name = os.path.join(working_dir , part_name + "_" + self.username + "_" + "v" + num + ".mb") system.saveAs(file_name) else: windows.confirmDialog(title="No username entered.", message="Please enter a valid username to save with.",button="Dismiss") #If the save file is type 1, its a publish attempt elif type==1: if windows.confirmDialog(title = "Publish File", message = "Publish this scene file?", button = ['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No')=='Yes': file_name = os.path.join(publish_dir, part_name + "_publish.mb") if os.path.isfile(file_name): ctime = os.path.getctime(file_name) moveFolder = os.path.join(publish_dir,"_old",time.strftime("%b%d_%Y %H-%M-%S",time.localtime(ctime))) if not os.path.isdir(moveFolder): os.makedirs(moveFolder) shutil.move(file_name, moveFolder) #Save the current file, then move on to cleaning up this file in preparation for publishing current_filename = system.sceneName() system.saveAs(current_filename) #Clean up all references reference_files = [] references = general.ls(type = "reference") if len(references)>0: for reference in references: if "sharedReferenceNode"!=reference: reference_files.append(system.referenceQuery(reference, filename=True)) else: for file in reference_files: system.FileReference(pathOrRefNode = file).remove() general.select(clear = True) general.select(general.ls(geometry = True)) layerName = os.path.split(system.sceneName())[1].split("_")[0].replace(" ", "_") general.createDisplayLayer(name = layerName) system.saveAs(file_name) system.openFile(current_filename, f = True) #If its type 2, its a QA submit elif type==2: if windows.confirmDialog(title = "Submit for QA", message = "Submit this scene file for QA?", button = ['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No')=='Yes': _time = time.strftime("%b%d_%Y_%H-%M-%S", time.localtime(time.time())) file_name = os.path.join(qa_dir, part_name + "_%s_%s.mb"%(self.username,_time)) _files = glob.glob(qa_dir+"/*.mb") if len(_files)>0: found=False for i in _files: if file_name == i: found=True if windows.confirmDialog(title = "Overwrite?", message = "A QA file with this name already exists. Overwrite it?", button = ['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No')=='Yes': current_filename = system.sceneName() system.saveAs(file_name) system.saveAs(current_filename) else: _folder = os.path.join(qa_dir,os.path.split(i)[1].split(".")[0]) os.makedirs(_folder) shutil.move(i, _folder) else: if found==False: current_filename = system.sceneName() system.saveAs(file_name) system.saveAs(current_filename) else: current_filename = system.sceneName() system.saveAs(file_name) system.saveAs(current_filename) else: windows.confirmDialog(title = "Part Not Found", message = "The selected part folder cannot be found.", button=["Dismiss"])
def __init__(self, driver=shapes.Plus, driven=None, **kwargs): # Driver if not isinstance(driver, shapes.Shape) and issubclass(driver, shapes.Shape): driver = driver() assert isinstance(driver, shapes.Shape), \ ("Parameter 'driver' must be an instance or subclass of %s." % shapes.Shape.__name__) self._driver = driver self._transform = driver.get_transform() self._shapes = self._transform.getShapes() # Driven if not driven: driven = ls(selection=True, transforms=True) assert len(driven) == 1, "Parameter 'driven' requires exactly one transform." driven = driven[0] self._driven = driven # Face Axis face_x = kwargs.pop('fx', kwargs.pop('faceX', False)) face_y = kwargs.pop('fy', kwargs.pop('faceY', False)) face_z = kwargs.pop('fz', kwargs.pop('faceZ', False)) face_sum = sum([face_x, face_y, face_z]) if not face_sum: face_x = True face_sum = 1 else: assert face_sum == 1, "Rig control can only face one axis." rotate(self._transform, [face_z and 90 or 0, 0, face_x and -90 or 0]) select(self._transform) FreezeTransformations() # Constraints do_parent_constraint = kwargs.pop('pc', kwargs.pop('parentConstraint', False)) do_point_constraint = kwargs.pop('xc', kwargs.pop('pointConstraint', False)) do_orient_constraint = kwargs.pop('oc', kwargs.pop('orientConstraint', False)) do_scale_constraint = kwargs.pop('sc', kwargs.pop('scaleConstraint', False)) if do_parent_constraint or do_point_constraint or do_orient_constraint or \ do_scale_constraint: self._buffer = Transform() snap(self._buffer, self._driven, scale=True) select(self._buffer) parent(self._transform, self._buffer) if do_parent_constraint: parentConstraint(self._transform, self._driven) else: if do_point_constraint: pointConstraint(self._transform, self._driven) if do_orient_constraint: orientConstraint(self._transform, self._driven) if do_scale_constraint: scaleConstraint(self._transform, self._driven) elif isinstance(self._driven, Joint): # Parent the drivers directly underneath the driven joint. parent(self._driver, self._driven, relative=True, shape=True) delete(self._transform) self._transform = self._driven elif isinstance(self._driven, IkHandle): self._buffer = self._transform self._transform = self._driven snap(self._ebuffer, self._transform) parent(self._transform, self._buffer) parent(self._driver, self._transform, relative=True, shape=True) else: # Parent the drivers underneath a new buffered transform. self._buffer = self._driven parent(self._transform, self._buffer) parent(self._buffer.getShapes(), self._transform, relative=True, shape=True) # Pop the shape nodes out and back in to reorder the driven shape(s) to # the top. This way, the Outliner icons for this transform will reflect the # appropriate first-child shape node. parent(self._driver, self._buffer, relative=True, shape=True) parent(self._driver, self._transform, relative=True, shape=True) if self._buffer: select(self._transform) ResetTransformations() for trs in 'trs': for xyz in 'xyz': self._buffer.attr(trs + xyz).lock() if isinstance(self._driven, IkHandle): self.__class__ = IkRigControl self.__init__()