Ejemplo n.º 1
0
    def refineSearch(self):
        for a in self.curveGrp:
            if cm.listRelatives(a, p=True):
                self.curveGrp.remove(a)
        for a in self.follicleGrp:

            cm.group(n='group_2_' + str(a), em=True, w=True)
            x1, y1, z1, x2, y2, z2 = cm.exactWorldBoundingBox(a)
            x1 = (x1 + x2) / 2
            y1 = (y1 + y2) / 2
            z1 = (z1 + z2) / 2
            x1 = abs(x1)
            y1 = abs(y1)
            z1 = abs(z1)

            for b in self.curveGrp:
                x1c, y1c, z1c, x2c, y2c, z2c = cm.exactWorldBoundingBox(b)
                x1c = abs(x1c)
                y1c = abs(y1c)
                z1c = abs(z1c)
                diffx1 = x1c - x1
                diffy1 = y1c - y1
                diffz1 = z1c - z1
                if diffx1 < self.Dist and diffx1 > -self.Dist and diffy1 < self.Dist and diffy1 > -self.Dist and diffz1 < self.Dist and diffz1 > -self.Dist:
                    if cm.listRelatives(b, p=False):
                        print b, 'has no parent'
                        cm.parent(b, 'group_2_' + str(a))
                    else:
                        pass
Ejemplo n.º 2
0
    def refineSearch(self):
        for a in self.curveGrp:
            if cm.listRelatives(a, p=True):
                self.curveGrp.remove(a)
        for a in self.follicleGrp:
                  
            cm.group(n='group_2_'+str(a), em=True, w=True)         
            x1, y1, z1, x2, y2, z2 = cm.exactWorldBoundingBox(a)  
            x1 = (x1+x2)/2
            y1 = (y1+y2)/2
            z1 = (z1+z2)/2           
            x1 = abs(x1)
            y1 = abs(y1)
            z1 = abs(z1)

            for b in self.curveGrp:
                x1c, y1c, z1c, x2c, y2c, z2c = cm.exactWorldBoundingBox(b)
                x1c = abs(x1c)
                y1c = abs(y1c)
                z1c = abs(z1c)
                diffx1=x1c-x1
                diffy1=y1c-y1
                diffz1=z1c-z1
                if diffx1<self.Dist and diffx1>-self.Dist and diffy1<self.Dist and diffy1>-self.Dist and diffz1<self.Dist and diffz1>-self.Dist:
                    if cm.listRelatives(b, p=False):
                        print b, 'has no parent'
                        cm.parent(b, 'group_2_'+str(a))
                    else: 
                        pass
Ejemplo n.º 3
0
    def search(self):
        for a in self.follicleGrp:   
            cm.group(n='group_'+str(a), em=True, w=True)  
            x1, y1, z1, x2, y2, z2 = cm.exactWorldBoundingBox(a)  
            x1 = (x1+x2)/2
            y1 = (y1+y2)/2
            z1 = (z1+z2)/2
            
            x1 = abs(x1)
            y1 = abs(y1)
            z1 = abs(z1)

            for b in self.curveGrp:
                x1c, y1c, z1c, x2c, y2c, z2c = cm.exactWorldBoundingBox(b)
                x1c = abs(x1c)
                y1c = abs(y1c)
                z1c = abs(z1c)
                diffx1=x1c-x1
                diffy1=y1c-y1
                diffz1=z1c-z1
                if diffx1<self.Dist and diffx1>-self.Dist and diffy1<self.Dist and diffy1>-self.Dist and diffz1<self.Dist and diffz1>-self.Dist:
                    if cm.listRelatives(b, p=False):
                        print b, 'Has no parent'
                        cm.parent(b, 'group_'+str(a))
        more = 0               
        for c in self.curveGrp:
            if cm.listRelatives(c, p=False):
                more = 1
        if more==1:
            self.Dist += (self.Dist*.8)
            print '***Refining search.'
            
            new.refineSearch()
Ejemplo n.º 4
0
    def search(self):
        for a in self.follicleGrp:
            cm.group(n='group_' + str(a), em=True, w=True)
            x1, y1, z1, x2, y2, z2 = cm.exactWorldBoundingBox(a)
            x1 = (x1 + x2) / 2
            y1 = (y1 + y2) / 2
            z1 = (z1 + z2) / 2

            x1 = abs(x1)
            y1 = abs(y1)
            z1 = abs(z1)

            for b in self.curveGrp:
                x1c, y1c, z1c, x2c, y2c, z2c = cm.exactWorldBoundingBox(b)
                x1c = abs(x1c)
                y1c = abs(y1c)
                z1c = abs(z1c)
                diffx1 = x1c - x1
                diffy1 = y1c - y1
                diffz1 = z1c - z1
                if diffx1 < self.Dist and diffx1 > -self.Dist and diffy1 < self.Dist and diffy1 > -self.Dist and diffz1 < self.Dist and diffz1 > -self.Dist:
                    if cm.listRelatives(b, p=False):
                        print b, 'Has no parent'
                        cm.parent(b, 'group_' + str(a))
        more = 0
        for c in self.curveGrp:
            if cm.listRelatives(c, p=False):
                more = 1
        if more == 1:
            self.Dist += (self.Dist * .8)
            print '***Refining search.'

            new.refineSearch()
Ejemplo n.º 5
0
def find_center(centerOp):
    #If the evaluation is true or 1 then the script adds all the selections to an array and
    if (centerOp == 1):
        #Find the items you want to select
        sel = cmds.ls(sl=True)
        for i in range(len(sel)):

            cmds.select(str(sel[i]))
            #Find the bounding box of the selection by using the command exactWorldBoundingBox
            bBox = cmds.exactWorldBoundingBox()

            #Use the formula (x1 + x2)/2), y, and z respectivly to find the center of the min and max points
            xPosWldLoct = ((bBox[0] + bBox[3]) / 2)
            yPosWldLoct = ((bBox[1] + bBox[4]) / 2)
            zPosWldLoct = ((bBox[2] + bBox[5]) / 2)

            #Make a locator at the found points
            cmds.select(cl=True)
            cmds.spaceLocator(p=(0, 0, 0))
            cmds.xform(t=(xPosWldLoct, yPosWldLoct, zPosWldLoct))
    #If it evaluates false or 0 then the selected objects are evaluated with one bounding box
    elif (centerOp == 0):
        #Find the bounding box of the selection by using the command exactWorldBoundingBox
        bBox = cmds.exactWorldBoundingBox()

        #Use the formula (x1 + x2)/2), y, and z respectivly to find the center of the min and max points
        xPosWldLoct = ((bBox[0] + bBox[3]) / 2)
        yPosWldLoct = ((bBox[1] + bBox[4]) / 2)
        zPosWldLoct = ((bBox[2] + bBox[5]) / 2)

        #Make a locator at the found points
        cmds.select(cl=True)
        cmds.spaceLocator(p=(0, 0, 0))
        cmds.xform(t=(xPosWldLoct, yPosWldLoct, zPosWldLoct))
Ejemplo n.º 6
0
def BBintersection(obj1, obj2):
	#derive the bounding box that is the intersection of two bounding boxes
	#coords returned as MVector
	
	BB1 = mc.exactWorldBoundingBox(obj1)
	BB2 = mc.exactWorldBoundingBox(obj2)
	
	BB1min = om.MVector(BB1[0],BB1[1],BB1[2])
	BB1max = om.MVector(BB1[3],BB1[4],BB1[5])

	BB2min = om.MVector(BB2[0],BB2[1],BB2[2])
	BB2max = om.MVector(BB2[3],BB2[4],BB2[5])	
	
	if BB1min.x >= BB2min.x: outMinX = BB1min.x
	if BB1min.x <= BB2min.x: outMinX = BB2min.x
	if BB1min.y >= BB2min.y: outMinY = BB1min.y
	if BB1min.y <= BB2min.y: outMinY = BB2min.y
	if BB1min.z >= BB2min.z: outMinZ = BB1min.z
	if BB1min.z <= BB2min.z: outMinZ = BB2min.z
	
	outMin = om.MVector(outMinX,outMinY,outMinZ)
	
	if BB1max.x <= BB2max.x: outMaxX = BB1max.x
	if BB1max.x >= BB2max.x: outMaxX = BB2max.x
	if BB1max.y <= BB2max.y: outMaxY = BB1max.y
	if BB1max.y >= BB2max.y: outMaxY = BB2max.y
	if BB1max.z <= BB2max.z: outMaxZ = BB1max.z
	if BB1max.z >= BB2max.z: outMaxZ = BB2max.z
	
	outMax = om.MVector(outMaxX,outMaxY,outMaxZ)
	
	return outMin,outMax
