def dense_chain(**kwargs): import pymel.core.datatypes as dt joints = kwargs.get("joints", None) joints_inbetween = kwargs.get("joints_inbetween", 5) if not joints: joints = pm.ls(selection=True) joints.pop(-1) for jnt in joints: child = jnt.getChildren() pos = pm.xform(jnt, query=True, translation=True, worldSpace=True) vpos1 = dt.Vector(pos) pos = pm.xform(child[0], query=True, translation=True, worldSpace=True) vpos2 = dt.Vector(pos) vpos = vpos2 - vpos1 div_vec = vpos / (joints_inbetween + 1) out_vec = vpos1 cur_jnt = jnt for i in range(joints_inbetween): out_vec = (out_vec + div_vec) pos = [out_vec.x, out_vec.y, out_vec.z] new_jnt = pm.insertJoint(cur_jnt) pm.joint(new_jnt, edit=True, component=True, position=pos, name=str(i)) cur_jnt = new_jnt return None
def createJntTweak(mesh, jntParent, ctlParent): """Create a joint tweak Args: mesh (mesh): The object to deform with the tweak jntParent (dagNode): The parent for the new joint ctlParent (dagNode): The parent for the control. """ if not isinstance(mesh, list): mesh = [mesh] name = "_".join(jntParent.name().split("_")[:3]) # create joints jointBase = primitive.addJoint(jntParent, name + "_tweak_jnt_lvl", jntParent.getMatrix(worldSpace=True)) resetJntLocalSRT(jointBase) joint = primitive.addJoint(jointBase, name + "_tweak_jnt", jntParent.getMatrix(worldSpace=True)) resetJntLocalSRT(joint) # hiding joint base by changing the draw mode # pm.setAttr(jointBase+".drawStyle", 2) try: defSet = pm.PyNode("rig_deformers_grp") except TypeError: pm.sets(n="rig_deformers_grp") defSet = pm.PyNode("rig_deformers_grp") pm.sets(defSet, add=joint) controlType = "circle" iconBase = icon.create(ctlParent, name + "_base_tweak_ctl", ctlParent.getMatrix(worldSpace=True), 13, controlType, w=.8, ro=datatypes.Vector(0, 0, 1.5708)) attribute.addAttribute(iconBase, "isCtl", "bool", keyable=False) o_icon = icon.create(iconBase, name + "_tweak_ctl", ctlParent.getMatrix(worldSpace=True), 17, controlType, w=.5, ro=datatypes.Vector(0, 0, 1.5708)) attribute.addAttribute(o_icon, "isCtl", "bool", keyable=False) for t in [".translate", ".scale", ".rotate"]: pm.connectAttr(iconBase + t, jointBase + t) pm.connectAttr(o_icon + t, joint + t) # magic of doritos connection for m in mesh: pre_bind_matrix_connect(m, joint, jointBase)
def guideBladeIcon(parent=None, name="blade",lenX=1.0, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None): """ Create a curve with a BLADE GUIDE shape. Note: This icon is specially design for **Shifter** blade guides Args: parent (dagNode): The parent object of the newly created curve. name (str): Name of the curve. lenX (float): Width of the shape. color (int or list of float): The color in index base or RGB. m (matrix): The global transformation of the curve. pos_offset (vector): The xyz position offset of the curve from its center. rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians Returns: dagNode: The newly created icon. """ v0 = dt.Vector(0 , 0, 0) v1 = dt.Vector(lenX , 0, 0) v2 = dt.Vector(0, lenX/3, 0) points = getPointArrayWithOffset([v0, v1, v2 ], pos_offset, rot_offset) bladeIco = cur.addCurve(parent, name, points, True, 1, m) setcolor(bladeIco, color) att.setNotKeyableAttributes(bladeIco) return bladeIco
def getVectorOffsetAttribute (adjustNode, svgNode): selectedItem = cmds.optionMenuGrp('svgOffsetWindowMenu', q=True, sl=True) selectedItem -= 1; #this makes it corrispond to the correct array element. zPositionAdjusts = pm.getAttr('%s.manipulatorPositionsPP' % adjustNode ) zScaleAdjusts = pm.getAttr('%s.manipulatorScalesPP' % adjustNode ) vertsPerCharArray = pm.getAttr('%s.solidsPerCharacter' % svgNode ) if zPositionAdjusts is None: zPositionAdjusts = [dt.Vector(0.0, 0.0, 0.0)] if zScaleAdjusts is None: zScaleAdjusts = [dt.Vector(1.0, 1.0, 1.0)] if (len(zPositionAdjusts) < len(vertsPerCharArray)) or len(zPositionAdjusts) == 0: for i in range (len(zPositionAdjusts), len(vertsPerCharArray), 1): zPositionAdjusts.append(dt.Vector(0.0, 0.0, 0.0)) if (len(zScaleAdjusts) < len(vertsPerCharArray)) or len(zScaleAdjusts) == 0: for i in range (len(zScaleAdjusts), len(vertsPerCharArray), 1): zScaleAdjusts.append(dt.Vector(1.0, 1.0, 1.0)) zSliderValue = zPositionAdjusts[selectedItem].z scaleValue = zScaleAdjusts[selectedItem].z cmds.floatSliderGrp ('svgOffsetWindowZSlider', e=True, v= zSliderValue ) cmds.floatSliderGrp ('svgOffsetWindowExtrudeSlider', e=True, v= scaleValue )
def clearVectorOffsetAttributes (adjustNode, svgNode): #get the array attributs zScaleAdjusts = pm.getAttr('%s.manipulatorScalesPP' % adjustNode ) zPositionAdjusts = pm.getAttr('%s.manipulatorPositionsPP' % adjustNode ) #get the vertsPerChar array, this tells us how many array elements we need vertsPerCharArray = pm.getAttr('%s.solidsPerCharacter' % svgNode ) if zPositionAdjusts is None: zPositionAdjusts = [dt.Vector(0.0, 0.0, 0.0)] if zScaleAdjusts is None: zScaleAdjusts = [dt.Vector(0.0, 0.0, 0.0)] for i in range (0, len(zPositionAdjusts), 1): zPositionAdjusts[i] = dt.Vector(0.0, 0.0, 0.0) for i in range (0, len(zScaleAdjusts), 1): zScaleAdjusts[i] = dt.Vector(1.0, 1.0, 1.0) pm.setAttr((adjustNode+'.manipulatorPositionsPP'), zPositionAdjusts, type="vectorArray" ) pm.setAttr((adjustNode+'.manipulatorScalesPP'), zScaleAdjusts, type="vectorArray" ) cmds.floatSliderGrp ('svgOffsetWindowZSlider', e=True, v= 0.0 ) cmds.floatSliderGrp ('svgOffsetWindowExtrudeSlider', e=True, v= 1.0 )
def diamond(parent=None, name="diamond", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None): """ Create a curve with a DIAMOND shape. Args: parent (dagNode): The parent object of the newly created curve. name (str): Name of the curve. width (float): Width of the shape. height (float): Height of the shape. depth (float): Depth of the shape. color (int or list of float): The color in index base or RGB. m (matrix): The global transformation of the curve. pos_offset (vector): The xyz position offset of the curve from its center. rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians Returns: dagNode: The newly created icon. """ dlen = width * 0.5 top = dt.Vector(0,dlen,0) pp = dt.Vector(dlen,0,dlen) pN = dt.Vector(dlen,0,dlen*-1) Np = dt.Vector(dlen*-1,0,dlen) NN = dt.Vector(dlen*-1,0,dlen*-1) bottom = (0,-dlen,0) points = getPointArrayWithOffset([pp,top,pN,pp,Np,top,NN,Np,NN,pN,bottom,NN,bottom,Np,bottom,pp], pos_offset, rot_offset) node = cur.addCurve(parent, name, points, False, 1, m) setcolor(node, color) return node
def square(parent=None, name="square", width=1, depth=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None): """ Create a curve with a SQUARE shape. Args: parent (dagNode): The parent object of the newly created curve. name (str): Name of the curve. width (float): Width of the shape. depth (float): Depth of the shape. color (int or list of float): The color in index base or RGB. m (matrix): The global transformation of the curve. pos_offset (vector): The xyz position offset of the curve from its center. rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians Returns: dagNode: The newly created icon. """ lenX = width * 0.5 lenZ = depth * 0.5 v0 = dt.Vector(lenX , 0, lenZ) v1 = dt.Vector(lenX , 0, lenZ*-1) v2 = dt.Vector(lenX*-1, 0, lenZ*-1) v3 = dt.Vector(lenX*-1, 0, lenZ) points = getPointArrayWithOffset([v0, v1, v2, v3], pos_offset, rot_offset) node = cur.addCurve(parent, name, points, True, 1, m) setcolor(node, color) return node
def finalize(self): """ This runs after all the connections are made and the hierarchy is built. """ children = self.border.getChildren(type="transform") if children: bbox = pm.exactWorldBoundingBox(children) # Update border to encapsulate the ui elements border_shape = self.border.getShape() margin = self.settings["margin"] cvs = [ # BL, BR, TR, TL, BL dt.Vector(bbox[0] - margin, bbox[1] - margin, bbox[2]), dt.Vector(bbox[3] + margin, bbox[1] - margin, bbox[2]), dt.Vector(bbox[3] + margin, bbox[4] + margin, bbox[2]), dt.Vector(bbox[0] - margin, bbox[4] + margin, bbox[2]), dt.Vector(bbox[0] - margin, bbox[1] - margin, bbox[2]), ] # Set cvs and update the shape. border_shape.setCVs(cvs, "world") border_shape.updateCurve() # Run default finalize logic. super(Component, self).finalize()
def test_lra_node(self): """ Test local rotation axes node. """ # Test if aim constrain exist. self.assertIn( pmc.PyNode( "L_MAIN_op_{}" "_{}_LRA_CON_buffer_GRP_CONST".format( self.TEST_1_OP_NAME, self.TEST_1_OP_INDEX ) ), self.test_op_1.get_node_list(), ) self.test_op_0.main_op_nd.rotate.set(0, 0, 0) sub_nodes = self.test_op_0.get_sub_op_nodes_from_main_op_nd() sub_nodes[0].translate.set(10, 3, -4) lra_buffer_local_rotation = ( self.test_op_0.lra_node_buffer_grp.rotate.get() ) lra_buffer_local_rotation = datatypes.Vector( [round(value, 4) for value in lra_buffer_local_rotation] ) lra_buffer_test_rotation = datatypes.Vector([3.1108, 20.9634, 16.6992]) self.assertEqual(lra_buffer_local_rotation, lra_buffer_test_rotation)
def addLookAtControlers(self, t_root, t_look): # Tracking # Eye aim control self.center_lookat = addTransform(self.over_ctl, self.getName("center_lookat"), t_root) radius = abs(self.getBboxRadius()[0] / 1.7) if True or not self.negate: ro = datatypes.Vector(0, 0, 0) po = datatypes.Vector(0, 0, radius) + self.offset else: ro = datatypes.Vector(math.pi, 0, 0) po = datatypes.Vector(0, 0, radius * -1.0) + self.offset self.arrow_npo = addTransform(self.root, self.getName("aim_npo"), t_look) self.arrow_ctl = self.addCtl( self.arrow_npo, "aim_%s" % self.ctlName, t_look, self.color_ik, "arrow", w=1, ro=ro, po=po, ) self.addToSubGroup(self.over_ctl, self.primaryControllersGroupName) ymt_util.setKeyableAttributesDontLockVisibility(self.arrow_ctl, params=["rx", "ry", "rz"])
def addObjects(self): self.root = self.add2DRoot() vTemp = transform.getOffsetPosition(self.root, [0, 0, 1]) self.sizeRef = self.addLoc("sizeRef", self.root, vTemp) pm.delete(self.sizeRef.getShapes()) attribute.lockAttribute(self.sizeRef) # Now we need to show the range of the controls with # template curves. arrow_curves = [ self.addTCurve(self.getName("up"), datatypes.Vector(0, 0, 0), self.root), self.addTCurve(self.getName("right"), datatypes.Vector(0, 0, -90), self.root), self.addTCurve(self.getName("down"), datatypes.Vector(0, 0, 180), self.root), self.addTCurve(self.getName("left"), datatypes.Vector(0, 0, 90), self.root) ] for [arrow_curve, param] in zip(arrow_curves, ["ty_positive", "tx_positive", "ty_negative", "tx_negative"]): sh = arrow_curve.getShape() sh.template.set(1) self.root.attr(param) >> sh.visibility self.root.addChild(sh, add=True, shape=True) pm.delete(arrow_curves)
def move_to_transform(obj, target, upVector=dt.Vector(0, 1, 0)): ''' Moves an inputed object to a target position. Orients to the upVector of the target. :param obj: The obj transform to transformed :param target: The target transform :param upVector: The local up vector of the target ''' # The world up vector worldUp = dt.Vector(0, 1, 0) # The Transformation matrix of the target in world space if target: targetSpace = target.getMatrix(worldSpace=True) else: targetSpace = dt.Matrix() # The input upVector transformed into target rotation space targetUp = upVector.rotateBy(targetSpace) # Create a Quaternion to represent the rotation # From the object orientation to the target orientation rotation = worldUp.rotateTo(targetUp) # Transform the object into the target space obj.setMatrix(targetSpace, worldSpace=True) obj.setRotation(rotation, space='world')
def CurveLoft(crv, geom, size, norDir, nm): try: crvSh = crv.listRelatives(s=1, type='nurbsCurve')[0] except: pm.warning('%s is not nurbsCurve') return tmpOC = pm.createNode('nearestPointOnCurve', n='TmpOC') crv.ws >> tmpOC.inputCurve copyCrvA = crv.duplicate(n='%sCopyACrv' % crv.name().replace('Crv', ''))[0] copyCrvB = crv.duplicate(n='%sCopyBCrv' % crv.name().replace('Crv', ''))[0] cvSz = int(crv.spans.get()) if crv.d.get() == 3: cvSz = cvSz + 3 upvec = dt.Vector(int(norDir[0]), int(norDir[1]), int(norDir[2])) for i in xrange(cvSz): tmpOC.inPosition.set(crv.cv[i].getPosition(space='world')) tVec = pm.pointOnCurve(crv, pr=tmpOC.parameter.get(), nt=1) cVecA = dt.cross(upvec, dt.Vector(tVec)) cVecB = dt.cross(dt.Vector(tVec), upvec) pm.move(copyCrvA.cv[i], cVecA * size, r=1) pm.move(copyCrvB.cv[i], cVecB * size, r=1) geo = pm.loft(copyCrvB, copyCrvA, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=int(geom), rsn=1) mel.eval('DeleteHistory %s' % geo[0].name()) pm.delete(tmpOC, copyCrvA, copyCrvB) return geo[0]
def alignToPointsLoop(points=None, loc=None, name=None, *args): """Create space locator align to the plain define by at less 3 vertex Args: points (None or vertex list, optional): The reference vertex to align the ref locator loc (None or dagNode, optional): If none will create a new locator name (None or string, optional): Name of the new locator *args: Description Returns: TYPE: Description """ if not points: oSel = pm.selected(fl=True) checkType = "<class 'pymel.core.general.MeshVertex'>" if (not oSel or len(oSel) < 3 or str(type(oSel[0])) != checkType): pm.displayWarning("We need to select a points loop, with at " "less 3 or more points") return else: points = oSel if not loc: if not name: name = "axisCenterRef" loc = pm.spaceLocator(n=name) oLen = len(points) wPos = [0, 0, 0] for x in points: pos = x.getPosition(space="world") wPos[0] += pos[0] wPos[1] += pos[1] wPos[2] += pos[2] centerPosition = datatypes.Vector([wPos[0] / oLen, wPos[1] / oLen, wPos[2] / oLen]) lookat = datatypes.Vector(points[0].getPosition(space="world")) # NORMAL a = lookat - centerPosition a.normalize() nextV = datatypes.Vector(points[1].getPosition(space="world")) b = nextV - centerPosition b.normalize() normal = pmu.cross(b, a) normal.normalize() trans = transform.getTransformLookingAt( centerPosition, lookat, normal, axis="xy", negate=False) loc.setTransformation(trans)
def addObjects(self): """Add all the objects needed to create the component.""" t = self.guide.tra["root"] if self.settings["mirrorBehaviour"] and self.negate: scl = [1, 1, -1] else: scl = [1, 1, 1] t = transform.setMatrixScale(t, scl) # The border needs to fit the ctl range of motion size = self.settings["ctlSize"] minX = -1 if self.settings["tx_negative"] else 0 maxX = 1 if self.settings["tx_positive"] else 0 minY = -1 if self.settings["ty_negative"] else 0 maxY = 1 if self.settings["ty_positive"] else 0 margin = 0.1 * self.size border_offset = dt.Point(minX + maxX, minY + maxY) * 0.5 self.border = self.addCtl(self.root, "border", t, self.color_ik, "square", w=size + (maxX - minX) + margin, d=size + (maxY - minY) + margin, tp=self.parentCtlTag, po=border_offset, ro=dt.Vector(math.radians(90), 0, 0)) border_shape = self.border.getShape() border_shape.overrideDisplayType.set(2) # Set display to reference self.ctl = self.addCtl(self.border, "ctl", t, self.color_ik, self.settings["icon"], d=size, h=size, w=size, tp=self.parentCtlTag, ro=dt.Vector(math.radians(90), 0, 0)) self.border.scale.set([self.size, self.size, self.size]) params = [ s for s in ["tx", "ty"] if self.settings[s + "_negative"] or self.settings[s + "_positive"] ] attribute.setKeyableAttributes(self.ctl, params) attribute.setKeyableAttributes(self.border, []) tx_limit = [minX, maxX] ty_limit = [minY, maxY] pm.transformLimits(self.ctl, tx=tx_limit, etx=[1, 1]) pm.transformLimits(self.ctl, ty=ty_limit, ety=[1, 1])
def get_dot(pos, upos, utang): """returns dot of vector from given position to curve's u position with its tangent """ vec = (dt.Vector(pos) - dt.Vector(upos)) dot = dt.Vector(utang).dot(vec.normal()) dist = vec.length() return dot, dist
def test_relativeMove(self): cube = pm.polyCube()[0] pm.move(1, 0, 0, xyz=True, r=1) self.assertEqual(cube.getTranslation(), dt.Vector(1, 0, 0)) pm.move(0, 1, 0, xyz=True, r=1) self.assertEqual(cube.getTranslation(), dt.Vector(1, 1, 0)) pm.move(0, 0, 1, xyz=True, r=1) self.assertEqual(cube.getTranslation(), dt.Vector(1, 1, 1))
def bdGetEyelidJntAngle(self, lidJnt): lidJntEnd = pm.listRelatives(lidJnt, c=True,type='joint',f=True)[0] startVectorUpperMid = dt.Vector(lidJnt.getRotatePivot(space = 'world')) endVectorUpperMid = dt.Vector(lidJntEnd.getRotatePivot(space = 'world')) diff = endVectorUpperMid - startVectorUpperMid angle = 90 - math.degrees(math.acos(diff.normal().y)) return angle
def getMatches(self): self.R_list = {} self.L_list = {} self.R_matches = {} self.L_matches = {} self.C_matches = {} self.N_matches = {} self.L_Rotation = {} self.R_Rotation = {} crv_list = pm.ls(ni=1, type="nurbsCurve") for crv in crv_list: transform = crv.getParent() if not transform.listAttr(k=1) or transform.listConnections( d=0, c=1, type="constraint"): continue pos = transform.getRotatePivot(space="world") attr = pos[self.axis] if attr > self.thersold: self.R_list[transform] = pos elif attr < -self.thersold: self.L_list[transform] = pos else: self.C_matches[transform] = pos for R_ctrl, R_pos in self.R_list.items(): L_ctrl = self.findNameMatchCtrl(R_ctrl) if L_ctrl: self.R_matches[R_ctrl] = L_ctrl self.L_matches[L_ctrl] = R_ctrl self.L_Rotation[L_ctrl] = dt.Vector( L_ctrl.getRotation(space="world")) self.R_Rotation[R_ctrl] = dt.Vector( R_ctrl.getRotation(space="world")) continue R_pos = self.negativeAxis(R_pos) R_end = R_ctrl.split("_")[-1] for L_ctrl, L_pos in self.L_list.items(): if (R_pos - L_pos).length() < self.thersold: if R_end == L_ctrl.split("_")[-1]: self.R_matches[R_ctrl] = L_ctrl self.L_matches[L_ctrl] = R_ctrl self.L_Rotation[L_ctrl] = dt.Vector( L_ctrl.getRotation(space="world")) self.R_Rotation[R_ctrl] = dt.Vector( R_ctrl.getRotation(space="world")) break else: self.N_matches[R_ctrl] = R_pos self.updateList()
def addObjects(self): po = dt.Vector(self.settings["ctlOffsetPosX"], self.settings["ctlOffsetPosY"], self.settings["ctlOffsetPosZ"]) so = dt.Vector(self.settings["ctlOffsetSclX"], self.settings["ctlOffsetSclY"], self.settings["ctlOffsetSclZ"]) ro = [ self.settings["ctlOffsetRotX"], self.settings["ctlOffsetRotY"], self.settings["ctlOffsetRotZ"] ] ro = set(map(lambda x: math.radians(x), ro)) ro = dt.Vector(*ro) self.normal = self.guide.blades["blade"].z * -1 self.binormal = self.guide.blades["blade"].x self.length0 = vec.getDistance(self.guide.apos[0], self.guide.apos[1]) t = tra.getTransformLookingAt(self.guide.apos[0], self.guide.apos[1], self.normal, axis="xy", negate=self.negate) self.ctl_npo = pri.addTransform(self.root, self.getName("ctl_npo"), t) self.ctl = self.addCtl( self.ctl_npo, "ctl", t, self.color_fk, "cube", w=(self.length0 * so.x), h=(self.size * .1 * so.y), d=(self.size * .1 * so.z), po=(dt.Vector(.5 * self.length0 * self.n_factor, 0, 0) + po)) t = tra.getTransformFromPos(self.guide.apos[0]) self.orbit_ref1 = pri.addTransform(self.root, self.getName("orbit_ref1"), t) t = tra.getTransformFromPos(self.guide.apos[1]) self.orbit_ref2 = pri.addTransform(self.root, self.getName("orbit_ref2"), t) self.orbit_cns = pri.addTransform(self.ctl, self.getName("orbit_cns"), t) self.orbit_npo = pri.addTransform(self.orbit_cns, self.getName("orbit_npo"), t) self.orbit_ctl = self.addCtl(self.orbit_npo, "orbit_ctl", t, self.color_fk, "sphere", w=self.length0 / 4) self.jnt_pos.append([self.ctl, "shoulder"])
def createPairs(src_vtx, dest_vtx, dist): pairs = {} for src in src_vtx: src_pos_v = dt.Vector(src.getPosition(space='world')) for dest in dest_vtx: dest_pos_v = dt.Vector(dest.getPosition(space='world')) if (dest_pos_v - src_pos_v).length() < dist: pairs[src] = dest return pairs
def mk_xform(vtx_X, vtx_Z, local_origin): X_axis = dt.Vector(vtx_X.getPosition('object')) - local_origin Z_axis = dt.Vector(vtx_Z.getPosition('object')) - local_origin Y_axis = dt.cross(Z_axis, X_axis) # Cross product gets the Y X_axis = dt.cross( Y_axis, Z_axis ) # X is recalculated for perfect orthogonality. X gets the least respect in this method. return dt.Matrix(X_axis.normal(), Y_axis.normal(), Z_axis.normal(), local_origin) # Scale / shear is tossed out here.
def guideBladeIcon(parent=None, name="blade", lenX=1.0, color=[0, 0, 0], m=datatypes.Matrix(), pos_offset=None, rot_offset=None): """Create a curve with a BLADE GUIDE shape. Note: This icon is specially design for **Shifter** blade guides Arguments: parent (dagNode): The parent object of the newly created curve. name (str): Name of the curve. lenX (float): Width of the shape. color (int or list of float): The color in index base or RGB. m (matrix): The global transformation of the curve. pos_offset (vector): The xyz position offset of the curve from its center. rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians Returns: dagNode: The newly created icon. """ v0 = datatypes.Vector(0, 0, 0) v1 = datatypes.Vector(lenX / 2, 0, 0) v2 = datatypes.Vector(lenX, lenX / 4, 0) v3 = datatypes.Vector(lenX / 2, lenX / 2, 0) v4 = datatypes.Vector(0, lenX / 2, 0) points = getPointArrayWithOffset([v0, v1, v2, v3, v4], pos_offset, rot_offset) bladeIco = curve.addCurve(parent, name, points, True, 1, m) setcolor(bladeIco, color) attribute.setNotKeyableAttributes(bladeIco) attribute.unlockAttribute(bladeIco, attributes=[ "tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz", "v", "ro" ]) # bladeIco.scale.set(1, 1, 1) # Set the control shapes isHistoricallyInteresting for oShape in bladeIco.getShapes(): oShape.isHistoricallyInteresting.set(False) return bladeIco
def Interpolate2Jnts(firstJnt=None, secondJnt=None, numOfNewJnts=4): if firstJnt == None or secondJnt == None: firstJnt, secondJnt = pm.ls(sl=True) newJnts = [] if numOfNewJnts <= 0: pm.warning("number of new joints must be bigger than zero.") return newJnts else: if (pm.objectType(firstJnt) == 'joint' and pm.objectType(secondJnt) == 'joint'): firstChildJnt = firstJnt.getChildren()[0] secondChildJnt = secondJnt.getChildren()[0] # find start and end pose of 2 curves crv1CV1Pos = dt.Vector(pm.xform(firstJnt, q=True, ws=True, t=True)) crv1CV2Pos = dt.Vector( pm.xform(firstChildJnt, q=True, ws=True, t=True)) crv2CV1Pos = dt.Vector(pm.xform(secondJnt, q=True, ws=True, t=True)) crv2CV2Pos = dt.Vector( pm.xform(secondChildJnt, q=True, ws=True, t=True)) # create a vector representing each curve crv1Vec = crv1CV2Pos - crv1CV1Pos crv2Vec = crv2CV2Pos - crv2CV1Pos start1ToStart2 = crv2CV1Pos - crv1CV1Pos end1ToEnd1 = crv2CV2Pos - crv1CV2Pos # find segment's length startSegLen = start1ToStart2.length() / (numOfNewJnts + 1) endSegLen = end1ToEnd1.length() / (numOfNewJnts + 1) # find start and end points for new curves and creating them for i in range(1, numOfNewJnts + 1): tmpStart = crv1CV1Pos + (start1ToStart2.normal() * startSegLen * i) tmpEnd = crv1CV2Pos + (end1ToEnd1.normal() * endSegLen * i) pm.select(clear=True) newJnts.append(pm.joint(p=tmpStart)) newJnts.append(pm.joint(p=tmpEnd)) pm.joint(newJnts, e=True, zso=True, oj="xzy", sao="yup", ch=True) return newJnts else: pm.error("interpolate2Jnts command needs 2 sets of joints.")
def buildChains(self, start, end, segments): startPos = start.getTranslation(space='world') startPosVector = dt.Vector(startPos) endPos = end.getTranslation(space='world') endPosVector = dt.Vector(endPos) totalLength = (endPosVector - startPosVector).length() print totalLength pm.select(clear=True) startJoint = pm.joint(p=startPos) endJoint = pm.joint(p=endPos) pm.joint(startJoint, e=True, zso=True, oj='xyz', sao='yup')
def get_distance_between_two_objects(): """use rotation pivot to get the position since frozen transforms will affect where the object is """ sel = pm.ls(sl=True) if len(sel) == 2: position1 = pm.xform(sel[0], query=True, worldSpace=True, rotatePivot=True) position2 = pm.xform(sel[1], query=True, worldSpace=True, rotatePivot=True) v1, v2 = dt.Vector(position1), dt.Vector(position2) print('Distance between {} and {}: {}'.format(sel[0], sel[1], dt.Vector(abs(v1 - v2)).length())), else: pm.warning('[get_distance] Select 2 objects.'),
def alignToPointsLoop(points=None, loc=None, name=None, *args): """ Create space locator align to the plain define by at less 3 vertex """ if not points: oSel = pm.selected(fl=True) if not oSel or len(oSel) < 3 or str(type( oSel[0])) != "<class 'pymel.core.general.MeshVertex'>": pm.displayWarning( "We need to select a points loop, with at less 3 or more points" ) return else: points = oSel if not loc: if not name: name = "axisCenterRef" loc = pm.spaceLocator(n=name) oLen = len(points) wPos = [0, 0, 0] for x in points: pos = x.getPosition(space="world") wPos[0] += pos[0] wPos[1] += pos[1] wPos[2] += pos[2] centerPosition = dt.Vector( [wPos[0] / oLen, wPos[1] / oLen, wPos[2] / oLen]) lookat = dt.Vector(points[0].getPosition(space="world")) # NORMAL a = lookat - centerPosition a.normalize() nextV = dt.Vector(points[1].getPosition(space="world")) b = nextV - centerPosition b.normalize() normal = pmu.cross(b, a) normal.normalize() trans = tra.getTransformLookingAt(centerPosition, lookat, normal, axis="xy", negate=False) loc.setTransformation(trans)
def setBasis(self): self.transform.centerPivots(val=True) self.originalPivots = self.transform.getPivots() if self.originalPivots[0] != self.originalPivots[1]: self.warning( 'RotationPivot and scalePivot are different. RotationPivot is used.' ) v1 = dt.Vector(self.shape.vtx[0].getPosition() - self.shape.vtx[1].getPosition()) vtemp = dt.Vector(self.shape.vtx[1].getPosition() - self.shape.vtx[2].getPosition()) v2 = v1.cross(vtemp) v3 = v1.cross(v2) self.basis = [v1, v2, v3, self.originalPivots[0]]
def addLengthCtrl(self, crv): t = getTransform(self.guide.root) t = self._getTransformWithRollByBlade(t) cvs = crv.length() tm = datatypes.TransformationMatrix(t) tm.addTranslation([0.0, cvs * 0.01, cvs * 1.4], om.MSpace.kObject) local_t = datatypes.Matrix(tm) self.length_npo = addTransform(self.aim_npo, self.getName("length_npo"), local_t) self.length_in = addTransform(self.length_npo, self.getName("sacle_in"), local_t) size = self.size w = size h = size d = size self.length_ctl = self.addCtl( self.length_in, "length_ctl", local_t, self.color_ik, "arrow", w=w, h=h, d=d, ro=datatypes.Vector([-math.pi / 2., math.pi / 2., 0.]) ) self.fk_upvectors = [] chain = getChainTransform2(self.guide.apos, self.normal, self.negate) for i, t in enumerate(chain): upv_npo = addTransform(self.length_in, self.getName("%s_fkupv_npo" % i), t) self.fk_upvectors.append(upv_npo) # global input self.scale_npo = addTransform(self.root, self.getName("scale_npo"), local_t) self.scale_in = addTransform(self.scale_npo, self.getName("sacle_in"), local_t) self.scale_ctl = self.addCtl( self.scale_in, "scale_ctl", local_t, self.color_ik, "cube", w=w*.2, h=h*.2, d=d*.2, ro=datatypes.Vector([-math.pi / 2., 0., 0.]) ) ymt_util.setKeyableAttributesDontLockVisibility(self.scale_ctl, self.s_params) ymt_util.setKeyableAttributesDontLockVisibility(self.length_ctl, ["tx", "ty", "tz"])
def circle(parent=None, name="circle", width=1, color=[0,0,0], m=dt.Matrix(), pos_offset=None, rot_offset=None): """ Create a curve with a CIRCLE shape. Args: parent (dagNode): The parent object of the newly created curve. name (str): Name of the curve. width (float): Width of the shape. color (int or list of float): The color in index base or RGB. m (matrix): The global transformation of the curve. pos_offset (vector): The xyz position offset of the curve from its center. rot_offset (vector): The xyz rotation offset of the curve from its center. xyz in radians Returns: dagNode: The newly created icon. """ dlen = width * 0.5 v0 = dt.Vector(0, 0, -dlen * 1.108) v1 = dt.Vector(dlen * .78 , 0, -dlen * .78) v2 = dt.Vector(dlen * 1.108, 0, 0) v3 = dt.Vector(dlen * .78 , 0, dlen * .78) v4 = dt.Vector(0, 0, dlen * 1.108) v5 = dt.Vector(-dlen * .78 , 0, dlen * .78) v6 = dt.Vector(-dlen * 1.108, 0, 0) v7 = dt.Vector(-dlen * .78 , 0, -dlen * .78) points = getPointArrayWithOffset([v0, v1, v2, v3, v4, v5, v6, v7], pos_offset, rot_offset) node = cur.addCurve(parent, name, points, True, 3, m) setcolor(node, color) return node