Ejemplo n.º 7
0
def BBintersection(obj1, obj2):
    #derive the bounding box that is the intersection of two bounding boxes
    #coords returned as MVector

    BB1 = mc.exactWorldBoundingBox(obj1)
    BB2 = mc.exactWorldBoundingBox(obj2)

    BB1min = om.MVector(BB1[0], BB1[1], BB1[2])
    BB1max = om.MVector(BB1[3], BB1[4], BB1[5])

    BB2min = om.MVector(BB2[0], BB2[1], BB2[2])
    BB2max = om.MVector(BB2[3], BB2[4], BB2[5])

    if BB1min.x >= BB2min.x: outMinX = BB1min.x
    if BB1min.x <= BB2min.x: outMinX = BB2min.x
    if BB1min.y >= BB2min.y: outMinY = BB1min.y
    if BB1min.y <= BB2min.y: outMinY = BB2min.y
    if BB1min.z >= BB2min.z: outMinZ = BB1min.z
    if BB1min.z <= BB2min.z: outMinZ = BB2min.z

    outMin = om.MVector(outMinX, outMinY, outMinZ)

    if BB1max.x <= BB2max.x: outMaxX = BB1max.x
    if BB1max.x >= BB2max.x: outMaxX = BB2max.x
    if BB1max.y <= BB2max.y: outMaxY = BB1max.y
    if BB1max.y >= BB2max.y: outMaxY = BB2max.y
    if BB1max.z <= BB2max.z: outMaxZ = BB1max.z
    if BB1max.z >= BB2max.z: outMaxZ = BB2max.z

    outMax = om.MVector(outMaxX, outMaxY, outMaxZ)

    return outMin, outMax
Ejemplo n.º 8
0
def inWorld(car):
    """Checks if the car is still in the map.
    Returns True if it is still within the bounds of the world / map."""
    bbox1 = cmds.exactWorldBoundingBox('streetMap')
    bbox2 = cmds.exactWorldBoundingBox(car)

    if (bbox2[2] >= bbox1[2] and bbox2[2] <= bbox1[5]
            or bbox2[5] >= bbox1[2] and bbox2[5] <= bbox1[5]) and (
                bbox2[0] >= bbox1[0] and bbox2[0] <= bbox1[3]
                or bbox2[3] >= bbox1[0] and bbox2[3] <= bbox1[3]):
        return True
Ejemplo n.º 9
0
def hitBuilding(car, buildingIndex):
    """Checks if the car has hit a building set.
    Returns True if collision between car and a building set is detected."""
    bbox1 = cmds.exactWorldBoundingBox(buildingList[buildingIndex])
    bbox2 = cmds.exactWorldBoundingBox(car)

    if (bbox2[2] >= bbox1[2] and bbox2[2] <= bbox1[5]
            or bbox2[5] >= bbox1[2] and bbox2[5] <= bbox1[5]) and (
                bbox2[0] >= bbox1[0] and bbox2[0] <= bbox1[3]
                or bbox2[3] >= bbox1[0] and bbox2[3] <= bbox1[3]):
        return True
Ejemplo n.º 10
0
def placeTreesInSquare(squareBbox, shaders):
    '''
    Places trees randomly in a given square.
    
    squareBbox: A list of two tuples containing the x- and z-coordinates for the
                bounding box of a square.
    shaders: A list of shaders for the tree crowns.
    On exit: A cube of the same size as the square been created and assigned a green
             shader in order to make it look like grass. Trees have created using 
             makeTree(...), and placed randomly using a dart throwing algorithm which 
             gives up after six failed attempts. Everything is united into one object
             which is returned as a tuple with the object name and the node name.             
    '''
    treeList = []
    width = squareBbox[1][0] - squareBbox[0][0]
    depth = squareBbox[1][1] - squareBbox[0][1]
    grass = cmds.polyCube(name = "grass", h = 0.3, w = width, d = depth)
    cmds.xform(grass, translation = (squareBbox[0][0] + 0.5 * width,0.15,squareBbox[0][1] + 0.5 * depth))
    cmds.sets(grass[0], edit=True, forceElement="grassMaterialGroup")
    while True:
        failCount = 0
        tree = makeTree(shaders)
        treeList.append(tree)
        bbox1 = cmds.exactWorldBoundingBox(tree[0])
        radius = (bbox1[3] - bbox1[0]) / 2.0
        coorx = random.uniform(squareBbox[0][0] + radius, squareBbox[1][0] - radius)
        coorz = random.uniform(squareBbox[0][1] + radius, squareBbox[1][1] - radius)
        cmds.xform(tree[0], translation = (coorx, 0, coorz))
        while True:
            failed = False
            for j in treeList:
                bbox1 = cmds.exactWorldBoundingBox(tree[0])
                bbox2 = cmds.exactWorldBoundingBox(j[0])
                # Check if the tree intersects with element j in treeList.
                xinters = (bbox1[0] < bbox2[3] and bbox1[0] > bbox2[0])\
                       or (bbox2[0] < bbox1[3] and bbox2[0] > bbox1[0])                
                zinters = (bbox1[2] < bbox2[5] and bbox1[2] > bbox2[2])\
                       or (bbox2[2] < bbox1[5] and bbox2[2] > bbox1[2])
                if xinters and zinters:
                    coorx = random.uniform(squareBbox[0][0] + radius, squareBbox[1][0] - radius)
                    coorz = random.uniform(squareBbox[0][1] + radius, squareBbox[1][1] - radius)
                    cmds.xform(tree[0], translation = (coorx, 0, coorz))               
                    failCount = failCount + 1
                    failed = True
                    break               
            if (failed == False) or (failCount > 5): 
                break
        if (failCount > 5) or (len(treeList) == 10):
            break
    cmds.delete(tree[0]) # Delete the last tree that was not successfully placed.         
    treeList.pop() 
    for i in treeList:
        grass = cmds.polyUnite(grass[0], i[0])
    return grass
Ejemplo n.º 11
0
def inJunction(car, juncIndex):
    """Checks bounding box of car and junction defining plane.
    Returns True if collision between car and junction is detected."""
    bbox1 = cmds.exactWorldBoundingBox(juncList[juncIndex][0])
    bbox2 = cmds.exactWorldBoundingBox(car)

    if (bbox2[2] >= bbox1[2] and bbox2[2] <= bbox1[5]
            or bbox2[5] >= bbox1[2] and bbox2[5] <= bbox1[5]) and (
                bbox2[0] >= bbox1[0] and bbox2[0] <= bbox1[3]
                or bbox2[3] >= bbox1[0] and bbox2[3] <= bbox1[3]):
        return True
Ejemplo n.º 12
0
def detectCollision(car1, car2):
    """Checks bounding box of two cars.
    Returns True if collision between car bounding boxes is detected"""
    bbox1 = cmds.exactWorldBoundingBox(car1)
    bbox2 = cmds.exactWorldBoundingBox(car2)

    if (bbox2[2] >= bbox1[2] and bbox2[2] <= bbox1[5]
            or bbox2[5] >= bbox1[2] and bbox2[5] <= bbox1[5]) and (
                bbox2[0] >= bbox1[0] and bbox2[0] <= bbox1[3]
                or bbox2[3] >= bbox1[0] and bbox2[3] <= bbox1[3]):
        return True
    else:
        return False
Ejemplo n.º 13
0
def findScaleFactor(ctrl, selection, buffer=5):
    '''Find by how much to scale the selected control to fit selection'''
    sel_bb = cmds.exactWorldBoundingBox(selection)
    ctrl_bb = cmds.exactWorldBoundingBox(ctrl)

    factorX_raw = sel_bb[3] / ctrl_bb[3]
    factorY_raw = sel_bb[4] / ctrl_bb[4]
    factorZ_raw = sel_bb[5] / ctrl_bb[5]

    factorX = buffer + factorX_raw
    factorY = buffer + factorY_raw
    factorZ = buffer + factorZ_raw

    return factorX, factorY, factorZ
Ejemplo n.º 14
0
def get_bbox_center(obj):

    shapes = mc.listRelatives(
        obj, s=True)  # obten objeto de el shape en caso de tener hijos
    cvs = []
    for shape in shapes:
        num_of_cvs = mc.getAttr(shape + ".controlPoints", size=True)
        cvs.append("{}.cv[0:{}]".format(shape, num_of_cvs - 1))

    bbmin = mc.exactWorldBoundingBox(cvs)[:3]
    bbmax = mc.exactWorldBoundingBox(cvs)[3:7]

    mid_point = [(b_max + b_min) / 2 for b_min, b_max in izip(bbmin, bbmax)]

    return mid_point
Ejemplo n.º 15
0
def initFunc(*args):
    """This function creates the locators"""

    # Get user's selection
    selection = cmds.ls(selection=True, transforms=True)

    # Create and scale locators
    data.firstLocator = cmds.spaceLocator(name="CircleLocator001")[0]
    cmds.scale(4,4,4)
    data.secondLocator = cmds.spaceLocator(name="CircleLocator002")[0]
    cmds.scale(4,4,4)
    
    # If there was a selection, use it as bounding box for locators
    if selection:
        # Get dimensions
        # exactWorldBoundingBox command returns a list of values representing the limits of the object
        # [minXCoordinate, minYCoordinate, minZCoordinate, maxXCoordinate, maxYCoordinate, maxZCoordinate]
        selectionBbox = cmds.exactWorldBoundingBox(selection)

        # Using both x's to calculate the middle point
        midX = (selectionBbox[3]+selectionBbox[0])/2.0

        # Using both y's to calculate the middle point
        midY = (selectionBbox[4]+selectionBbox[1])/2.0

        # Select and move first locator to minimum Z on bounding box
        cmds.select(data.firstLocator)
        cmds.move(midX,midY,selectionBbox[2])

        # Select and move first locator to maximum Z on bounding box
        cmds.select(data.secondLocator)
        cmds.move(midX,midY,selectionBbox[5])
Ejemplo n.º 16
0
def jntForEach():
    geolist = cmds.ls(sl=1)
    for each in geolist:
        jntname = ''
        for prfx in prefixlist:
            if prfx in each:
                jntname = each.replace(prfx, '')
                print jntname
                break
            else:
                jntname = each
        if 'jnt_' + jntname == each:
            jntname = increment(jntname)
            print jntname
        if 'geo_' in each or 'geom_' in each:
            cmds.select(cl=1)
            boxarray = cmds.exactWorldBoundingBox(each)
            jnt = cmds.joint(name='jnt_' + jntname,
                             p=((boxarray[0] + boxarray[3]) / 2,
                                (boxarray[1] + boxarray[4]) / 2,
                                (boxarray[2] + boxarray[5]) / 2))
        else:
            cmds.select(each)
            jnt = cmds.joint(name='jnt_' + jntname)
        try:
            cmds.skinCluster(each, jnt, tsb=1)
        except Exception:
            pass
Ejemplo n.º 17
0
def dropToFloor(nodes = None, offset = 0):
    #no object is selected, return error
    if not nodes:
        nodes = cmds.ls(sl = True)

    if not nodes:
        cmds.error("No object is selected")

    #for loop for each object
    for node in nodes:
        #get the bouding box
        bbox = cmds.exactWorldBoundingBox(node)

        #store minimum y value
        minValue = bbox[1]

        #get wordl coordinate of the object
        ws = cmds.xform(node, q = True, t = True, ws = True)

        #calculate the difference between the floor with offset
        distance = ws[1] - bbox[1] + float(offset)
        ws[1] = distance
        
        #move the object
        cmds.xform(node, translation = ws, ws = True)
Ejemplo n.º 18
0
def get_pos(obj):
    if pm.PyNode(obj).type() == 'camera':
        obj_pos = pm.xform(obj, q=1, t=1, ws=1)
    else:
        obj_bb = mc.exactWorldBoundingBox(obj)
        obj_pos = [mix(obj_bb[0 + x], obj_bb[3 + x]) for x in range(3)]
    return obj_pos
Ejemplo n.º 19
0
def setLocs(mesh):
  global voxelSize, cubeSize, xmin, xmax, ymin, ymax, zmin, zmax, xLocs, yLocs, zLocs
  bb = cmds.exactWorldBoundingBox(mesh)
  xmin = bb[0]
  ymin = bb[1]
  zmin = bb[2]
  xmax = bb[3]
  ymax = bb[4]
  zmax = bb[5]
  
  # make 3 arrays of ray start points, one for each axis
  xLocs = []
  yLocs = []
  zLocs = []

  fac = 1/voxelSize
  
  for y in range(int(ymin*fac), int(ymax*fac+1)):
    for z in range(int(zmin*fac), int(zmax*fac+1)):
      loc = (xmax, y*voxelSize, z*voxelSize)
      xLocs.append(loc)
  for z in range(int(zmin*fac), int(zmax*fac+1)):
    for x in range(int(xmin*fac), int(xmax*fac+1)):
      loc = (x*voxelSize, ymax, z*voxelSize)
      yLocs.append(loc)
  for x in range(int(xmin*fac), int(xmax*fac+1)):
    for y in range(int(ymin*fac), int(ymax*fac+1)):
      loc = (x*voxelSize, y*voxelSize, zmax)
      zLocs.append(loc)
Ejemplo n.º 20
0
    def animatedVoxelization(self, name, res):

        time = cmds.currentTime(q=True)
        cmds.currentTime(time, e=True, u=False)
        cmds.currentTime(time, e=True, u=True)

        cmds.showHidden(name)

        voxelGroupName = name + 'VoxelGroup'
        if cmds.objExists(voxelGroupName):
            cmds.delete(voxelGroupName)

        meshDuplicate = cmds.duplicate(name)
        cmds.makeIdentity(meshDuplicate[0],
                          a=True,
                          t=True,
                          r=True,
                          s=True,
                          n=0)
        meshBbox = cmds.exactWorldBoundingBox(meshDuplicate[0])
        cmds.delete(meshDuplicate)

        cmds.voxelMesh(name, meshBbox, res)

        cmds.hide(name)
Ejemplo n.º 21
0
def createBuilding(position, blockSize, buildingSize):
    building = cmd.polyCube(sx=1, sy=1, sz=1, w=buildingSize[0], h=buildingSize[1], d=buildingSize[2])
    buildingBlock = cmd.polyPlane(sx=1, sy=1, w=blockSize[0], h=blockSize[1])
    #lamp = cmd.pointLight(decayRate=2, intensity=50, useRayTraceShadows=True)
    #cmd.move(6,2,0, lamp)
    
    buildingRig = cmd.circle(center=[0,0,0], normal=[0,1,0], radius=10, n='buildingRig')
    cmd.addAttr(buildingRig, longName='buildingHeight', shortName='bh', defaultValue=1, minValue=1, maxValue=20, attributeType='long')
    
    bbox = cmd.exactWorldBoundingBox(building)
    cmd.xform(building, piv=[0, bbox[1], 0], ws=True)
    cmd.move(0, -bbox[1], 0, building)
    cmd.makeIdentity(building, apply=True, t=True, r=True, s=True)
    cmd.delete(building, constructionHistory=True)
    cmd.delete(buildingBlock, constructionHistory=True)
    cmd.delete(buildingRig, constructionHistory=True)
    
    buildingGroup = cmd.group(em=True, name='building_1')
    buildingRig_group = cmd.parent(buildingRig[0], buildingGroup)
    cmd.parent(building[0], buildingGroup)
    cmd.parent(buildingBlock[0], buildingGroup)
    #cmd.parent(lamp, buildingGroup)
    
    cmd.connectAttr(buildingRig_group[0]+'.bh', building[0]+'.scaleY')
    x = position[0] * blockSize[0]
    y = position[1] * blockSize[1]
    cmd.move(x, 0, y, buildingGroup)
    height = math.floor(r.uniform(1, 10))
    cmd.setAttr(buildingRig_group[0]+'.bh', height)
    cmd.setAttr(buildingRig_group[0]+'.visibility', False)    
    return buildingGroup
Ejemplo n.º 22
0
    def __init__(self, parent=None, geometry='', curve='', up_curve=''):
        """Initialization method. and set global variables

        :Keywords:
            parent : `QtGui.QWidget` or `None`
                The parent widget to embed this dialog within.
                If None do not embed this widget into another.
            geometry : `string`
                name of the last geometry selected
            curve : `string`
                name of the first curve selected
            up_curve : `string`
                name of the last curve selected
        """
        super(DuplicateGeoUI, self).__init__(parent=parent)
        self.geometry = geometry
        self._geo_height = 0
        if self.geometry:
            self._geo_height = cmds.exactWorldBoundingBox(self.geometry)[4]
        self.curve = curve
        self.up_curve = up_curve

        self.setWindowTitle('Duplicate Geo Along Curve')
        self.setModal(False)
        self.setWindowModality(QtCore.Qt.NonModal)
        self.create_widgets()
        self.build_layout()
        self.connect_buttons()
        self.pre_fill_widget()
Ejemplo n.º 23
0
    def doPress(self):

        # print "PRESS"
        self.isMouseDown = True

        am = self.activeManip()

        m = Mom()
        m.strandsSelected(
            self.helicesNames,
            (am is self.fDistanceFrontManip, am is self.fDistanceBackManip))

        self.createHelixDragMarker()
        selectedItems = cmds.ls(Mom().helixTransformName + "*", selection=True)
        bbox = cmds.exactWorldBoundingBox(selectedItems)

        cmds.setAttr(helixManip.transformName + ".scale",
                     bbox[3] - bbox[0],
                     0,
                     bbox[4] - bbox[1],
                     type="double3")

        z = 0
        if am is self.fDistanceFrontManip:
            z = bbox[5]
        elif am is self.fDistanceBackManip:
            z = bbox[2]

        self.moveHelixDragMarkerTo(
            ((bbox[0] + bbox[3]) / 2, (bbox[1] + bbox[4]) / 2, z))
        cmds.showHidden(helixManip.transformName)

        self.calculateDeltaBounds()

        return OpenMaya.kUnknownParameter
Ejemplo n.º 24
0
def convert_joint(curr_joint, group_name, root_jnt=True):
    scale_size = mc.jointDisplayScale(q=True) * 2.0

    _children = mc.listRelatives(curr_joint, c=True)
    if _children is not None:
        for node in _children:
            if mc.nodeType(node) == 'joint':
                convert_joint(node, group_name, root_jnt=False)

    parent = mc.listRelatives(curr_joint, p=True)
    if parent is None or root_jnt:
        return

    _name_ball = curr_joint + group_name + "_ball"
    new_ball = mc.sphere(n=_name_ball)

    _name_cone = curr_joint + group_name + "_joint"
    new_cone = mc.cone(p=(0, 0, 0),
                       ax=(1, 0, 0),
                       ssw=0,
                       esw=360,
                       r=0.5,
                       hr=4,
                       d=1,
                       ut=0,
                       tol=0.01,
                       s=8,
                       nsp=4,
                       ch=1,
                       n=_name_cone)
    mc.move(-1,
            0,
            0,
            _name_cone + ".scalePivot",
            _name_cone + ".rotatePivot",
            r=True)

    mc.parent(new_cone, group_name)
    mc.parent(new_ball, group_name)
    xform1 = mc.xform(curr_joint, q=True, ws=True, t=True)
    xform2 = mc.xform(parent[0], q=True, ws=True, t=True)
    dist = 0.0
    for i in range(len(xform1)):
        dist += (xform1[i] - xform2[i]) * (xform1[i] - xform2[i])
    dist = (dist**0.5) / 2.0
    mc.scale(scale_size, scale_size, scale_size, new_ball, r=True)
    bbox = mc.exactWorldBoundingBox(new_ball)
    bbox_size = ((((bbox[3] - bbox[0])**2 + (bbox[4] - bbox[1])**2 +
                   (bbox[5] - bbox[2])**2)**0.5) / 4.0) * 2.0
    mc.scale(dist, bbox_size, bbox_size, new_cone, r=True)
    mc.pointConstraint(parent[0], new_cone, weight=1)
    mc.pointConstraint(parent[0], new_ball, weight=1)
    mc.aimConstraint(curr_joint,
                     new_cone,
                     aim=(1, 0, 0),
                     u=(0, 1, 0),
                     wu=(0, 1, 0),
                     weight=1)
    create_node(group_name, new_ball[0], 'ball')
    create_node(group_name, new_cone[0], 'edge')
def createABranch(rotAxis, angle):
    global prevRot, prevPos
    '''Extract Euler angles from constructed quaternion'''
    euAngles = EulerAnglesFromAxisQuat(rotAxis, angle)

    #print toDegrees(euAngles[0])#x
    #print toDegrees(euAngles[1])#y
    #print toDegrees(euAngles[2])#z
    '''Create Cylinder'''
    branch = mc.polyCylinder(
        n='cy1', r=0.1, height=branchLength)  #axis=(dirx[0],diry[0],dirz[0]),

    #time.sleep(1)
    '''Set pivot to botton so as to rotate properly'''
    bbox = mc.exactWorldBoundingBox(branch)
    bottom = [(bbox[0] + bbox[3]) / 2, bbox[1],
              (bbox[2] + bbox[5]) / 2]  #(xmin,xmax)/2 , (zmin,zmax)/2
    #now set pivot to the bottom of the cylinder
    mc.xform(branch[0], piv=bottom, ws=True, r=True)
    cmds.refresh()
    #time.sleep(1)

    print "branchStackPos=%s" % (branchStackPos)

    #print "myposUsed=%s"%(prevPos)

    mypos = prevPos
    myrot = prevRot

    #mypos=branchStackPos.pop()
    #myrot=branchStackRot.pop()
    '''Move cylinder to the current position & the current rotation'''
    mc.xform(rotation=myrot, translation=mypos)
    cmds.refresh()
    #time.sleep(1)

    cylHeight = mc.polyCylinder(branch[0], height=True, query=True)
    '''move towards direction- push it up on the local y Axis'''
    mc.move(0, cylHeight, 0, r=True,
            os=True)  #step forward - move up in local Y
    '''Store this new branch position'''
    prevPos = mc.xform(query=True, translation=True,
                       worldSpace=True)  #keeps the previous position

    cmds.refresh()
    #time.sleep(1)
    '''Rotate and Store rotation'''
    mc.rotate(toDegrees(euAngles[0]),
              toDegrees(euAngles[1]),
              toDegrees(euAngles[2]),
              branch[0],
              r=True)  #perform relative rotation
    prevRot = mc.xform(
        query=True, rotation=True,
        worldSpace=True)  #keeps the previous rotated degree angles

    cmds.refresh()
    #time.sleep(1)

    setAngle(0)
Ejemplo n.º 26
0
def get_selection_center(selection=None):
    """Bounding box center that is."""
    selection = selection or mc.ls(selection=True, flatten=True)
    if not selection:
        raise Exception('Nothing is selected.')
    if len(selection) == 1:
        return mc.xform(selection[0],
                        query=True,
                        translation=True,
                        worldSpace=True)
    minx = miny = minz = float('inf')
    maxx = maxy = maxz = -float('inf')
    for item in selection:
        if '.' in item:
            # Components (vertex, edge, ...)
            x1, y1, z1 = mc.xform(item,
                                  query=True,
                                  translation=True,
                                  worldSpace=True)
            x2, y2, z2 = x1, y1, z1
        else:
            # Geo/transform
            x1, y1, z1, x2, y2, z2 = mc.exactWorldBoundingBox(item)
        minx = min(x1, minx)
        maxx = max(x2, maxx)
        miny = min(y1, miny)
        maxy = max(y2, maxy)
        minz = min(z1, minz)
        maxz = max(z2, maxz)
    return average([minx, maxx]), average([miny, maxy]), average([minz, maxz])
def CreateJoints():
    SelectedObject = cmds.ls(sl=True)
    for item in SelectedObject:
        bbox = cmds.exactWorldBoundingBox(calculateExactly=True)
        cmds.joint()
        cmds.parent('SelectedObject|joint', removeObject=True)
        cmds.joint()
    def create_main_controls(self):
        """
        Function that creates main rig controls
        """

        xmin, ymin, zmin, xmax, ymax, zmax = mc.exactWorldBoundingBox(
            self._geo['model'])
        a = [xmin, 0, 0]
        b = [xmax, 0, 0]
        radius = (math.sqrt(
            pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2) + pow(a[2] - b[2], 2)))

        self._root_ctrl = control.Circle('root',
                                         normal=[0, 1, 0],
                                         radius=radius,
                                         color_index=29)
        self._main_ctrl = control.Circle('main',
                                         normal=[0, 1, 0],
                                         radius=radius - 6,
                                         color_index=16)
        self._main_ctrl.translate_control_shapes(0, 1, 0)

        mc.addAttr(self._main_grp, ln='root_ctrl', at='message')
        mc.addAttr(self._main_grp, ln='main_ctrl', at='message')
        mc.setAttr(self._main_grp + '.root_ctrl', lock=False)
        mc.setAttr(self._main_grp + '.main_ctrl', lock=False)
        mc.connectAttr(self._root_ctrl.node + '.message',
                       self._main_grp + '.root_ctrl')
        mc.connectAttr(self._main_ctrl.node + '.message',
                       self._main_grp + '.main_ctrl')
Ejemplo n.º 29
0
    def Action_UnFreezeScale(self):
        maya_cmds.undoInfo(openChunk=True)
        try:
            transforms = self.window.Text_Transforms.toPlainText().strip(
            ).split('\n')
            isConsiderRot = self.window.Check_ConsiderRot.isChecked()
            selection = []
            if isConsiderRot:
                selection = maya_cmds.ls(selection=True)
                duplicates = maya_cmds.duplicate(transforms)
                for i in xrange(len(duplicates)):
                    maya_cmds.setAttr(duplicates[i] + '.rotateX', 0)
                    maya_cmds.setAttr(duplicates[i] + '.rotateY', 0)
                    maya_cmds.setAttr(duplicates[i] + '.rotateZ', 0)
            else:
                duplicates = transforms

            for i in xrange(len(transforms)):
                boundaries = maya_cmds.exactWorldBoundingBox(
                    duplicates[i], calculateExactly=True)
                maya_cmds.ToolSeq_Freeze_Apply(
                    transforms=transforms[i],
                    isScaX=True,
                    isScaY=True,
                    isScaZ=True,
                    scaX=boundaries[3] - boundaries[0],
                    scaY=boundaries[4] - boundaries[1],
                    scaZ=boundaries[5] - boundaries[2])

            if isConsiderRot:
                maya_cmds.delete(duplicates)
                maya_cmds.select(selection)
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(closeChunk=True)
    def duplicate_button( self, *args  ):
        self.original_selected_objects = cmds.ls( selection=True )

        if( len(self.original_selected_objects) == 0 ):
            print "Nothing selected"
            return 0

        elif( len(self.original_selected_objects) == 1 ):
            self.relatives = cmds.listRelatives( children=True )

            if( len(self.relatives) == 1 ):
                print "Skip combine"
                cmds.duplicate( self.original_selected_objects, name=self.original_selected_objects[0] + "_Copy" )
                cmds.delete( constructionHistory=True )
                the_parent = cmds.listRelatives( parent=True )
                if( the_parent != None ):
                    cmds.parent( self.original_selected_objects[0] + "_Copy", world=True )

            else:
                self.combine()

        else:
            self.combine()

        self.newOriginCopy = cmds.ls( selection=True )[0]
        self.bbox = cmds.exactWorldBoundingBox( self.newOriginCopy )
        cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, self.newOriginCopy + ".scalePivot", self.newOriginCopy + ".rotatePivot", absolute=True)
        cmds.move( 0, 0, 0, self.newOriginCopy, rpr=True )
        cmds.makeIdentity( apply=True, t=1, r=1, s=1 )
        cmds.delete( constructionHistory=True )
    def bulge_button( self, *args  ):
        if( cmds.objExists( "ZBend" ) ):
            cmds.confirmDialog( title="Error", message="First delete the bulge history on the previously\ndeformed object before bulging another.", button="Okie Dokie" )
            return 0

        latestSelection = cmds.ls( selection=True )
        if( len( latestSelection ) == 0 ):
            return 0

        if( len( latestSelection ) == 1 ):
            self.relatives = cmds.listRelatives( children=True )

            if( len(self.relatives) == 1 ):
                self.bbox = cmds.exactWorldBoundingBox( latestSelection )

                cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "x_bulge_slider", value=True, query=True ) )
                cmds.rename( "XBend" )
                cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "XBend", rpr=True )
                cmds.setAttr( "XBend.rotateZ", -90 )

                cmds.select( latestSelection )

                cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "z_bulge_slider", value=True, query=True ) )
                cmds.rename( "ZBend" )
                cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "ZBend", rpr=True )
                cmds.setAttr( "ZBend.rotateZ", -90 )
                cmds.setAttr( "ZBend.rotateX", 90 )
                cmds.connectControl( "x_bulge_slider", "bend1.curvature" )
                cmds.connectControl( "z_bulge_slider", "bend2.curvature" )
                cmds.select( latestSelection )
Ejemplo n.º 32
0
def trailmouth(crv, partname, jnt_up, jnt_low, smlfrn_l, smlfrn_r):
    mthbnd = cmds.exactWorldBoundingBox(crv)
    size = (mthbnd[3] - mthbnd[0]) * 1.4
    centerfortrail = [
        round(((mthbnd[3] + mthbnd[0]) / 2), 2),
        round(((mthbnd[4] + mthbnd[1]) / 2), 2),
        round(((mthbnd[5] + mthbnd[2]) / 2), 2)
    ]
    trail = 'trail_' + partname
    cmds.circle(r=size, n=trail, nrz=0, nry=1, sw=180, cx=size * 0.92)
    cmds.xform(trail, t=centerfortrail, ro=(0, 90, 0))
    cmds.circle(r=size,
                n='smlfrn_' + trail,
                nrz=0,
                nry=1,
                sw=180,
                cx=size * 0.5,
                cy=-size * 0.5)
    cmds.xform('smlfrn_' + trail, t=centerfortrail, ro=(90, 0, 90))
    cmds.duplicate(trail, n=trail + '_up')
    cmds.duplicate(trail, n=trail + '_mid')
    cmds.duplicate(trail, n=trail + '_low')
    cmds.delete(trail)
    cmds.skinCluster(jnt_up, smlfrn_l, smlfrn_r, trail + '_up', tsb=1)
    cmds.skinCluster(jnt_low, smlfrn_l, smlfrn_r, trail + '_low', tsb=1)
    cmds.skinCluster(jnt_low,
                     jnt_up,
                     smlfrn_l,
                     smlfrn_r,
                     trail + '_mid',
                     tsb=1)
Ejemplo n.º 33
0
def init():
    # create group
    _group = cmds.group(n='Group', em=True)
    cmds.group(n='geometry', em=True, parent=_group)
    _rig_group = cmds.group(n='rig', em=True, parent=_group)
    _master_group = cmds.group(n='master', em=True, parent=_rig_group)
    # create circle
    modellist = cmds.ls(type='mesh')
    if modellist:
        boxlist = cmds.exactWorldBoundingBox(modellist)
        radius = max(boxlist[3], boxlist[5])
        _main_circle = cmds.circle(n='Main', nr=(0, 1, 0), r=radius * 1.6)
        _first_circle = cmds.circle(n='First', nr=(0, 1, 0), r=radius * 1.3)
        _second_circle = cmds.circle(n='Second', nr=(0, 1, 0), r=radius)
    else:
        _main_circle = cmds.circle(n='Main', nr=(0, 1, 0), r=5)
        _first_circle = cmds.circle(n='First', nr=(0, 1, 0), r=3.8)
        _second_circle = cmds.circle(n='Second', nr=(0, 1, 0), r=2.5)
    # set circle parent
    cmds.parent(_second_circle, _first_circle)
    cmds.parent(_first_circle, _main_circle)
    cmds.parent(_main_circle, _master_group)
    # color&history
    _set_color('Main', color=(1, 0, 0))
    cmds.delete('Main', constructionHistory=True)
    _set_color('First', color=(0, 1, 0))
    _set_color('Second', color=(0, 0, 1))
    # create joint
    cmds.group(n='joint', em=True, parent=_rig_group)
    cmds.joint(n='Root_M')
    cmds.group(n='deform', em=True, parent=_rig_group)
Ejemplo n.º 34
0
    def _get_recommended_pivot_bank(self, geometries, tm_ref, tm_ref_dir, pos_toes, direction=1):
        """
        Determine recommended position using ray-cast from the toes.
        TODO: If the ray-case fail, use a specified default value.
        return: The recommended position as a world pymel.datatypes.Vector
        """
        # Sanity check, ensure that at least one point is in the bounds of geometries.
        # This can prevent rays from being fired from outside a geometry.
        # TODO: Make it more robust.
        filtered_geometries = []
        for geometry in geometries:
            xmin, ymin, zmin, xmax, ymax, zmax = cmds.exactWorldBoundingBox(geometry.__melobject__())
            bound = pymel.datatypes.BoundingBox((xmin, ymin, zmin), (xmax, ymax, zmax))
            if bound.contains(pos_toes):
                filtered_geometries.append(geometry)

        dir = pymel.datatypes.Point(direction, 0, 0) * tm_ref_dir
        pos = libRigging.ray_cast_nearest(pos_toes, dir, filtered_geometries)
        if not pos:
            cmds.warning("Can't automatically solve FootRoll bank inn pivot.")
            pos = pos_toes

        pos.y = 0

        return pos
Ejemplo n.º 35
0
def dispatchObjects():

    sel = cmds.ls(sl=True, l=True)

    Xvalues = []
    Zvalues = []

    if len(sel) <= 1:
        cmds.warning('Select at least 2 objects')

    else:
        for s in sel:
            cmds.xform(s, a=True, t=(0, 0, 0))
            bbox = cmds.exactWorldBoundingBox(s)

            Xvalues.append(abs(bbox[0]) + abs(bbox[3]))
            Zvalues.append(abs(bbox[2]) + abs(bbox[5]))

        columnIndex = int(math.sqrt(len(sel))) + 1

        moveValueX = max(Xvalues) * 1.1
        moveValueZ = max(Zvalues) * 1.1

        for s in sel:

            index = sel.index(s)
            rowIndex = int(index / columnIndex)

            cmds.xform(s,
                       a=True,
                       t=(index * moveValueX, 0, rowIndex * moveValueZ))
            cmds.xform(s,
                       r=True,
                       t=(-(rowIndex * moveValueX * columnIndex), 0, 0))
Ejemplo n.º 36
0
def center_selection():
    """Creates locator at bounding box center of objects or components

    Note:
        Uses function "convert_joint_selection_to_loc()" to "convert" any selected joints to locators temporarily.
    Joints don't work with bbox calculations accurately for this use

    Tested with transforms, joints, vertices, edges
    *Does not center locator on polygon "faces"
    """
    selection = cmds.ls(selection=True)
    if selection:
        filter_sel = convert_joint_selection_to_loc()
        if filter_sel:
            bbx = cmds.exactWorldBoundingBox(filter_sel[0])
            centerX = (bbx[0] + bbx[3]) / 2.0
            centerY = (bbx[1] + bbx[4]) / 2.0
            centerZ = (bbx[2] + bbx[5]) / 2.0
            bbox_center = [centerX, centerY, centerZ]
            loc = cmds.spaceLocator()[0]
            cmds.setAttr('{}.translate'.format(loc), *bbox_center)
            if filter_sel[1]:
                cmds.delete(filter_sel[1])
            cmds.select(loc)
            return loc
Ejemplo n.º 37
0
def exactLocalBoundingBox(*args,**keywords):

	if len(args)==0:
		args=mc.ls(sl=True)
		
	obj=args[0]
	
	r=False #relative to the rotate pivot
	
	for k in keywords:
		if k=='r' or k=='relative':
			r=keywords[k]
		if k in locals():
			exec(k+'=keywords[k]')		
	
	t,r,s=mc.getAttr(obj+'.t')[0],mc.getAttr(obj+'.r')[0],mc.getAttr(obj+'.s')[0]

	mc.setAttr(obj+'.t',0,0,0)
	mc.setAttr(obj+'.r',0,0,0)
	mc.setAttr(obj+'.s',1,1,1)
	
	if r:
		rp=mc.xform(obj,q=True,ws=True,rp=True)
		mc.xform(obj,ws=True,t=(-rp[0],-rp[1],-rp[2]))
		
	returnVal=mc.exactWorldBoundingBox(obj)
	
	mc.setAttr(obj+'.t',*t)
	mc.setAttr(obj+'.r',*r)
	mc.setAttr(obj+'.s',*s)
	
	return returnVal
Ejemplo n.º 38
0
def bounding_by_frame(frame_range=[], path=[]):
    if len(frame_range) == 2:
        if path is not None:
            path = mc.ls(path)
            boundingbox = [
                999999999, 999999999, 999999999, -999999999, -999999999,
                -999999999
            ]
            for frame in range(frame_range[0], frame_range[1] + 1):
                mc.currentTime(frame)
                temp = mc.exactWorldBoundingBox(path)
                if boundingbox[0] > temp[0]:
                    boundingbox[0] = temp[0]
                if boundingbox[1] > temp[1]:
                    boundingbox[1] = temp[1]
                if boundingbox[2] > temp[2]:
                    boundingbox[2] = temp[2]
                if boundingbox[3] < temp[3]:
                    boundingbox[3] = temp[3]
                if boundingbox[4] < temp[4]:
                    boundingbox[4] = temp[4]
                if boundingbox[5] < temp[5]:
                    boundingbox[5] = temp[5]

            return boundingbox
Ejemplo n.º 39
0
def BBoxToCurve( obj, autoParent = False ):
	bbinfo = mc.exactWorldBoundingBox( obj ) # xmin, ymin, zmin, xmax, ymax, zmax
	point1 = [bbinfo[0],bbinfo[1],bbinfo[2]]
	point2 = [bbinfo[3],bbinfo[4],bbinfo[5]]
	coords = ([point1[0], point2[1], point2[2] ],
			 point2,
			 [ point2[0], point2[1], point1[2] ],
			 [ point1[0], point2[1], point1[2] ],
			 [ point1[0], point2[1], point2[2] ],
			 [ point1[0], point1[1], point2[2] ],
			 point1,
			 [ point2[0], point1[1], point1[2] ],
			 [ point2[0], point1[1], point2[2] ],
			 [ point1[0], point1[1], point2[2] ],
			 [ point2[0], point1[1], point2[2] ],
			 point2,
			 [ point2[0], point2[1], point1[2] ],
			 [ point2[0], point1[1], point1[2] ],
			 point1,
			 [ point1[0], point2[1], point1[2] ])
	bbox = mc.curve( d = 1, p = coords, k = [ a for a in range(len(coords))], n = "cube#" )
	if autoParent:
		shape = mc.listRelatives( bbox, f = True, s = True )
		mc.select( shape, obj )
		mc.parent( add = True, shape = True )
		mc.delete( bbox )
	return bbox
 def failUnlessCubeWidthEqual(self, timeValueList):
     for time, value in timeValueList:
         MayaCmds.currentTime(time, update = True)
         bbox = MayaCmds.exactWorldBoundingBox('cube')
         width = bbox[3] - bbox[0]
         self.failUnlessAlmostEqual(
                 value, width, 3,
                 'Time: %f, Width: %f (expected) != %f' % (time, value, width))
Ejemplo n.º 41
0
def isBoundingBoxCross( firstObj, secondObj ):
    
    bboxFirst   = cmds.exactWorldBoundingBox( firstObj )
    bboxSecond  = cmds.exactWorldBoundingBox( secondObj )
    
    firstMin = bboxFirst[:3]
    firstMax = bboxFirst[3:]
    secondMin = bboxSecond[:3]
    secondMax = bboxSecond[3:]
    
    isCross = True
    for dimantion in [ [0,1], [1,2], [2,0] ]: 
        for i in dimantion:
            if firstMax[i] < secondMin[i] or firstMin[i] > secondMax[i]:
                isCross = False
                break
    return isCross
Ejemplo n.º 42
0
def make_origin_target():
    o = cmds.polySphere() # create a sphere
    cmds.select(o) # select the sphere
    bbox = cmds.exactWorldBoundingBox() # create bounding box around it
    bottom = [(bbox[0] + bbox[3])/2, bbox[1], (bbox[2] + bbox[5])/2] # define the bottom of the bounding box
    cmds.xform(piv=bottom, ws=True) # move the sphere to the bottom of the bounding box
    cmds.move(rpr=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0) # freeze transforms
Ejemplo n.º 43
0
def create_guide():
    if cmds.objExists('loc_guide_deformer'):
        cmds.delete('loc_guide_deformer')
    bound_centre = [0,0,0]
    if len(cmds.ls(sl=True)) is not 0:
        bound = cmds.exactWorldBoundingBox(cmds.ls (sl = True))
        bound_centre = [(bound[0] + bound[3])/2, (bound[1] + bound[4])/2, (bound[2] + bound[5])/2]
    cmds.spaceLocator (n="loc_guide_deformer", a = True, p = (bound_centre[0], bound_centre[1], bound_centre[2]))
    cmds.CenterPivot()
Ejemplo n.º 44
0
def run():
    """Measure the scene bounding box for geometric objects in centimeters.
     ---
     units, bounding box, center and dimensions for scene
     sceneboundingbox() -> (string, 
            float, float, float, 
            float, float, float, 
            float, float, float, 
            float, float, float)
     """
    t0 = float(time.time())
    verbose = cmds.optionVar(query='checkmateVerbosity')
    
    units = cmds.currentUnit(query=True, linear=True)
    if units != 'cm' :
        cmds.currentUnit(linear='cm')
    	#raise InvalidLinearUnits, "current linear unit is not centimeters"
    transforms = cmds.ls(transforms=True)
    geometry =   cmds.ls(geometry=True)
    try:
    	bbox = cmds.exactWorldBoundingBox(geometry) 
    except TypeError:
        return (units, 
            0, 0, 0, 
            0, 0, 0, 
            0, 0, 0, 
            0, 0, 0)
    
    (bbMinX, bbMinY, bbMinZ, 
        bbMaxX, bbMaxY, bbMaxZ) = cmds.exactWorldBoundingBox(geometry)
    width = bbMaxX - bbMinX
    height = bbMaxY - bbMinY
    depth = bbMaxZ - bbMinZ
    centerX = ( bbMaxX + bbMinX ) / 2.0
    centerY = ( bbMaxY + bbMinY ) / 2.0
    centerZ = ( bbMaxZ + bbMinZ ) / 2.0
    print '%-24s : %.6f seconds' % ('stats.bbox.run()', 
        float(time.time())-t0
    ) 
    return (units, 
            bbMinX, bbMinY, bbMinZ, 
            bbMaxX, bbMaxY, bbMaxZ, 
            centerX, centerY, centerZ, 
            width, height, depth)
Ejemplo n.º 45
0
def moveToOrigin():
    # group and move all geo to origin
    cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True), r=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    cmds.group(n='tempGroup')
    bbox = cmds.exactWorldBoundingBox()
    bottom = [(bbox[0] + bbox[3])/2, bbox[1], (bbox[2] + bbox[5])/2]
    cmds.xform(piv=bottom, ws=True)
    cmds.move(rpr=True)
    cmds.ungroup('tempGroup')
 def create_world_button( self, *args  ):
     if( cmds.objExists( "OurSampleWorld" ) ):
         return 0
     else:
         cmds.sphere( r=10, sections=40, spans=30, name="OurSampleWorld" )
         cmds.setAttr( "OurSampleWorld.scale", 9.599, 9.599, 9.599 )
         cmds.makeIdentity( apply=True, t=1, r=1, s=1 )
         self.wbbox = cmds.exactWorldBoundingBox( "OurSampleWorld" )
         cmds.move((self.wbbox[0] + self.wbbox[3])/2, self.wbbox[4], (self.wbbox[2] + self.wbbox[5])/2, "OurSampleWorld.scalePivot", "OurSampleWorld.rotatePivot", absolute=True)
         cmds.move( 0, 0, 0, "OurSampleWorld", rpr=True )
         cmds.connectControl( "world_size_slider", "OurSampleWorld.scaleX", "OurSampleWorld.scaleY", "OurSampleWorld.scaleZ" )
Ejemplo n.º 47
0
def createBirail(curveGrp) :
    
    eachCrvGrp = cmds.listRelatives(curveGrp)
    
    shapeEachCrvGrp = cmds.listRelatives(eachCrvGrp, children=True)
    meshInGrp = cmds.ls(shapeEachCrvGrp, type='mesh')
    
    if len(eachCrvGrp)>3 and len(meshInGrp)==0 :
        
        #checking if curves are in right order
        intersect1 = cmds.curveIntersect(eachCrvGrp[0], eachCrvGrp[1])
        intersect2 = cmds.curveIntersect(eachCrvGrp[0], eachCrvGrp[2])
        intersect3 = cmds.curveIntersect(eachCrvGrp[0], eachCrvGrp[3])
        curveOrder = []
        
        if str(intersect1)=='None' :
            curveOrder = [eachCrvGrp[0], eachCrvGrp[2], eachCrvGrp[1], eachCrvGrp[3]]
        elif str(intersect3)=='None' :
            curveOrder = [eachCrvGrp[0], eachCrvGrp[1], eachCrvGrp[3], eachCrvGrp[2]]
        else :
            curveOrder = eachCrvGrp
        #
                
        crv1shape = cmds.listRelatives(curveOrder[1], children=True)
        crv1spans = cmds.getAttr(crv1shape[0]+'.spans')
        crv2shape = cmds.listRelatives(curveOrder[0], children=True)
        crv2spans = cmds.getAttr(crv2shape[0]+'.spans')
        
        #creating birail
        if crv1spans<crv2spans :
            mesh = cmds.doubleProfileBirailSurface([curveOrder[1], curveOrder[3],  curveOrder[0] ,curveOrder[2]], bl =  0.5 ,tp2 =  0 , ch = True , po = 1 ,tm = 1 , tp1 = 0) 
        else :
            mesh = cmds.doubleProfileBirailSurface([curveOrder[0] ,curveOrder[2], curveOrder[1],  curveOrder[3]], bl =  0.5 ,tp2 =  0 , ch = True , po = 1 ,tm = 1 , tp1 = 0) 
    
        shape = cmds.listRelatives(mesh, children = True)[0] 
        tess = cmds.listConnections(shape + '.inMesh') 
        density = 12 
    
        bboxGrp = cmds.exactWorldBoundingBox(curveGrp)
        
        cmds.setAttr(tess[0] + '.polygonType', 1)
        cmds.setAttr(tess[0] + '.uType', 1)
        cmds.setAttr(tess[0] + '.vType', 1)
        cmds.setAttr(tess[0] + '.format', 2)
        
        #check the order of u and v for tesselation to be homogeneous
        if ((bboxGrp[3] - bboxGrp[0])*density)>((bboxGrp[4] - bboxGrp[1])*density) :
            cmds.setAttr(tess[0] + '.uNumber', int((bboxGrp[3] - bboxGrp[0])*density)) 
            cmds.setAttr(tess[0] + '.vNumber', int((bboxGrp[4] - bboxGrp[1])*density))
        else :
            cmds.setAttr(tess[0] + '.vNumber', int((bboxGrp[3] - bboxGrp[0])*density)) 
            cmds.setAttr(tess[0] + '.uNumber', int((bboxGrp[4] - bboxGrp[1])*density))
        
        cmds.parent(mesh[0], curveGrp)
Ejemplo n.º 48
0
def bbMinMaxMVector(obj):

	#returns the vector values of the BB of an object
	objBB = mc.exactWorldBoundingBox(obj)
	objBBmin = om.MVector(objBB[0],objBB[1],objBB[2])
	objBBmax = om.MVector(objBB[3],objBB[4],objBB[5])
	centre = (objBBmin + objBBmax )/2
	outmin = objBBmin - centre
	outmax = objBBmax - centre
	
	return 	outmin, outmax
Ejemplo n.º 49
0
def buildBoundingBoxGeo(objectName, noChildren, ignoreInv):
    '''
    Builds a bounding box from the selected object.
    '''

    # as a workaround to a Maya bug duplicate said object to use to evaluate the box size (I know it's messy)
    duplicatedObject = cmds.duplicate(objectName, rc=True, un=False, ic=False, n='duplicated_'+objectName)
    dupObjChildren = cmds.listRelatives(duplicatedObject, children=True, typ='transform')
    
    # unlock attributes so we can freeze the duped geo
    for piece in duplicatedObject:
        cmds.setAttr(piece+".translateX", lock=False)
        cmds.setAttr(piece+".translateY", lock=False)
        cmds.setAttr(piece+".translateZ", lock=False)
        cmds.setAttr(piece+".translate", lock=False)
        cmds.setAttr(piece+".rotateX", lock=False)
        cmds.setAttr(piece+".rotateY", lock=False)
        cmds.setAttr(piece+".rotateZ", lock=False)
        cmds.setAttr(piece+".rotate", lock=False)
        cmds.setAttr(piece+".scaleX", lock=False)
        cmds.setAttr(piece+".scaleY", lock=False)
        cmds.setAttr(piece+".scaleZ", lock=False)
        cmds.setAttr(piece+".scale", lock=False)

    
    # delete children if we want only the one object
    if noChildren:
        cmds.select(dupObjChildren, r=True)
        cmds.delete()
    
    # unparent and freeze the geo (cause maya doesn't calculate the box properly otherwise)
    if cmds.listRelatives(duplicatedObject[0], p=True):
        newName = cmds.parent(duplicatedObject[0], w=True)
    cmds.makeIdentity(duplicatedObject[0], apply=True,translate=True, rotate=True, scale=True)
    
    # get the bounding box then blow away the duped geo
    boundingBoxDims = cmds.exactWorldBoundingBox(duplicatedObject[0], ii=ignoreInv)
    cmds.delete(duplicatedObject[0])
    
    # calculate the dimensions and centre of the box
    boxWidth = boundingBoxDims[3] - boundingBoxDims[0]
    boxHeight = boundingBoxDims[4] - boundingBoxDims[1]
    boxDepth = boundingBoxDims[5] - boundingBoxDims[2]
    boxCentreX = (boxWidth/2)+boundingBoxDims[0]
    boxCentreY = (boxHeight/2)+boundingBoxDims[1]
    boxCentreZ = (boxDepth/2)+boundingBoxDims[2]
    
    # build the box and put in the right place
    cubeName = cmds.polyCube(w=boxWidth, h=boxHeight, d=boxDepth, ch=False, n=objectName+'_bBox')
    cmds.xform(cubeName, ws=True, t=(boxCentreX, boxCentreY, boxCentreZ))
    
    return cubeName
Ejemplo n.º 50
0
def cubeCell(obj,parent,mat,aPos):
	mc.setAttr(obj + '.visibility', False)
	BB = mc.exactWorldBoundingBox(obj)
	activeShard = mc.polyCube( ch = False, sx=1, sy=1, sz=1, w = ((BB[3]-BB[0])*2), h=((BB[4]-BB[1])*2), d = ((BB[5]-BB[2])*2))
	activeShard = activeShard[0]
	mc.move(aPos[0], aPos[1], aPos[2], activeShard, a = True)
	mc.setAttr(activeShard + '.visibility', True)
	mc.sets( activeShard, forceElement = ('%sSG' % (mat)),  e = True)
	dupe = mc.duplicate(obj, rr = True)
	cutShard = dupe[0]
	mc.delete (cutShard, ch = True)
	mc.setAttr(cutShard + '.visibility', True)
	return activeShard, cutShard
Ejemplo n.º 51
0
def volumeScatter(name, count):
    a=[]
    bbox = cmds.exactWorldBoundingBox(name)
    for i in range(count):
        x = random.uniform(bbox[0], bbox[3])
        y = random.uniform(bbox[1], bbox[4])
        z = random.uniform(bbox[2], bbox[5])

        newObj = cmds.polyCone()[0]
        a.append(newObj)

        cmds.move(x,y,z,newObj)
    return a
Ejemplo n.º 52
0
def createBoundingBox():
    
    for i in cmds.ls(sl=True):
        print i
        cube = cmds.polyCube()[0]
        x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(i, calculateExactly=True)
        cmds.move(x1, '%s.f[5]' % cube, x=True)
        cmds.move(y1, '%s.f[3]' % cube, y=True)
        cmds.move(z1, '%s.f[2]' % cube, z=True)
        cmds.move(x2, '%s.f[4]' % cube, x=True)
        cmds.move(y2, '%s.f[1]' % cube, y=True)
        cmds.move(z2, '%s.f[0]' % cube, z=True) 
        cmds.rename(i+"_BBox")   
Ejemplo n.º 53
0
def returnBoundingBoxSize (meshGrp,objOnly = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass an object, mesh group or whatever into it,  it calculates it's bounding box info and returns list

    ARGUMENTS:
    meshGrp(string) - mesh or mesh group

    RETURNS:
    returnList(list) - [xLength,yLength,zLength]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if type(meshGrp) is list:
	for o in meshGrp: assert mc.objExists(o),"returnBoundingBoxSize: meshGrp object doesn't exist: '%s'"%o
    else:
	assert mc.objExists(meshGrp),"returnBoundingBoxSize: meshGrp doesn't exist: '%s'"%meshGrp
    returnList = []
    boundingBoxSize = []
    
    if objOnly:
	buffer= mc.duplicate(meshGrp,returnRootsOnly=True)
	l_relatives = mc.listRelatives(buffer[0],allDescendents = True,fullPath = True,type = 'transform')
	if l_relatives:mc.delete(l_relatives)  
	box = mc.exactWorldBoundingBox (buffer[0]) 
	if buffer:mc.delete(buffer)
	
    #box = mc.exactWorldBoundingBox (meshGrp)
    else:
	box = mc.exactWorldBoundingBox (meshGrp)   
    rawBuffer =  [(box[3] - box[0]), (box[4] - box[1]), (box[5] - box[2])]
    for number in rawBuffer:
        if mayaVersion >= 2010:
            returnList.append(float('{0:f}'.format(number)))
        else:
            returnList.append(float(number))
    
    return returnList
Ejemplo n.º 54
0
 def shortDistance(self):
     if len(self.follicleGrp)<2:
         print "***ERROR: Select 2 or more follicles."
         return 
     i=-1
     for a in self.follicleGrp:
         i+=1
         x1, y1, z1, x2, y2, z2 = cm.exactWorldBoundingBox(a)
         self.FolBBoxGrp.append((x1, y1, z1))
         for b in reversed(self.follicleGrp):
             x2, y2, z2, x3, y3, z3 = cm.exactWorldBoundingBox(b)
             tempDist = math.sqrt(((x1-x2)**2)+((y1-y2)**2)+((z1-z2)**2))
             
             if tempDist < self.Dist:
                 if b==a:
                     pass
                 else:
                     self.Dist = tempDist   
     self.Dist/=2 
     
     print 'Shortest distance:', self.Dist
     if self.Dist<.5:
         print '***WARNING: Range is <0.5. May create empty groups.'
def voroLocal():
    
    density = cmds.intSliderGrp( 'localDensity', query = True, value = True)
    density = density * 10
    selectedVerts = cmds.ls( sl = True )
    selectedMesh = selectedVerts[0].split('.')
    seeds = []        
     
    if len( selectedVerts ) == 1:
        shape = selectedVerts[0]
        bbox = cmds.exactWorldBoundingBox( selectedMesh[0] )
        
        for i in range( density ):
            vtx = cmds.xform( selectedVerts[0], q = True, ws = True, t = True )
            seed = cmds.spaceLocator( p = ( 0, 0, 0), a = True )[0]
            cmds.move( random.uniform( vtx[0] - 0.1, vtx[0] + 0.1 ), random.uniform( vtx[1] - 0.1, vtx[1] + 0.1 ), random.uniform( vtx[2] - 0.1, vtx[2] + 0.1 ), a = True )
            cmds.scale( 0.1, 0.1, 0.1, a = True, ocp = True )
            
            seedL = cmds.xform( seed, q = True, ws = True, t = True )
            
            if( seedL[0] > bbox[0] and seedL[0] < bbox[3] and seedL[1] > bbox[1] and seedL[1] < bbox[4] and seedL[2] > bbox[2] and seedL[2] < bbox[5] ): 
                seeds.append( seed )
            
            else:
                cmds.select( seed )
                cmds.delete()
        
        
        print(len(seeds))    
        for i in range ( 0, len(seeds)):
            
            meshCopy = cmds.duplicate( selectedMesh[0] ) 
            
            for j in range ( 0, len(seeds)):
                    
                if i != j:
                    
                    voronoiFracture( i, j, seeds, meshCopy )
                    
        cmds.select( selectedMesh[0] )
        cmds.delete()
        
        cmds.select( *seeds )
        cmds.delete()
        
    elif( len( selection ) > 1 ):
        print( 'error: please select only 1 vertex' )
        
    else:
        print( 'error: please select a vertex' )
Ejemplo n.º 56
0
def createBBoxFromSelected():
	import maya.cmds as cmds

	sel = cmds.ls(sl=True)

	x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(sel, calculateExactly=True)

	cube = cmds.polyCube()[0]
	cmds.move(x1, '%s.f[5]' % cube, x=True)
	cmds.move(y1, '%s.f[3]' % cube, y=True)
	cmds.move(z1, '%s.f[2]' % cube, z=True)
	cmds.move(x2, '%s.f[4]' % cube, x=True)
	cmds.move(y2, '%s.f[1]' % cube, y=True)
	cmds.move(z2, '%s.f[0]' % cube, z=True)
Ejemplo n.º 57
0
    def mainFunc(self):
        original_height = float(self.float_height.value())
        #define values
        verts = cmds.ls(os = True)
        verts_pos = cmds.xform(verts, q=True, ws = True, t = True)
        v0 = cmds.xform(verts[0], q=True, ws = True, t = True)
        v1 = cmds.xform(verts[1], q=True, ws = True, t = True)
        v2 = cmds.xform(verts[2], q=True, ws = True, t = True)
        v3 = cmds.xform(verts[3], q=True, ws = True, t = True)
        print v0, v1, v2, v3
        
        """not using numpy
        """
        cp_x = (v0[0]+v1[0]+v2[0]+v3[0])/4
        cp_y = (v0[1]+v1[1]+v2[1]+v3[1])/4
        cp_z = (v0[2]+v1[2]+v2[2]+v3[2])/4
        
        cp = [cp_x, cp_y, cp_z]
        
        """ using numpy
        verts_pos = np.reshape(np.array(verts_pos), (len(verts_pos)/3,3))
        cp = np.average(verts_pos, axis = 0)
        """
        
        object = verts[0].split('.vtx')[0]
        plane = 'bottom_plane'

        #create plane for alignment
        cmds.polyCreateFacet(p =(v0,v1,v2,v3), n = plane)
        self.movePivot(cp, object)
        self.movePivot(cp, plane)
        cmds.parent(object, plane)
        cmds.move(-cp[0],-cp[1],-cp[2], plane)
        self.align_plane(plane)

        #clean up the aid objects
        cmds.parent(plane + '|' + object, world = True)
        #cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=2)
        cmds.delete(plane)
        cmds.delete('locator_center')
        cmds.delete('locator_normal_aim')
        cmds.delete('locator_for_z')
        
        
        bb = cmds.exactWorldBoundingBox()
        height = bb[4] - bb[1]
        print height
        s = original_height/height
        print s
        cmds.scale(s,s,s, object)
Ejemplo n.º 58
0
def makebb(parent):
    children = cmds.listRelatives(parent)
    if children == None:
        return
    print parent
    for rn in children:
        x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(parent + "|" + rn, calculateExactly=True)
        cube = cmds.polyCube()[0]
        cmds.move(x1, "%s.f[5]" % cube, x=True)
        cmds.move(y1, "%s.f[3]" % cube, y=True)
        cmds.move(z1, "%s.f[2]" % cube, z=True)
        cmds.move(x2, "%s.f[4]" % cube, x=True)
        cmds.move(y2, "%s.f[1]" % cube, y=True)
        cmds.move(z2, "%s.f[0]" % cube, z=True)
        makebb(rn)
Ejemplo n.º 59
0
def fix ():
    geoSource = cmds.ls(selection=True)
    for g in geoSource:
        print 'category name = ' + str(g)
        geometry = cmds.listRelatives(g)
        for i in geometry:
            print 'found = ' + str(i)
            cmds.select(i)
            # bounding box & center each object
            bbox = cmds.exactWorldBoundingBox()
            bottom = [(bbox[0] + bbox[3])/2, bbox[1], (bbox[2] + bbox[5])/2]
            cmds.xform(piv=bottom, ws=True)
            cmds.move(rpr=True)
            # freeze transforms
            cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)