Esempio n. 1
0
def mirrorGeo():
    # Variables and selection
    mirrorMode = cmds.radioButtonGrp('mirrorMode', q=True, sl=True)
    mDir = cmds.radioButtonGrp('mDir', q=True, sl=True)
    sel = cmds.ls(sl=True)

    # Duplication type
    if (mirrorMode == 1):
        cmds.duplicate()
    elif (mirrorMode == 2):
        cmds.instance()
    else:
        newHalf = cmds.duplicate()

    # Scaling
    if (mDir == 1):
        cmds.scale(-1, 1, 1)
    elif (mDir == 2):
        cmds.scale(1, -1, 1)
    else:
        cmds.scale(1, 1, -1)

    # Merging Copy
    if (mirrorMode == 3):
        cmds.select(sel[0], r=True)
        cmds.select(newHalf, add=True)
        cmds.polyUnite()
        cmds.ConvertSelectionToVertices()
        cmds.polyMergeVertex(d=0.001, am=1, ch=1)
        cmds.select(sel[0])
Esempio n. 2
0
def placeGem(pt, norm):
	cmds.select('gem')
	cmds.instance()

	r_angle = getRotAngle(norm)
	cmds.rotate(r_angle[0],r_angle[1],r_angle[2], r = True)
	cmds.move(pt[0], pt[1], pt[2])
Esempio n. 3
0
def placeStreetLight(blockList,daytime,lightGeom):
    '''
    Places street light instances on every block in the city.
    
    blockList: A list containing all the objects of the class Block.
    daytime: Boolean variable which is true if it is day and false if it is night.
    lightGeom: Tuple containing the object name and node name for a polygonal object,
               in this case a street light.
    On exit: The polygonal object (lightGeom) has been instanced and placed around
             every block in blockList using placeLight(...). 
    '''
    for i in blockList:
        widthNumber = int(i.width / 5.0 - 1) #number of objects placed along the width of the block
        widthDistance = i.width / (widthNumber + 1) #distance between every object
        depthNumber = int(i.depth / 5.0 - 1) #number of objects placed along the depth of the block
        depthDistance = i.depth / (depthNumber + 1) #distance between every object
        for j in range(widthNumber):
            light1 = cmds.instance(lightGeom[0])
            light2 = cmds.instance(lightGeom[0])
            placeLight(light1,(i.center[0] - i.width/2.0 + (j+1) * widthDistance, i.center[1] - i.depth/2.0 + 0.2), daytime)
            placeLight(light2,(i.center[0] - i.width/2.0 + (j+1) * widthDistance, i.center[1] + i.depth/2.0 - 0.2), daytime)
        for j in range(depthNumber):
            light1 = cmds.instance(lightGeom[0])
            light2 = cmds.instance(lightGeom[0])
            placeLight(light1, (i.center[0] - i.width/2.0 + 0.2, i.center[1] - i.depth/2.0 + (j+1) * depthDistance), daytime)
            placeLight(light2, (i.center[0] + i.width/2.0 - 0.2, i.center[1] - i.depth/2.0 + (j+1) * depthDistance), daytime)
Esempio n. 4
0
 def __init__(self, position, rotation):
     cmds.instance(self.template, n="outer_wall_" + str(self.index))
     cmds.showHidden("outer_wall_" + str(self.index))
     cmds.move(position.x, position.y + self.wallSize.y / 2, position.z,
               "outer_wall_" + str(self.index))
     cmds.rotate(rotation.x, rotation.y, rotation.z,
                 "outer_wall_" + str(self.index))
     super(OuterWall, self).__init__("outer_wall_" + str(self.index))
     self.IncementWallIndex()
Esempio n. 5
0
    def __init__(self, position):
        cmds.instance(self.template, n="tower_" + str(self.index))
        cmds.showHidden("tower_" + str(self.index))
        cmds.move(position.x, position.y + self.height / 2, position.z,
                  "tower_" + str(self.index))

        cmds.xform("tower_" + str(self.index), piv=(0, -self.height / 2, 0))
        self.name = "tower_" + str(self.index)
        self.IncementTowerIndex()
        return
Esempio n. 6
0
 def __init__(self, position, rotation):
     cmds.instance(self.template, n="ground_wall_" + str(self.index))
     cmds.showHidden("ground_wall_" + str(self.index))
     #cmds.xform("ground_wall_" + str(self.index),piv=(0,-self.wallSize.y/2,0))
     cmds.move(position.x, position.y, position.z,
               "ground_wall_" + str(self.index))
     cmds.rotate(rotation.x, rotation.y, rotation.z,
                 "ground_wall_" + str(self.index))
     super(GroundWall, self).__init__("ground_wall_" + str(self.index))
     self.IncementWallIndex()
     return
Esempio n. 7
0
def applyCallback(pPetalShape, pNumPetals, pPetalHeight, pPetalRadius,
                  pPetalAngle, *pArgs):
    '''
    This function generates pine cone like shapes from user input
    '''
    #retrieving the values from user input
    numberPetals = cmds.intField(pNumPetals, query=True, value=True)
    startH = cmds.floatField(pPetalHeight, query=True, value=True)
    startR = cmds.floatField(pPetalRadius, query=True, value=True)
    petalAngle = cmds.intField(pPetalAngle, query=True, value=True)
    petalShape = cmds.optionMenu(pPetalShape, query=True, value=True)

    #creating a cone or cylinder base shape based on what the user selected from the shape dropdown menu
    if petalShape == 'Cone':
        result = cmds.polyCone(r=startR, h=startH, name='OG#')
    else:
        result = cmds.polyCylinder(r=startR, h=startH, name='OG#')

    #moving the pivot down to the base of the shape so that rotating the instances will create the radial effect
    cmds.move(0, startH / 2, 0, result[0])
    cmds.move(0,
              0,
              0,
              result[0] + ".scalePivot",
              result[0] + ".rotatePivot",
              absolute=True)
    cmds.rotate(petalAngle, 0, 0, result[0])
    coneGroup = cmds.group(empty=True, name="Group")

    #creating one layer with the correct number of petals
    for i in range(1, numberPetals):
        resInstance = cmds.instance(result[0], name='instance#')
        cmds.rotate(petalAngle, 0, 360 / numberPetals * i, resInstance)
        cmds.parent(resInstance, coneGroup)
    #parenting the initial petal into this first layer
    cmds.parent(result, coneGroup)

    #creating a group for all five layers
    full = cmds.group(empty=True, name="full")

    #creating the other four layers
    for x in range(1, 5):
        dupInstance = cmds.instance(coneGroup, name='dup#')
        cmds.move(0, 0, 0.2 * x, dupInstance)
        #scaling each layer instance down by a larger factor each iteration
        cmds.scale(1 - (0.1 * x), 1 - (0.1 * x), 1 - (0.1 * x), dupInstance)
        cmds.parent(dupInstance, full)

    #parenting the initial layer into the final shape group
    cmds.parent(coneGroup, full)
Esempio n. 8
0
def test_isInstanced():
    sel = cmdc.SelectionList().add("perspShape")

    persp_shape = sel.getDagPath(0)
    assert not persp_shape.isInstanced()

    cmds.instance("perspShape")
    assert persp_shape.isInstanced()

    invalid_dag = cmdc.DagPath()
    nose.tools.assert_raises(
        RuntimeError,
        invalid_dag.isInstanced,
    )
Esempio n. 9
0
def copyToLocators(replace=False, instance=False):

	selection = cmds.ls(sl=True)

	# Check if two or more obj selected
	if len(selection) < 2:
	    OpenMaya.MGlobal.displayError("Select at least two objects")

	for object in selection[:-1]:

	    cmds.select(selection[-1:])

	    if not instance:
	        new_obj = cmds.duplicate()[0]
	    else:
	        new_obj = cmds.instance()[0]

	    # Set position
	    trans = cmds.xform(object, q=True, ws=True, rp=True)
	    cmds.move(trans[0],trans[1],trans[2], new_obj, a=True, ws=True, rpr=True)

	    # Set rotation
	    rot = cmds.getAttr(object + ".r")[0]
	    cmds.setAttr(new_obj + ".rotate", rot[0],rot[1],rot[2])

	    if replace:
	        cmds.delete(object)
	    else:
	        cmds.parent(new_obj, object)
Esempio n. 10
0
def match( source, destination, instObj ) :
    d2 = cmds.duplicate( destination )[0]
    s2 = cmds.instance( instObj )[0]
    cmds.xform( s2, cp=True )
    cmds.xform( d2, cp=True )
    # move to origin
    dpiv = cmds.xform( d2, q=True, ws=True, piv=True )
    cmds.xform( d2, r=True, ws=True, translation=(-dpiv[0],-dpiv[1],-dpiv[2]) ) 
    cmds.makeIdentity( d2, apply=True, t=True, r=True, s=True, n=False )
    #cmds.xform( target, cp=True )
    src = MatchObj( s2 )
    dst = MatchObj( d2)
    src.createBasis()
    dst.createBasis()
    # create instance of src, move to origin
    cmds.select( s2 )
    transformByMatrix( src.matrix.inverse() )
    #cmds.xform( target, cp=True )
    tmpg = cmds.group()
    # match rotation
    cmds.select( tmpg )
    transformByMatrix( dst.matrix )
    # clean up
    cmds.xform( s2, r=True, ws=True, translation=(dpiv[0],dpiv[1],dpiv[2]) ) 
    #cmds.xform( s2, r=True, ws=True, translation=(spiv[0],spiv[1],spiv[2]) )
    cmds.parent( s2, w=True )
    cmds.delete( d2 )
    cmds.delete( tmpg )
    return s2
Esempio n. 11
0
File: am_maya.py Progetto: pixo/hk
def instanceAsset(namespace=""):
    """Find new namespace"""
    ns = namespace
    name = "%s:root" % ns

    i = 1
    while cmds.objExists(name):
        ns = "%s%d" % (namespace, i)
        name = "%s:root" % ns
        i += 1

    """Make instance"""
    cmds.namespace(add=ns)
    root = cmds.instance("%s:root" % namespace, name=name)[0]

    """Get model_grp path"""
    model_grp = "%s:root|%s:master_trs|%s:shot_trs|%s:aux_trs|%s:model_grp" % (
        ns,
        namespace,
        namespace,
        namespace,
        namespace,
    )

    """Lock attributes"""
    cmds.setAttr("%s.%s" % (root, "asset"), lock=True)
    cmds.setAttr("%s.%s" % (root, "texturever"), lock=True)
    cmds.setAttr("%s.inheritsTransform" % model_grp, 0)
Esempio n. 12
0
    def fetchCursorObject(self):
        '''
        gather necessary data and generate a new cursor Object and return the string to the source DAG and the cursor DAG
        '''
        #fetch a new cursorObject
        if (self.uiValues.random): sourceDAG = self.sourceList.getRandom()
        else: sourceDAG = self.sourceList.getNext()

        #checking if the sourceDAG is a transform, if not attempting to find the parent transform
        #instancing multiple object doesnt work if using a shape
        #duplicating input connections on the parent transform is not carried over if using the shape
        if(mc.nodeType(sourceDAG)!='transform'):
            tempDAG = mc.listRelatives(sourceDAG, parent=True)
            sourceDAG = tempDAG[0]

        newObjectDAG = None
        if (self.uiValues.instance):
                newObjectDAG = mc.instance(sourceDAG)
        else:
                newObjectDAG = mc.duplicate(sourceDAG, ic=self.uiValues.preserveConn)

        if (len(newObjectDAG)>1):
            print ('warning: multiple objects created')

        #create the temporary group used through the stroke to store geometry as they are created
        self.tempgroup = mc.group (empty=True, name=spPaint3dTempGroupID)
        newObjectDAG = mc.parent(newObjectDAG[0], self.tempgroup, relative=True)

        return sourceDAG, newObjectDAG[0]
Esempio n. 13
0
    def scatter_func(self):
        # need to modify verts to scatter on with percentage
        if (self.percentage_to_scatter_to == 100.00):
            pass
        elif (self.percentage_to_scatter_to == 0.00):
            return 0
        else:
            self.choose_percentage_of_vertices()

        for vertex in self.verts_picked:
            self.instanced_obj = cmds.instance(self.obj_to_scatter,
                                               smartTransform=True)

            if (self.scale_checked):
                self.random_scale_instance(self.instanced_obj)

            self.move_instance(self.instanced_obj, vertex)

            if (self.align_to_normals_value):
                self.align_and_rotate_to_normals_function(
                    self.instanced_obj, vertex)
                if (self.push_in_objs):
                    self.push_in_instance(self.instanced_obj)
            elif (self.push_in_objs):
                self.align_and_rotate_to_normals_function(
                    self.instanced_obj, vertex)
                self.push_in_instance(self.instanced_obj)
                if (self.rotate_checked):
                    self.random_rotate_instance(self.instanced_obj)
            elif (self.rotate_checked):
                self.random_rotate_instance(self.instanced_obj)
Esempio n. 14
0
def replace(instance=True):
    selected = cmds.ls(sl=True, l=True)
    targets = selected[:-1]
    src = selected[-1]
    delete = []
    for tobj in targets:
        r = cmds.getAttr(tobj + '.rotate')[0]
        t = cmds.getAttr(tobj + '.translate')[0]
        s = cmds.getAttr(tobj + '.scale')[0]
        p = cmds.listRelatives(tobj, f=True, p=True)
        if p and len(p) > 0:
            p = p[0]

        newobj = None
        if instance:
            newobj = cmds.instance(src, n='MarzaReplaceObj')[0]
        else:
            newobj = cmds.duplicate(src, n='MarzaReplaceObj')[0]
        delete.append(tobj)
        cmds.setAttr(newobj + '.translate', t[0], t[1], t[2])
        cmds.setAttr(newobj + '.rotate', r[0], r[1], r[2])
        cmds.setAttr(newobj + '.scale', s[0], s[1], s[2])
        cmds.delete(tobj)
        if p:
            cmds.parent(newobj, p)
        print(newobj, tobj.split('|')[-1])
        cmds.rename(newobj, tobj.split('|')[-1])
Esempio n. 15
0
    def __init__(self, index, generator):

        # Stores its location.
        self.__index = index

        # Retrieves the values needed from the UI.
        self.__get_values(generator)

        # Fetches a pointer to the cratering data.
        cratering = self.__cratering

        # Stores the transform and shape nodes.
        nodes = []

        # If this is the first moon created, create a polyPlatonicSolid.
        if (index == 0):

            # Creates the shape.
            nodes = polyPlatonicSolid(radius=self.__radius, name="Moon")

            # For aesthetics, the polyPlatonicSolid is beveled (based on the user's input) and smoothed.
            polyBevel3(offset=getAttr("polyBevel1.offset") *
                       generator.get_spinbox_value("moon_ratio"),
                       depth=cratering.get_depth(),
                       segments=cratering.get_segments(),
                       fraction=cratering.get_fraction())
            polySmooth(divisions=2)

        # Otherwise, instance the original.
        else:
            nodes = instance("Moon")

        # Stores the transform node.
        self.__transform_node = nodes[0]
Esempio n. 16
0
    def copy2VertexPy(self, sel, points):
        if not len(sel) >= 1:
            raise RuntimeError("Select at least one object first.")
        targetMesh = cmds.ls(points, o=1)
        targetMesh = targetMesh[0]
        sizeOfTobeInstanced = len(sel)

        for objIndex in range(sizeOfTobeInstanced):
            eachObj = sel[objIndex]
            cmds.select(eachObj, r=1)
            pivotWSPos = cmds.xform(ws=1, q=1, piv=1)
            cmds.move(0, 0, 0, eachObj, rpr=1)
            mel.eval("FreezeTransformations")
            cmds.move(pivotWSPos[0],
                      pivotWSPos[1],
                      pivotWSPos[2],
                      eachObj,
                      rpr=1)

        vertBinormals, vertTangents, vertNormals, vertPoints = self.getPosNormalTangents(
            targetMesh)

        for i in points:
            vertid = int(str(i).split('[')[1][:-1])
            objToInstance = random.randrange(0, sizeOfTobeInstanced)
            newInstance = cmds.instance(sel[objToInstance])
            mat = self.vectorsToMatrix(vertBinormals[vertid],
                                       vertTangents[vertid],
                                       vertNormals[vertid], vertPoints[vertid])
            cmds.xform(newInstance, m=mat)
Esempio n. 17
0
def generate_shield(p_shield_shape, p_num_shield_pieces):
    random.seed(1234)
    transformName = p_shield_shape[0]
    instanceGroupName = cmds.group(empty=True,
                                   name=transformName + '_instance_grp#')

    #to keep track of the actual instances for returning
    instance_group = []

    for i in range(0, p_num_shield_pieces):
        instanceResult = cmds.instance(transformName,
                                       name=transformName + '_instance#')
        cmds.parent(instanceResult, instanceGroupName)

        x = random.uniform(-10, 10)
        y = random.uniform(0, 20)
        z = random.uniform(-10, 10)

        cmds.move(x, y, z, instanceResult)

        xRot = random.uniform(0, 360)
        yRot = random.uniform(0, 360)
        zRot = random.uniform(0, 360)

        #no rotation needed since the pieces will be aimed at the core later

        scalingFactor = random.uniform(0.3, 1.15)
        cmds.scale(scalingFactor, 1.0, scalingFactor, instanceResult)
        instance_group.append(instanceResult)

    cmds.hide(transformName)
    cmds.xform(instanceGroupName, centerPivots=True)
    return instance_group, instanceGroupName
    def explodeHumanFace(self):
        # get the source object
        result = cmds.ls(orderedSelection=True)[0]

        if len(result) == 0:
            print 'Please select one object'
            return
        else:
            print 'result: %s' % (result)

        # query the number of faces
        faces = cmds.polyEvaluate(result, f=True)
        triangles = cmds.polyEvaluate(result, t=True)

        selection = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getActiveSelectionList(selection)
        mDagPath = OpenMaya.MDagPath()
        selection.getDagPath(0, mDagPath)

        centers = self.faceCenter(mDagPath)

        for i in range(0, len(centers) / 4):
            instanceResult = cmds.instance(self.srcObject,
                                           name=self.srcObject + '_instance#')

            cmds.move(centers[i * 4], centers[i * 4 + 1], centers[i * 4 + 2],
                      instanceResult)
 def Action_ModifyInstancedShape(self, deleteOriginal):
     maya_cmds.undoInfo(openChunk=True)
     try:
         shapeSource = self.window.Line_SourceShape.text().strip()
         shapeTarget = self.window.Line_TargetShape.text().strip()
         parentSource = maya_cmds.listRelatives(shapeSource,
                                                path=True,
                                                parent=True)
         parentsTarget = maya_cmds.listRelatives(shapeTarget,
                                                 path=True,
                                                 allParents=True)
         for i in xrange(len(parentsTarget)):
             instanceSource = maya_cmds.instance(parentSource)
             instanceSourceChildrens = maya_cmds.listRelatives(
                 instanceSource, path=True, children=True)
             for j in xrange(len(instanceSourceChildrens)):
                 if parentsTarget[i] not in maya_cmds.listRelatives(
                         instanceSourceChildrens[j], path=True,
                         allParents=True):
                     maya_cmds.parent(instanceSourceChildrens[j],
                                      parentsTarget[i],
                                      shape=True,
                                      relative=True)
             maya_cmds.delete(instanceSource)
         if deleteOriginal:
             maya_cmds.delete(shapeTarget)
     except Exception as e:
         print >> stderr, str(e)
     maya_cmds.undoInfo(closeChunk=True)
Esempio n. 20
0
def sphere_placement(mdllist):
    cmds.polySphere(sx=12, sy=12, r=50, name='sphere')
    result = cmds.ls(orderedSelection=True)
    instanceName = result[0]
    instanceGroupName = cmds.group(empty=True,
                                   name=instanceName + '_instance_grp#')

    for i, mdl in enumerate(mdllist):
        instanceResult = cmds.instance(instanceName,
                                       name=instanceName + '_instance' +
                                       str(i))
        cmds.parent(instanceResult, instanceGroupName)

        x = random.uniform(-600, 600)
        y = random.uniform(-400, 400)
        z = random.uniform(-700, 700)
        xr = random.uniform(0, 360)
        yr = random.uniform(0, 360)
        zr = random.uniform(0, 360)
        scalingFactor = random.uniform(0.8, 1.8)

        cmds.move(x, y, z, instanceResult)
        cmds.rotate(xr, yr, zr, instanceResult)
        cmds.scale(scalingFactor, scalingFactor, 0.7 * scalingFactor,
                   instanceResult)

        mat = cmds.shadingNode(mdl, name='test_%s' % mdl, asShader=True)
        matSG = cmds.sets(name='%sSG' % mat,
                          empty=True,
                          renderable=True,
                          noSurfaceShader=True)
        cmds.connectAttr('%s.outColor' % mat, '%s.surfaceShader' % matSG)
        cmds.sets(instanceResult, e=True, forceElement=matSG)
Esempio n. 21
0
def instantiate() :
    selected = cmds.ls( sl=True, long=True )
    source = selected[-1]
    targets = selected[0:-1]
    if isDirectParent( source ) :
        for t in targets :
            inst = cmds.instance( source )[0]
            sp = cmds.listRelatives( source, parent=True, fullPath=True )[0]
            tp = cmds.listRelatives( t, parent=True, fullPath=True )[0]
            inst = '%s|%s' % (sp,inst)
            cmds.select( inst )
            cmds.select( t, add=True )
            mel.eval( 'CenterPivot' )
            matchTranslate()
            matchRotation()
            print( 'created: %s, parent: %s' % (inst, sp) )
            try :
                cmds.parent( inst, tp )
            except :
                pass
            cmds.delete( t )
    else :
        stree = {}
        stree[source] = {}
        storeBelow( stree[source], source )
        for t in targets :
            ttree = {}
            ttree[t] = {}
            storeBelow( ttree[t], t )
            instantiateTree( stree[source], ttree[t], t )
Esempio n. 22
0
 def object_y(self, den_list, object_to_instance):
     """scatter inst face up"""
     for vert in den_list:
         vertex_pos = cmds.xform(vert, q=True, ws=True, t=True)
         new_instance = cmds.instance(object_to_instance, n='obj_inst')
         cmds.move(vertex_pos[0], vertex_pos[1], vertex_pos[2],
                   new_instance)
Esempio n. 23
0
    def __init__(self, index, planet_radius, number_of_rings):

        # The index is used when determining the scale and rotation of the ring.
        self.__index = index

        # To shrink each successive ring, a decrement value is calculated.
        self.__scale_decrement_value = .5 / number_of_rings

        # Names the ring.
        name = "Ring"

        # If this is the first ring created, create a polyTorus.
        if (index == 0):

            # Since this is the first ring, the outer radius is stored and used when calculating how far away the moons and starfields should be.
            radius = self.__radius = float(planet_radius + number_of_rings)

            # The torus that makes the ring is created then smoothed.
            instance_nodes = polyTorus(name=name,
                                       radius=radius,
                                       sectionRadius=(radius / 100))
            polySmooth(divisions=2)

            # Since this is the first ring, its transform node is also stored as a class member.
            self.__transform_node = instance_nodes[0]

        # Otherwise, instance the initial ring.
        else:

            # Creates an instance of the initial ring and stores the nodes.
            nodes = instance(name)

            # The transform node of the ring is stored as an instance member.
            self.__transform_node = nodes[0]
Esempio n. 24
0
 def __init__(self, root_obj_name, sel_name, run_option):
     # this function runs the script
     face_sel = cmds.ls(sl=True, fl=True) # makes a selection from the UI
     Face_Center()# passes the selection into Face_Center class to find centers of faces in face_sel
     self.run_option = run_option
     self.sel_name = sel_name
     self.dupe_geo_list = []
     for dummy_item in face_sel:                        
         for key, val in FACE_CENTER_DICT.iteritems(): # loops through global dict to find relevant coordinates
             if self.run_option == 'Instance':
                 dummy_new_geo = cmds.instance(root_obj_name)
             elif self.run_option == 'Duplicate':
                 dummy_new_geo = cmds.duplicate(root_obj_name)
             cmds.setAttr( str(dummy_new_geo[0])+'.translateX', val[0] )
             cmds.setAttr( str(dummy_new_geo[0])+'.translateY', val[1] )
             cmds.setAttr( str(dummy_new_geo[0])+'.translateZ', val[2] )
             dummy_constr = cmds.normalConstraint(dummy_item, str(dummy_new_geo[0]), aimVector = (0,1,0), u = (0,1,0), worldUpType= 0, wu = (0, 1, 0))
             cmds.delete(dummy_constr)
             self.dupe_geo_list.append(dummy_new_geo)
         cmds.setAttr( str(root_obj_name)+'.translateX', 0 )
         cmds.setAttr( str(root_obj_name)+'.translateY', 0 )
         cmds.setAttr( str(root_obj_name)+'.translateZ', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateX', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateY', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateZ', 0 )               
         FACE_CENTER_DICT.clear() # memory management purposes 
     self.sel_name_grp=cmds.group( em=True, name=self.sel_name ) # creates a group to house the duplicated geometries
     for dummy_geo in self.dupe_geo_list:
         cmds.parent( dummy_geo, str(self.sel_name_grp) )                
Esempio n. 25
0
def createRandomInstance(number=10,
                         x=10,
                         y=10,
                         z=10,
                         scale=[1.0, 1.0],
                         randomOrient=False):
    """
    Creates a bunch of randomly distrubuted copies of selection.

    :param number: the amount of copies wanted (default: 10)
    :param x: Maximum movement in x, default 10
    :param y: Maximum movement in y, default 10
    :param z: Maximum movement in z, default 10
    :param scale: Maximum scale multiplier [low,high], default [1.0, 1.0]
    :param randomOrient: set to true to randomize orientation. Default false


    """
    random.seed(1234)

    result = cmds.ls(orderedSelection=True)

    print('Copying: {}'.format(result))

    transformName = result[0]

    instanceGroupName = cmds.group(empty=True,
                                   name=transformName + '_instance_grp#')

    for i in range(0, number):

        instanceResult = cmds.instance(transformName,
                                       name=transformName + '_instance#')

        cmds.parent(instanceResult, instanceGroupName)

        xvar = random.uniform(-x, x)
        yvar = random.uniform(-y, y)
        zvar = random.uniform(-z, z)

        cmds.move(xvar, yvar, zvar, instanceResult)

        xRot = 0
        yRot = 0
        zRot = 0

        if randomOrient == True:
            xRot = random.uniform(0, 360)
            yRot = random.uniform(0, 360)
            zRot = random.uniform(0, 360)

        cmds.rotate(xRot, yRot, zRot, instanceResult)

        scalingFactor = random.uniform(scale[0], scale[1])

        cmds.scale(scalingFactor, scalingFactor, scalingFactor, instanceResult)

    cmds.hide(transformName)

    cmds.xform(instanceGroupName, centerPivots=True)
Esempio n. 26
0
def shoal(colo, nbFish, espacementFish, scaleFish, nomType):
    lar = 14  #taille du terrain qui variera en fonction du terrain
    long = 14

    #groupe qui regroupe les poissons du bancs
    grFish = cmds.group(em=True, n="grp_fishy")

    #generation de plusieurs fish
    for i in range(0, nbFish):
        r1 = rand.uniform(-espacementFish / 2.0, espacementFish / 2.0)
        r2 = rand.uniform(-espacementFish / 2.0, espacementFish / 2.0)
        r3 = rand.uniform(-espacementFish / 2.0, espacementFish / 2.0)
        cmds.move(r1, r2, r3, nomType)
        cmds.rotate(rand.uniform(-20, 20), rand.uniform(-20, 20), 0, nomType)
        cmds.scale(scaleFish, scaleFish, scaleFish, nomType)
        f = cmds.instance(nomType, leaf=True)
        cmds.parent(f, grFish)

    #------------ REPARTITION ici -------------------
    randomY = rand.uniform(4, 8)  #?gerer la hauteur
    cmds.move(rand.uniform(-lar / 2, lar / 2), randomY,
              rand.uniform(-long / 2, long / 2),
              grFish)  #repartition dans l'espace sur un plan
    cmds.rotate(rand.uniform(-15, 15), rand.uniform(-180, 180), 0, grFish)

    cmds.select(nomType)
    cmds.delete(nomType)

    applyColor(nomType, colo)
Esempio n. 27
0
    def fetchCursorObject(self):
        '''
        gather necessary data and generate a new cursor Object and return the string to the source DAG and the cursor DAG
        '''
        #fetch a new cursorObject
        if (self.uiValues.random): sourceDAG = self.sourceList.getRandom()
        else: sourceDAG = self.sourceList.getNext()

        #checking if the sourceDAG is a transform, if not attempting to find the parent transform
        #instancing multiple object doesnt work if using a shape
        #duplicating input connections on the parent transform is not carried over if using the shape
        if(mc.nodeType(sourceDAG)!='transform'):
            tempDAG = mc.listRelatives(sourceDAG, parent=True)
            sourceDAG = tempDAG[0]

        newObjectDAG = None
        if (self.uiValues.instance):
                newObjectDAG = mc.instance(sourceDAG)
        else:
                newObjectDAG = mc.duplicate(sourceDAG, ic=self.uiValues.preserveConn)

        if (len(newObjectDAG)>1):
            print ('warning: multiple objects created')

        #create the temporary group used through the stroke to store geometry as they are created
        self.tempgroup = mc.group (empty=True, name=spPaint3dTempGroupID)
        newObjectDAG = mc.parent(newObjectDAG[0], self.tempgroup, relative=True)

        return sourceDAG, newObjectDAG[0]
Esempio n. 28
0
def placeTrafficLights(street,trafficLights, size):
    '''
    Creates instances of traffic lights and places them throughout the city.
    
    street: An object of the class Street.
    trafficLights: A list containing four traffic light objects of different type.
    size: Tuple that contains the x- and z-components for the size of the city.
    On exit: Traffic light instances have been placed at the start point and end point 
             of the street, except if this is at the edge of the city. The procedure is
             recursively called in order to place traffic lights for every street in the
             binary tree that makes up the street structure for the city. 
    '''
    #randomly pick which geometries should be instanced.
    num1 = random.random()
    if num1 > 0.6:
        geom1 = trafficLights[0]
    elif num1 > 0.2:
        geom1 = trafficLights[3]
    elif num1 > 0.1:
        geom1 = trafficLights[2]
    else:
        geom1 = trafficLights[1]
    num2 = random.random()
    if num2 > 0.6:
        geom2 = trafficLights[0]
    elif num2 > 0.2:
        geom2 = trafficLights[3]
    elif num2 > 0.1:
        geom2 = trafficLights[2]
    else:
        geom2 = trafficLights[1]
    if street.split[0] == "horisontal":
        if street.start[0] != -size[0]/2.0:            
            light1 = cmds.instance(geom1[0])
            light2 = cmds.instance(geom1[0])
            cmds.xform(light1, rotation = (0,90,0), translation = (street.start[0]+3, 0, street.start[1] + 2.2))
            cmds.xform(light2, rotation = (0,90,0), translation = (street.start[0]+3, 0, street.start[1] - 2.2))
        if street.end[0] != size[0]/2.0:
            light1 = cmds.instance(geom2[0])
            light2 = cmds.instance(geom2[0])
            cmds.xform(light1, rotation = (0,-90,0), translation = (street.end[0]-3, 0, street.end[1] + 2.2))
            cmds.xform(light2, rotation = (0,-90,0), translation = (street.end[0]-3, 0, street.end[1] - 2.2))
    else:
        if street.start[1] != -size[1]/2.0:
            light1 = cmds.instance(geom1[0])
            light2 = cmds.instance(geom1[0])
            cmds.xform(light1, translation = (street.start[0] + 2.2, 0, street.start[1] + 3))
            cmds.xform(light2, translation = (street.start[0] - 2.2, 0, street.start[1] + 3))
        if street.end[1] != size[1]/2.0:
            light1 = cmds.instance(geom2[0])
            light2 = cmds.instance(geom2[0])
            cmds.xform(light1, rotation = (0,180,0), translation = (street.end[0] + 2.2, 0, street.end[1] - 3))
            cmds.xform(light2, rotation = (0,180,0), translation = (street.end[0] - 2.2, 0, street.end[1] - 3))
    if street.smaller != None:
        placeTrafficLights(street.smaller, trafficLights, size)
    if street.larger != None:
        placeTrafficLights(street.larger, trafficLights, size)
Esempio n. 29
0
def replaceTargetsObjectsWithSources(sources,
                                     targets,
                                     inPlace=False,
                                     usePivot=False,
                                     asInstance=False,
                                     deleteTargets=True):
    """
	Replaces the targets with sources.

	:param sources: Sources.
	:type sources: list
	:param targets: Targets.
	:type targets: list
	:param inPlace: In place replacement.
	:type inPlace: bool
	:param usePivot: Use target pivot.
	:type usePivot: bool
	:param asInstance: Duplicate as instances.
	:type asInstance: bool
	:param deleteTargets: Delete targets.
	:type deleteTargets: bool
	"""

    duplicatedObjects = []
    for target in targets:
        if not asInstance:
            duplicatedObject = cmds.duplicate(sources[random.randrange(
                0, len(sources))],
                                              rr=True)[0]
        else:
            duplicatedObject = cmds.instance(sources[random.randrange(
                0, len(sources))])[0]

        duplicatedObjects.append(duplicatedObject)
        if not inPlace:
            if usePivot:
                components = ("rx", "ry", "rz", "sx", "sy", "sz")
                pivot = cmds.xform(target,
                                   query=True,
                                   worldSpace=True,
                                   rotatePivot=True)
                for i, component in enumerate(("tx", "ty", "tz")):
                    cmds.setAttr(duplicatedObject + "." + component, pivot[i])
            else:
                components = ("tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy",
                              "sz")

            for component in components:
                cmds.setAttr(duplicatedObject + "." + component,
                             cmds.getAttr(target + "." + component))
        if deleteTargets:
            cmds.delete(target)

    if duplicatedObjects:
        if not inPlace:
            duplicationGrp = cmds.group(em=True)
            for duplicatedObject in duplicatedObjects:
                cmds.parent(duplicatedObject, duplicationGrp)
            cmds.rename(duplicationGrp, "duplication_grp")
 def fnCreateCylinder(intX, intY, fltTemp, strFtr, strPlyName):                                                          #this generates a single cylinder
     strInstanceResult = cmds.instance(strPlyName, name = strPlyName + '_Factor' + strFtr + '_instance#')[0] 
     cmds.setAttr(strInstanceResult + '.scaleY', fltTemp)   
     fltTranslateHeight = fltSize * fltTemp / float(2) 
     fltXMovment = (float(intX) * fltXScaler) + fltXConstant 
     fltYMovement = (float(intY) * fltYScaler) + fltYConstant
     cmds.move(fltXMovment, fltTranslateHeight, fltYMovement, strInstanceResult, absolute=True)
     return(strInstanceResult)         
Esempio n. 31
0
def makeFountainPark(wxd, treeShaders, daytime, lightGeom):
    '''
    Creates a park with a fountain in the middle.
    
    wxd: A tuple containing the width and the depth of the park.
    treeShaders: A list of shaders for the tree crowns.
    daytime: Boolean variable which is true if it is day and false if it is night.
    lightGeom: Tuple containing the object name and node name for a polygonal object,
               in this case a street light.
    On exit: A park with trees (placeTreesInSquare(...)), fences (makeFence(...)) 
             and street lights (trafficLight.placeLight(...)) has been created and
             a fountain has been created in the middle of the park using 
             makeFountain(...). Everything has been combined into a single polygonal 
             object except the lights, which are instead parented to this object. 
             The park object is returned as a tuple containing the object name and 
             node name.
    '''
    # Make fences around the park.
    fence1 = makeFence((-wxd[0]/2.0,wxd[1]/2.0), (-1,wxd[1]/2.0), "x")
    fence2 = makeFence((1,wxd[1]/2.0), (wxd[0]/2.0,wxd[1]/2.0), "x")
    fence3 = makeFence((wxd[0]/2.0,wxd[1]/2.0), (wxd[0]/2.0,1), "z")
    fence4 = makeFence((wxd[0]/2.0,-1), (wxd[0]/2.0,-wxd[1]/2.0), "z")
    fence5 = makeFence((wxd[0]/2.0,-wxd[1]/2.0), (1,-wxd[1]/2.0), "x")
    fence6 = makeFence((-1,-wxd[1]/2.0), (-wxd[0]/2.0,-wxd[1]/2.0), "x")
    fence7 = makeFence((-wxd[0]/2.0,-wxd[1]/2.0), (-wxd[0]/2.0,-1), "z")
    fence8 = makeFence((-wxd[0]/2.0,1), (-wxd[0]/2.0,wxd[1]/2.0), "z")
    fountain = makeFountain()
    # Place squares with grass and trees around the paths.
    square1 = placeTreesInSquare(((-wxd[0]/2.0, -wxd[1]/2.0), (-1,-1)), treeShaders)
    square2 = placeTreesInSquare(((-wxd[0]/2.0, 1),(-1, wxd[1]/2.0)), treeShaders)
    square3 = placeTreesInSquare(((1, -wxd[1]/2.0),(wxd[0]/2.0, -1)), treeShaders)
    square4 = placeTreesInSquare(((1,1),(wxd[0]/2.0, wxd[1]/2.0)), treeShaders)
    park = cmds.polyUnite(fence1, fence2, fence3, fence4, fence5, fence6, fence7,
                          fence8, fountain, square1, square2, square3, square4)
    cmds.delete(park, ch = True)
    # Create and place instances of street lights
    light1 = cmds.instance(lightGeom[0])
    trafficLight.placeLight(light1[0], (-1.5,-0.9), daytime)
    light2 = cmds.instance(lightGeom[0])
    trafficLight.placeLight(light2[0], (-1.5,0.9), daytime)
    light3 = cmds.instance(lightGeom[0])
    trafficLight.placeLight(light3[0], (1.5,-0.9), daytime)
    light4 = cmds.instance(lightGeom[0])
    trafficLight.placeLight(light4[0], (1.5,0.9), daytime)
    cmds.parent((light1[0],light2[0],light3[0],light4[0]),park[0])
    return park
Esempio n. 32
0
def symmetricalInstance(object):
	"""
	This definition creates a symmetrical instance.

	:param object: Object to symmetrical instantiate. ( String )
	"""

	instance = cmds.instance(object)
	cmds.setAttr(object + ".sx", -1)
Esempio n. 33
0
def spawnRand():
    objList = cm.ls(sl=True)
    mRX = 10
    mRX2 = -10
    mRY = 10
    mRY2 = -10
    mRZ = 10
    mRZ2 = -10
    rRX = (360)
    rRY = (360)
    rRZ = (360)
    dupR = 25

    for i in range(dupR):

        cm.move(rand(mRX, mRX2), rand(mRY, mRY2), rand(mRZ, mRZ2), objList)
        cm.rotate(rand(0, rRX), rand(0, rRY), rand(0, rRZ), objList)
        cm.instance(objList)
Esempio n. 34
0
    def createObject(self,intersection):
        '''
        will create the object at the intersection object gathered data, pending all ui and transform options
        will update the stored data to store the created object DAG path and return the newly created object DAG Path back
        '''

        newObjectDAG = None
        if (self.uiValues.instance):
            if(sp3d_dbg): logDebugInfo('creating instance')
            #fetching the transform for that shape (instance dont create object of child objects if it's the shape that gets instanced)
            tempDAG = mc.listRelatives(intersection.dagMeshSourceObject, parent=True)
            newObjectDAG = mc.instance(tempDAG[0])
        else:
            #fetching the parent transform to prevent some issue while duplicating with preserve input connections and stuff docked onto the transform and not the shape
            if(sp3d_dbg): logDebugInfo('duplicating object')
            tempDAG = mc.listRelatives(intersection.dagMeshSourceObject, parent=True)
            newObjectDAG = mc.duplicate(tempDAG[0], ic=self.uiValues.preserveConn)
        if(sp3d_dbg): logDebugInfo('DONE creating instance / duplicating object')

        if (len(newObjectDAG)>1):
            print ('warning: multiple objects created')

        moveTo(newObjectDAG[0], intersection.hitPoint)


        if (self.uiValues.align):
            #align to surface normal
            if(sp3d_dbg): logDebugInfo('aligning object with surface normal')
            rx, ry, rz = getEulerRotationQuaternion(self.worldUp, intersection.getHitNormal(self.uiValues.smoothNormal))
            mc.xform(newObjectDAG[0], ro=(rx, ry, rz) )
            if(sp3d_dbg): logDebugInfo('DONE aligning object with surface normal')

        if (self.uiValues.transformRotate and not self.uiValues.rampFX):
            #rotate transform
            randrotate = self.transform.getRandomRotate()
            mc.rotate(randrotate[0], randrotate[1], randrotate[2], newObjectDAG[0], os=True, r=True, rotateXYZ=True)

        if (self.uiValues.transformScale and not self.uiValues.rampFX):
            #scale transform
            randscale = self.transform.getRandomScale(self.uiValues.transformScaleUniform)
            mc.scale(randscale[0],randscale[1],randscale[2],newObjectDAG[0], relative=True)

        if (self.uiValues.upOffset != 0):
           offsetArray = [self.uiValues.upOffset*self.worldUp.x,self.uiValues.upOffset*self.worldUp.y,self.uiValues.upOffset*self.worldUp.z]
           mc.move(offsetArray[0],offsetArray[1],offsetArray[2],newObjectDAG[0],relative=True) 


        if(self.uiValues.hierarchy):
            #grouping objects
            grouped = None
            if mc.objExists(self.tempgroup):
                grouped = mc.parent(newObjectDAG[0], self.tempgroup, relative=True)
            else:
                print 'error: temp group does not exist'
                print grouped
            return grouped[0];
        else: return newObjectDAG[0]
Esempio n. 35
0
    def createObject(self,intersection):
        '''
        will create the object at the intersection object gathered data, pending all ui and transform options
        will update the stored data to store the created object DAG path and return the newly created object DAG Path back
        '''

        newObjectDAG = None
        if (self.uiValues.instance):
            if(sp3d_dbg): logDebugInfo('creating instance')
            #fetching the transform for that shape (instance dont create object of child objects if it's the shape that gets instanced)
            tempDAG = mc.listRelatives(intersection.dagMeshSourceObject, parent=True)
            newObjectDAG = mc.instance(tempDAG[0])
        else:
            #fetching the parent transform to prevent some issue while duplicating with preserve input connections and stuff docked onto the transform and not the shape
            if(sp3d_dbg): logDebugInfo('duplicating object')
            tempDAG = mc.listRelatives(intersection.dagMeshSourceObject, parent=True)
            newObjectDAG = mc.duplicate(tempDAG[0], ic=self.uiValues.preserveConn)
        if(sp3d_dbg): logDebugInfo('DONE creating instance / duplicating object')

        if (len(newObjectDAG)>1):
            print ('warning: multiple objects created')

        moveTo(newObjectDAG[0], intersection.hitPoint)


        if (self.uiValues.align):
            #align to surface normal
            if(sp3d_dbg): logDebugInfo('aligning object with surface normal')
            rx, ry, rz = getEulerRotationQuaternion(self.worldUp, intersection.getHitNormal(self.uiValues.smoothNormal))
            mc.xform(newObjectDAG[0], ro=(rx, ry, rz) )
            if(sp3d_dbg): logDebugInfo('DONE aligning object with surface normal')

        if (self.uiValues.transformRotate and not self.uiValues.rampFX):
            #rotate transform
            randrotate = self.transform.getRandomRotate()
            mc.rotate(randrotate[0], randrotate[1], randrotate[2], newObjectDAG[0], os=True, r=True, rotateXYZ=True)

        if (self.uiValues.transformScale and not self.uiValues.rampFX):
            #scale transform
            randscale = self.transform.getRandomScale(self.uiValues.transformScaleUniform)
            mc.scale(randscale[0],randscale[1],randscale[2],newObjectDAG[0], relative=True)

        if (self.uiValues.upOffset != 0):
           offsetArray = [self.uiValues.upOffset*self.worldUp.x,self.uiValues.upOffset*self.worldUp.y,self.uiValues.upOffset*self.worldUp.z]
           mc.move(offsetArray[0],offsetArray[1],offsetArray[2],newObjectDAG[0],relative=True) 


        if(self.uiValues.hierarchy):
            #grouping objects
            grouped = None
            if mc.objExists(self.tempgroup):
                grouped = mc.parent(newObjectDAG[0], self.tempgroup, relative=True)
            else:
                print 'error: temp group does not exist'
                print grouped
            return grouped[0];
        else: return newObjectDAG[0]
Esempio n. 36
0
def building(*args):

    result = cmds.ls(sl=True)

    min = cmds.intSliderGrp('numMin', q=1, value=1)
    max = cmds.intSliderGrp('numMax', q=1, value=1)

    sXmin = cmds.floatSliderGrp('scalexMin', q=1, value=1.0)
    sXmax = cmds.floatSliderGrp('scalexMax', q=1, value=1.0)

    sYmin = cmds.floatSliderGrp('scaleyMin', q=1, value=1.0)
    sYmax = cmds.floatSliderGrp('scaleyMax', q=1, value=1.0)

    sZmin = cmds.floatSliderGrp('scalezMin', q=1, value=1.0)
    sZmax = cmds.floatSliderGrp('scalezMax', q=1, value=1.0)

    mXmin = cmds.floatSliderGrp('movexMin', q=1, value=1.0)
    mXmax = cmds.floatSliderGrp('movexMax', q=1, value=1.0)

    mYmin = cmds.floatSliderGrp('moveyMin', q=1, value=1.0)
    mYmax = cmds.floatSliderGrp('moveyMax', q=1, value=1.0)

    mZmin = cmds.floatSliderGrp('movezMin', q=1, value=1.0)
    mZmax = cmds.floatSliderGrp('movezMax', q=1, value=1.0)

    rXmin = cmds.floatSliderGrp('rotatexMin', q=1, value=1.0)
    rXmax = cmds.floatSliderGrp('rotatexMax', q=1, value=1.0)

    rYmin = cmds.floatSliderGrp('rotateyMin', q=1, value=1.0)
    rYmax = cmds.floatSliderGrp('rotateyMax', q=1, value=1.0)

    rZmin = cmds.floatSliderGrp('rotatezMin', q=1, value=1.0)
    rZmax = cmds.floatSliderGrp('rotatezMax', q=1, value=1.0)

    num = int(rand(min, max))

    for i in range(num):
        cmds.instance(result)
        cmds.scale(rand(sXmin, sXmax), rand(sYmin, sYmax), rand(sZmin, sZmax),
                   result)
        cmds.move(rand(mXmin, mXmax), rand(mYmin, mYmax), rand(mZmin, mZmax),
                  result)
        cmds.rotate(rand(rXmin, rXmax), rand(rYmin, rYmax), rand(rZmin, rZmax),
                    result)
Esempio n. 37
0
    def scatter_objects(self):
        """ Takes current selection and adds it to second selection verts """
        rand_trans = [0, 1, 2, 3]
        rand_rot = [0, 1, 2, 3]
        rand_scale = [0, 1, 2, 3]
        selection = cmds.ls(orderedSelection=True, flatten=True)
        vertex_names = cmds.filterExpand(selection,
                                         selectionMask=31,
                                         expand=True)
        """ Create a group """
        scatter_grp = cmds.group(em=True, n='scatter_grp')

        object_to_instance = selection[0]
        if cmds.objectType(object_to_instance) == 'transform':
            for ver in vertex_names:
                new_instance = cmds.instance(object_to_instance)
                position = cmds.pointPosition(ver, world=True)
                """ Apply the random offset to the position. """
                new_position = [
                    x + random.uniform(rand_trans[0], rand_trans[1])
                    for x in position
                ]
                new_rotation = [
                    random.uniform(rand_rot[0], rand_rot[1]) for _ in range(3)
                ]
                new_scale = [
                    random.uniform(rand_scale[0], rand_scale[1])
                    for _ in range(3)
                ]
                """ Set the position """
                cmds.move(new_position[0],
                          new_position[1],
                          new_position[2],
                          new_instance,
                          absolute=True,
                          worldSpace=True)
                """ Set the rotation """
                cmds.rotate(new_rotation[0],
                            new_rotation[1],
                            new_rotation[2],
                            new_instance,
                            relative=True,
                            objectSpace=True)
                """ Set the scale """
                cmds.scale(new_scale[0],
                           new_scale[1],
                           new_scale[2],
                           new_instance,
                           relative=True)
                """ Parent into the group """
                cmds.parent(new_instance, scatter_grp)

        else:
            print(
                "Make sure to select object you want scattered. "
                "Then shift select verts on the object you want scattered on")
Esempio n. 38
0
def symmetricalInstance(object):
    """
	Creates a symmetrical instance.

	:param object: Object to symmetrical instantiate.
	:type object: str
	"""

    instance = cmds.instance(object)
    cmds.setAttr(object + ".sx", -1)
Esempio n. 39
0
def test_instancenumber():
    sel = cmdc.SelectionList().add("|persp|perspShape")

    persp_shape = sel.getDagPath(0)
    nose.tools.assert_raises(
        TypeError,
        persp_shape.instanceNumber,
    )

    cmds.instance("perspShape")
    sel.add("|persp1|perspShape")
    persp1_shape = sel.getDagPath(1)
    assert persp_shape.instanceNumber() == 0
    assert persp1_shape.instanceNumber() == 1

    invalid_dag = cmdc.DagPath()
    nose.tools.assert_raises(
        RuntimeError,
        invalid_dag.instanceNumber,
    )
Esempio n. 40
0
    def copyToFaces_exec(self, sel, faces):
        targetObj = faces[0].split('.')[0]
        targetList = om2.MSelectionList()
        targetList.add(targetObj)
        targetPath = targetList.getDagPath(0)
        targetFaceIt = om2.MItMeshPolygon(targetPath)
        faceid_center = {}
        faceid_normal = {}
        faceid_area = {}
        facesId = []
        avgArea = 0
        avgAreaSum = 0
        for i in faces:
            facesId.append(int(i.split('[')[1][:-1]))

        while not targetFaceIt.isDone():
            index = targetFaceIt.index()
            area = targetFaceIt.getArea()
            center = targetFaceIt.center(space=2)
            normal = targetFaceIt.getNormal(space=2)
            faceid_center[index] = center
            faceid_normal[index] = normal
            faceid_area[index] = area
            targetFaceIt.next(None)

        for faceid in faceid_area:
            avgAreaSum = avgAreaSum + faceid_area[faceid]

        avgArea = avgAreaSum / len(faceid_area)

        for i in sel:
            pivotWSPos = cmds.xform(i, ws=1, q=1, piv=1)
            cmds.move(0, 0, 0, i, rpr=1)
            cmds.makeIdentity(i, apply=True, t=1, r=1, s=1, n=0)
            cmds.move(pivotWSPos[0], pivotWSPos[1], pivotWSPos[2], i, rpr=1)

        if cmds.objectType(sel[0]) == "transform":
            for face in faces:
                faceid = int(face.split('[')[1][:-1])
                objToInstance = int(random.random() * len(sel))
                newInstance = cmds.instance(sel[objToInstance])
                position = faceid_center[faceid]
                normal = faceid_normal[faceid]
                self.copy2Vertex_normal_moveAlign(newInstance, normal,
                                                  position)

                scaleValue = faceid_area[faceid] / avgArea
                cmds.scale(scaleValue,
                           scaleValue,
                           scaleValue,
                           newInstance,
                           r=1)
        else:
            print("Select Object First!")
Esempio n. 41
0
    def __init__(self, typeFish, scaleFish=0.5, nom="boid"):
        #changer les mesh
        if (typeFish == 2):
            nameType = "PoissonLong"
            path = cmds.internalVar(
                usd=True) + "SeaBedGenerator/Models/PoissonLong.fbx"
            cmds.file(path, i=True, mergeNamespacesOnClash=True, namespace=':')
            self.rBoid = cmds.instance(nameType, leaf=True)
            cmds.scale(scaleFish, scaleFish, scaleFish, self.rBoid)
            cmds.delete(nameType)
        if (typeFish == 1):
            nameType = "PoissonFleche"
            path = cmds.internalVar(
                usd=True) + "SeaBedGenerator/Models/PoissonFleche.fbx"
            cmds.file(path, i=True, mergeNamespacesOnClash=True, namespace=':')
            self.rBoid = cmds.instance(nameType, leaf=True)
            cmds.scale(scaleFish, scaleFish, scaleFish, self.rBoid)
            cmds.delete(nameType)

        self.listeBoids.append(self.rBoid)
Esempio n. 42
0
def instancer(assetName, transform=False):
    selectedAsset = assetName
    namespace = selectedAsset.split(":")[0]

    newInstance = mc.instance(selectedAsset, name=namespace + ":" + "instance#")[0]

    if transform:
        channels = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"]
        count = 0
        for i in channels:
            mc.setAttr(newInstance + "." + i, transform[count])
            count +=1
Esempio n. 43
0
def copyOnSelected(i=False, r=False):
	# i - instance
	# r - replace
	selection = cmds.ls(selection=True, o=True)
	for node in selection[1:]:
		if i:
			inst = cmds.instance(selection[0])
		else:
			inst = cmds.duplicate(selection[0])
		alignTwoObj(inst, node)
		if r:
			cmds.delete(node)
Esempio n. 44
0
def instanceFirst(doShaders=False):
    #1. make an array of all selected objects
    target = mc.ls(sl=1)

    #2. if only one selection, just make a new instance at the same coordinates...
    if(len(target)==1):
        mc.instance()

    else:
        #3. ...otherwise, for each selected object...
        for i in range(1,len(target)):

            #4. ...get current selection's position and copy keyframes and shader
            mc.select(target[i])
            pos = mc.xform(target[i], q=True, t=True, ws=True)
            try:
                shader = getShader()
            except:
                print "Couldn't get shader."
            try:
                mc.copyKey()
            except:
                print "Couldn't copy keys."

            #5. instance the first selection
            mc.select(target[0])
            mc.instance()
        
            #6. move first selection to position and paste keyframes and shader
            mc.move(pos[0],pos[1],pos[2])
            if(doShaders==True):
                setShader(shader)
            try:
                mc.pasteKey()
            except:
                print "Couldn't paste keys."
           
            #7. delete selection
            mc.delete(target[i])
Esempio n. 45
0
    def activate(self):
        if self.active:
            return

        if not self.refExists():
            m.warning('{}: {}: Reference does not exists. Activation skipped.'.format(self.refLocator.shape, self.refFilename))
            return

        if not m.objExists(self.instanceSource):
            self.createRefSource()

        m.instance(
            self.instanceSource,
            name=REF_INST_NAME
        )

        inst = '|{}|{}'.format(INSTANCES_SOURCE_GROUP, REF_INST_NAME)
        m.setAttr(inst + '.overrideEnabled', True)
        m.setAttr(inst + '.overrideDisplayType', 2)
        lockTransformations(inst, visibility=True)
        parentAPI(inst, self.refLocator.transform, absolute=False)
        m.connectAttr(self.refNode + '.message', self.refLocator.shape + '.refNodeMessage', force=True)

        self.active = True
Esempio n. 46
0
def replaceTargetsObjectsWithSources(sources, targets, inPlace=False, usePivot=False, asInstance=False, deleteTargets=True):
	"""
	Replaces the targets with sources.

	:param sources: Sources.
	:type sources: list
	:param targets: Targets.
	:type targets: list
	:param inPlace: In place replacement.
	:type inPlace: bool
	:param usePivot: Use target pivot.
	:type usePivot: bool
	:param asInstance: Duplicate as instances.
	:type asInstance: bool
	:param deleteTargets: Delete targets.
	:type deleteTargets: bool
	"""

	duplicatedObjects = []
	for target in targets:
		if not asInstance:
			duplicatedObject = cmds.duplicate(sources[random.randrange(0, len(sources))], rr=True)[0]
		else:
			duplicatedObject = cmds.instance(sources[random.randrange(0, len(sources))])[0]

		duplicatedObjects.append(duplicatedObject)
		if not inPlace:
			if usePivot:
				components = ("rx", "ry", "rz", "sx", "sy", "sz")
				pivot = cmds.xform(target, query=True, worldSpace=True, rotatePivot=True)
				for i, component  in enumerate(("tx", "ty", "tz")):
					cmds.setAttr(duplicatedObject + "." + component, pivot[i])
			else:
				components = ("tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz")

			for component in components:
				cmds.setAttr(duplicatedObject + "." + component, cmds.getAttr(target + "." + component))
		if deleteTargets:
			cmds.delete(target)

	if duplicatedObjects:
		if not inPlace:
			duplicationGrp = cmds.group(em=True)
			for duplicatedObject in duplicatedObjects:
				cmds.parent(duplicatedObject, duplicationGrp)
			cmds.rename(duplicationGrp, "duplication_grp")
Esempio n. 47
0
def distribute(i=True, r=False):
	# i - instance
	# r - replace
	selection = cmds.ls(selection=True, o=True)
	for node in selection[1:]:
		if i:
			inst = cmds.instance(selection[0])
		else:
			inst = cmds.duplicate(selection[0])

		objPos = cmds.xform(node, q=1, ws=1, rp=1)
		objRot = cmds.xform(node, q=1, ro=True)
		cmds.move(objPos[0], objPos[1], objPos[2], inst, rpr=True)
		cmds.rotate(objRot[0], objRot[1], objRot[2], inst, r=True)
		cmds.select(inst)

		if r:
			cmds.delete(node)
Esempio n. 48
0
def ins(*args):
	negIns = cmds.checkBox("negIns", q=True, v=True)
	insAx = cmds.radioButtonGrp("insAx", q=True, sl=True)
	
	if(insAx==1):
		scaI = ".scaleX"
	if(insAx==2):
		scaI = ".scaleY"
	if(insAx==3):
		scaI = ".scaleZ"
	
	if(negIns==1):
		scaVal = -1
	else:
		scaVal = 1
		
	newIns = cmds.instance()
	#print(newIns)
	cmds.setAttr(newIns[0] + scaI, scaVal)
Esempio n. 49
0
	def _duplicate( self, dpOriginal, copyAsInstance, suffix ):
		fInstanced = MFnDependencyNode( dpOriginal.transform() )
		
		# We need the full path to the instanced object, but if that
		# object is a shape we actually want the path to the shape's
		# parent transform (this is so that the instance and duplicate
		# commands work right)
		#
		originalFullName = ""
		if dpOriginal.node().hasFn( MFn.kTransform ):
			originalFullName = dpOriginal.fullPathName()
		else:
			MDagPath.getAPathTo( dpOriginal.transform(), dpOriginalTransform )
			originalFullName = dpOriginalTransform.fullPathName()
		
		duplicateNames = []
		if copyAsInstance:
			duplicateNames = mc.instance( originalFullName )
		else:
			duplicateNames = mc.duplicate( originalFullName, rr=True )
	
		duplicateList = MSelectionList()
		MGlobal.getSelectionListByName( duplicateNames[0], duplicateList )
		dpDuplicate = MDagPath()
		duplicateList.getDagPath( 0, dpDuplicate )
		
		self._renameHierarchy( dpDuplicate, dpOriginal, suffix )
		
		if not dpDuplicate.node().hasFn( MFn.kTransform ):
			raise ns.Errors.UnsupportedError( "Currently only instanced transforms are supported." )
			
		fDuplicate = MFnTransform( dpDuplicate.transform() )
		if not fDuplicate.parent(0).hasFn( MFn.kWorld ):
			oDuplicate = dpDuplicate.transform()
			modifier = MDagModifier()
			modifier.reparentNode( oDuplicate )
			modifier.doIt()
			MDagPath.getAPathTo( oDuplicate, dpDuplicate )
		
		return dpDuplicate
Esempio n. 50
0
def makePark(wxd, treeShaders, daytime, lightGeom):
    '''
    Creates a park block with trees, paths, fences and street lights.
    
    wxd: A tuple containing the width and the depth of the park.
    treeShaders: A list of shaders for the tree crowns.
    daytime: Boolean variable which is true if it is day and false if it is night.
    lightGeom: Tuple containing the object name and node name for a polygonal object,
               in this case a street light.
    On exit: A park with three randomly placed paths has been created and street 
             lights placed using trafficLights.placeLights(...) at the intersection of 
             these paths. Trees and fences have also been created using 
             placeTreesInSquare(...) and makeFence(...). Everything has been combined 
             into a single polygonal object except the lights, which are instead parented
             to this object. The park object is returned as a tuple containing the 
             object name and node name.
    '''
    # Decide if the first path should be horisontal (along the x-axis) or vertical (along the z-axis).
    dir = random.choice(["horisontal", "vertical"]) 
    if dir == "horisontal":
        path1 = random.uniform(-wxd[1]/2 + 2, wxd[1]/2 - 2) # z-coordinate for the first path.
        path2 = random.uniform(-wxd[0]/2 + 2, wxd[0]/2 - 2) # x-coordinate for the second path.
        path3 = random.uniform(-wxd[0]/2 + 2, wxd[0]/2 - 2) # x-coordinate for the third path.
        # Place squares with grass and trees around the paths.
        square1 = placeTreesInSquare(((-wxd[0]/2.0, -wxd[1]/2.0), (path2 - 0.5, path1 - 1)), treeShaders)
        square2 = placeTreesInSquare(((-wxd[0]/2.0, path1 + 1), (path3 - 0.5, wxd[1]/2.0)), treeShaders)
        square3 = placeTreesInSquare(((path2 + 0.5, -wxd[1]/2.0), (wxd[0]/2.0, path1 - 1)), treeShaders)
        square4 = placeTreesInSquare(((path3 + 0.5, path1 + 1), (wxd[0]/2.0, wxd[1]/2.0)), treeShaders)
        # Make fences around the park.
        fence1 = makeFence((-wxd[0]/2.0,-wxd[1]/2.0), (path2 -0.5,-wxd[1]/2.0), "x")
        fence2 = makeFence((path2 + 0.5,-wxd[1]/2.0), (wxd[0]/2.0,-wxd[1]/2.0), "x")
        fence3 = makeFence((wxd[0]/2.0,-wxd[1]/2.0), (wxd[0]/2.0,path1 - 1), "z")
        fence4 = makeFence((wxd[0]/2.0,path1 + 1), (wxd[0]/2.0,wxd[1]/2.0), "z")
        fence5 = makeFence((wxd[0]/2.0,wxd[1]/2.0), (path3 + 0.5,wxd[1]/2.0), "x")
        fence6 = makeFence((path3 - 0.5,wxd[1]/2.0), (-wxd[0]/2.0,wxd[1]/2.0), "x")
        fence7 = makeFence((-wxd[0]/2.0,wxd[1]/2.0), (-wxd[0]/2.0,path1 + 1), "z")
        fence8 = makeFence((-wxd[0]/2.0,path1 - 1), (-wxd[0]/2.0,-wxd[1]/2.0), "z")
        # Create and place instances of street lights
        light1 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light1[0], (path3 - 1.5,path1 + 0.9), daytime)
        light2 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light2[0], (path3 + 1.5,path1 + 0.9), daytime)
        light3 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light3[0], (path2 - 1.5,path1 - 0.9), daytime)
        light4 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light4[0], (path2 + 1.5,path1 - 0.9), daytime)
    if dir == "vertical":
        path1 = random.uniform(-wxd[0]/2 + 2, wxd[0]/2 - 2) # x-coordinate for the first path.
        path2 = random.uniform(-wxd[1]/2 + 2, wxd[1]/2 - 2) # z-coordinate for the second path.
        path3 = random.uniform(-wxd[1]/2 + 2, wxd[1]/2 - 2) # z-coordinate for the third path.
        # Place squares with grass and trees around the paths.
        square1 = placeTreesInSquare(((-wxd[0]/2.0, -wxd[1]/2.0), (path1 - 1, path2 - 0.5)), treeShaders)
        square2 = placeTreesInSquare(((-wxd[0]/2.0, path2 + 0.5), (path1 - 1, wxd[1]/2.0)), treeShaders)
        square3 = placeTreesInSquare(((path1 + 1, -wxd[1]/2.0), (wxd[0]/2.0, path3 - 0.5)), treeShaders)
        square4 = placeTreesInSquare(((path1 + 1, path3 + 0.5), (wxd[0]/2.0, wxd[1]/2.0)), treeShaders)
        # Make fences around the park.
        fence1 = makeFence((-wxd[0]/2.0,-wxd[1]/2.0), (path1 -1,-wxd[1]/2.0), "x")
        fence2 = makeFence((path1 + 1,-wxd[1]/2.0), (wxd[0]/2.0,-wxd[1]/2.0), "x")
        fence3 = makeFence((wxd[0]/2.0,-wxd[1]/2.0), (wxd[0]/2.0,path3 - 0.5), "z")
        fence4 = makeFence((wxd[0]/2.0,path3 + 0.5), (wxd[0]/2.0,wxd[1]/2.0), "z")
        fence5 = makeFence((wxd[0]/2.0,wxd[1]/2.0), (path1 + 1,wxd[1]/2.0), "x")
        fence6 = makeFence((path1 - 1,wxd[1]/2.0), (-wxd[0]/2.0,wxd[1]/2.0), "x")
        fence7 = makeFence((-wxd[0]/2.0,wxd[1]/2.0), (-wxd[0]/2.0,path2 + 0.5), "z")
        fence8 = makeFence((-wxd[0]/2.0,path2 - 0.5), (-wxd[0]/2.0,-wxd[1]/2.0), "z")
        # Create and place instances of street lights
        light1 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light1[0], (path1 + 0.9,path3 - 1.5), daytime)
        light2 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light2[0], (path1 + 0.9,path3 + 1.5), daytime)
        light3 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light3[0], (path1 - 0.9,path2 - 1.5), daytime)
        light4 = cmds.instance(lightGeom[0])
        trafficLight.placeLight(light4[0], (path1 - 0.9,path2 + 1.5), daytime)
    park = cmds.polyUnite(square1,square2,square3,square4,fence1, fence2, fence3,
                          fence4, fence5, fence6, fence7, fence8)
    cmds.delete(park, ch = True)
    cmds.parent((light1[0],light2[0],light3[0],light4[0]),park[0])
    return park
Esempio n. 51
0
    def createJnts(self, upLow, locData = ''):
        """
        creating joints
        """
        if locData:
            self.locData        = locData
            #- lip joints and location position
            self.lipEPos        = self.locData['setupLoc']['lipEPos']
            self.lipWPos        = [-self.lipEPos[0], self.lipEPos[1], self.lipEPos[2]]
            self.lipNPos        = self.locData['setupLoc']['lipNPos']
            self.lipSPos        = self.locData['setupLoc']['lipSPos']
            self.lipYPos        = self.locData['setupLoc']['lipYPos']
            self.headSkelPos    = self.locData['setupLoc']['headSkelPos']
            self.jawRigPos      = self.locData['setupLoc']['jawRigPos']
            self.cheekPos       = self.locData['setupLoc']['cheekPos']
            self.squintPuffPos  = self.locData['setupLoc']['squintPuffPos']
            self.lowCheekPos    = self.locData['setupLoc']['lowCheekPos']
    
            self.uplipVtxs    = eval(self.locData['upLipVtxs'])
            self.lolipVtxs    = eval(self.locData['loLipVtxs'])
            self.uplipVtxs    = self.sortSelected(self.uplipVtxs)
            self.lolipVtxs    = self.sortSelected(self.lolipVtxs)            
            
        if upLow == self.uploPrefix[0]:
            verts = self.uplipVtxs
        elif upLow == self.uploPrefix[1]:
            verts = self.lolipVtxs
        vNum = len(verts)# + 2       
        
        if upLow == self.uploPrefix[0]:
            lipCntPos = self.lipNPos
            #vMin = 0
            #vMax = vNum
                
        elif upLow == self.uploPrefix[1]:
            lipCntPos = self.lipSPos

        vMin = 0
        vMax = vNum
        
        #increment = 1.0/(vNum-1)
        #
        #- create lip joint guide curve
        tempCrv       = cmds.curve(d= 3, ep= [(-self.lipEPos[0], self.lipEPos[1], self.lipEPos[2]),(lipCntPos),(self.lipEPos)]) 
        guideCrv      = cmds.rename(tempCrv, upLow + "Guide" + self.crvSuffix)
        guideCrvShape = cmds.listRelatives(guideCrv, c = True) 
        cmds.rebuildCurve(guideCrv, d = 3, rebuildType = 0, keepRange = 0) 
                
        #- final lip shape ctrl curve
        templipCrv    = cmds.curve(d = 3, p =([0,0,0],[0.25,0,0],[0.5,0,0],[0.75,0,0],[1,0,0])) 
        cmds.rebuildCurve(rt = 0, d = 3, kr = 0, s = 4)    
        lipCrv        = cmds.rename(templipCrv, upLow + 'Lip' + self.crvSuffix)
        lipCrvShape   = cmds.listRelatives(lipCrv, c = True)
        lipCrvGrp     = self.group([lipCrv, guideCrv], upLow + 'LipCrv' + self.grpSuffix)
        self.group(lipCrvGrp, self.lipPCrvGrp)
        
        if not cmds.listRelatives(self.lipPCrvGrp, p = True):
            self.group(self.lipPCrvGrp, self.crvGrp)

        #- lip curve for LipJotX tx,ty for UDLR ctrl
        tempTyCrv = cmds.curve(d = 3, p =([0,0,0],[0.25,0,0],[0.5,0,0],[0.75,0,0],[1,0,0])) 
        cmds.rebuildCurve(rt = 0, d = 3, kr = 0, s = 4)    
        tyLipCrv = cmds.rename(tempTyCrv, upLow +'TyLip' + self.crvSuffix) 
        tylipCrvShape = cmds.listRelatives(tyLipCrv, c = True) 
        cmds.parent(tyLipCrv, lipCrvGrp)

        
        #- lipTarget curve shape
        lUpLow = self.prefix[0] + upLow
        rUpLow = self.prefix[1] + upLow
        
        jawOpenCrv = cmds.duplicate(lipCrv,     n = upLow + 'JawOpen' + self.crvSuffix)
        
        lLipWideCrv   = cmds.duplicate(lipCrv,  n = lUpLow + 'lipWide' + self.crvSuffix)
        rLipWideCrv   = cmds.duplicate(lipCrv,  n = rUpLow + 'lipWide' + self.crvSuffix)
        self.mirrorCurve(lLipWideCrv[0], rLipWideCrv[0])
        cmds.hide(rLipWideCrv[0])
        
        lLipECrv      = cmds.duplicate(lipCrv,  n = lUpLow + 'lipE' + self.crvSuffix)
        rLipECrv      = cmds.duplicate(lipCrv,  n = rUpLow + 'lipE' + self.crvSuffix)  
        self.mirrorCurve(lLipECrv[0], rLipECrv[0])
        cmds.hide(rLipECrv[0])
        
        lUCrv         = cmds.duplicate(lipCrv,  n = lUpLow + 'U' + self.crvSuffix)
        rUCrv         = cmds.duplicate(lipCrv,  n = rUpLow + 'U' + self.crvSuffix) 
        self.mirrorCurve(lUCrv[0], rUCrv[0])
        cmds.hide(rUCrv[0])
        
        lOCrv         = cmds.duplicate(lipCrv,  n = lUpLow + 'O' + self.crvSuffix) 
        rOCrv         = cmds.duplicate(lipCrv,  n = rUpLow + 'O' + self.crvSuffix)
        self.mirrorCurve(lOCrv[0], rOCrv[0])
        cmds.hide(rOCrv[0])
        
        lHappyCrv  = cmds.duplicate(lipCrv,    n = lUpLow + 'Happy' + self.crvSuffix) 
        rHappyCrv  = cmds.duplicate(lipCrv,    n = rUpLow + 'Happy' + self.crvSuffix)
        self.mirrorCurve(lHappyCrv[0], rHappyCrv[0])
        cmds.hide(rHappyCrv[0])
        
        lSadCrv    = cmds.duplicate(lipCrv,    n = lUpLow + 'Sad' + self.crvSuffix) 
        rSadCrv    = cmds.duplicate(lipCrv,    n = rUpLow + 'Sad' + self.crvSuffix) 
        self.mirrorCurve(lSadCrv[0], rSadCrv[0])
        cmds.hide(rSadCrv[0])
        
        lipCrvBS = cmds.blendShape(jawOpenCrv[0],
                                   lLipWideCrv[0],rLipWideCrv[0],
                                   lLipECrv[0],rLipECrv[0],
                                   lUCrv[0], rUCrv[0],
                                   lOCrv[0], rOCrv[0],
                                   lHappyCrv[0],rHappyCrv[0],
                                   lSadCrv[0],rSadCrv[0],
                                   lipCrv, n = upLow + 'LipCrvBS')
        cmds.blendShape(lipCrvBS[0],
                        edit=True,
                        w=[(0, 1),(1, 1),(2, 1),(3, 1),(4, 1),(5, 1),(6, 1),(7, 1),(8, 1),(9, 1),(10, 1),(11, 1),(12, 1)])

        #- lip freeform Ctrls curve(different number of points(4), so can not be target of the blendShape)      
        templipCtlCrv = cmds.curve(d = 3, p =([0,0,0],[0.25,0,0],[0.5,0,0],[0.75,0,0],[1,0,0])) 
        cmds.rebuildCurve(rt = 0, d = 3, kr = 0, s = 4)   
        lipCtlCrv = cmds.rename(templipCtlCrv, upLow +'LipCtl' + self.crvSuffix)
        lipCtlCrvShape = cmds.listRelatives(lipCtlCrv, c = True) 
        cmds.parent(lipCtlCrv, lipCrvGrp) 

        # lip Roll control curve shape(different number of points(4), so can not be target of the blendShape)      
        tempRollCrv = cmds.curve(d = 3, p =([0,0,0],[0.25,0,0],[0.5,0,0],[0.75,0,0],[1,0,0])) 
        cmds.rebuildCurve(rt = 0, d = 3, kr = 0, s = 2)   
        lipRollCrv = cmds.rename(templipCtlCrv, upLow + 'LipRoll' + self.crvSuffix)  
        lipRollCrvShape = cmds.listRelatives(lipRollCrv, c = True) 
        cmds.parent(lipRollCrv, lipCrvGrp) 

        #lip RollYZ control curve shape
        lipRollYZCrv = cmds.duplicate(lipRollCrv, n= upLow +'RollYZ' + self.crvSuffix)
        lipRollYZCrvShape = cmds.listRelatives(lipRollYZCrv, c = True)

        if not cmds.objExists(self.cheekCrvGrp):
            cheekCrvGrp = cmds.group(n = self.cheekCrvGrp, em =True, p = 'faceMain|crv_grp') 

            cheekTempCrv = cmds.curve(d=1, p = [(self.lowCheekPos),(self.lipEPos),(self.cheekPos),(self.squintPuffPos)]) 
            lCheekCrv = cmds.rename(cheekTempCrv, self.prefix[0] + "cheek" + self.crvSuffix)
            rCheekCrv = cmds.duplicate(lCheekCrv, n = self.prefix[1] + "cheek" + self.crvSuffix)
            cmds.setAttr(rCheekCrv[0] + '.scaleX', -1)
            cmds.parent(lCheekCrv,rCheekCrv, self.cheekCrvGrp)
            cmds.xform(lCheekCrv,rCheekCrv, centerPivots = 1)   

            lHappyCheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'happyCheek' + self.crvSuffix)
            rHappyCheekCrv = cmds.instance(lHappyCheekCrv, n= self.prefix[1] + 'happyCheek' + self.crvSuffix)
            lWideCheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'wideCheek' + self.crvSuffix)
            rWideCheekCrv = cmds.instance(lWideCheekCrv, n= self.prefix[1] + 'wideCheek' + self.crvSuffix)
            lECheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'eCheek' + self.crvSuffix)
            rECheekCrv = cmds.instance(lECheekCrv, n= self.prefix[1] + 'eCheek' + self.crvSuffix)

            lSadCheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'sadCheek' + self.crvSuffix)
            rSadCheekCrv = cmds.instance(lSadCheekCrv, n= self.prefix[1] + 'sadCheek' + self.crvSuffix)
            lUCheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'uCheek' + self.crvSuffix)
            rUCheekCrv = cmds.instance(lUCheekCrv, n= self.prefix[1] + 'uCheek' + self.crvSuffix)
            lOCheekCrv = cmds.duplicate(lCheekCrv, n= self.prefix[0] + 'oCheek' + self.crvSuffix)
            rOCheekCrv = cmds.instance(lOCheekCrv, n= self.prefix[1] + 'oCheek' + self.crvSuffix)

            lCheekBS = cmds.blendShape(lHappyCheekCrv[0],lWideCheekCrv[0],
                                       lECheekCrv[0],lSadCheekCrv[0],
                                       lUCheekCrv[0],lOCheekCrv[0],
                                       lCheekCrv, n ='lCheekBS')
            cmds.blendShape(lCheekBS[0], edit=True, w=[(0, 1),(1, 1),(2, 1),(3,1),(4,1),(5,1)])  
            rCheekBS = cmds.blendShape(rHappyCheekCrv[0],rWideCheekCrv[0],rECheekCrv[0],rSadCheekCrv[0],rUCheekCrv[0],rOCheekCrv[0], rCheekCrv, n ='rCheekBS')
            cmds.blendShape(rCheekBS[0], edit=True, w=[(0, 1),(1, 1),(2, 1),(3,1),(4,1),(5,1)])   
            cmds.move(2,0,0, lHappyCheekCrv, lWideCheekCrv, lSadCheekCrv, lECheekCrv, lUCheekCrv[0], lOCheekCrv, rotatePivotRelative = 1)
            cmds.move(-2,0,0, rHappyCheekCrv, rWideCheekCrv, rSadCheekCrv, rECheekCrv, rUCheekCrv[0], rOCheekCrv, rotatePivotRelative = 1)

            #attach ctrls to main cheek curves
            for lr in self.prefix:
               cvLs = cmds.ls(lr + '_cheek%s.cv[*]' %self.crvSuffix, fl = 1)
               cvLen = len(cvLs)
               lipCorner = cmds.group(em =1, n= lr +'_lipCorner', p ='supportRig')
               cheekList = [lr + '_lowCheek' + self.grpSuffix, lipCorner, lr + '_cheek' + self.grpSuffix, lr + '_squintPuff' + self.grpSuffix]
            
               for v in range(0, cvLen):
                   cheekPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = 'cheek' + str(v) + '_poc')
                   cmds.connectAttr(lr+'_cheek%sShape.worldSpace' %self.crvSuffix, cheekPoc + '.inputCurve')  
                   cmds.setAttr(cheekPoc + '.parameter', v)           
                   cmds.connectAttr(cheekPoc + '.positionX', cheekList[v] + '.tx')
                   cmds.connectAttr(cheekPoc + '.positionY', cheekList[v] + '.ty')
                   cmds.connectAttr(cheekPoc + '.positionZ', cheekList[v] + '.tz')  

        #- create lip joints parent group
        lipJotGrp = cmds.group(n = upLow + 'Lip' + self.grpSuffix, em =True) 
        cmds.parent(lipJotGrp, 'lipJotP')
        cmds.xform(lipJotGrp, ws = 1, t = self.jawRigPos) 
        
        #- delete detail lip ctrls 
        lipDetailP = upLow + 'LipDetailGrp' 
        kids = cmds.listRelatives(lipDetailP, ad=True, type ='transform')   
        if kids: cmds.delete(kids)

        vPos = []
        for vert in verts:
            voc = cmds.xform(vert, t =1, q=1, ws = 1)
            vPos.append(voc)
        vrtsDist = []
        for p in range(0, vNum-1):
            vDist = self.distance(vPos[p], vPos[p+1])
            vrtsDist.append(vDist)
        vrtsDist.insert(0,0)
        vLength = sum(vrtsDist)

        linearDist = 1.0/(vNum-1)
        increment = 0
        distSum = 0.0
        for i in range(vMin, vMax):
            distSum += vrtsDist[i]
            #increment = distSum / vLength
            poc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow + 'Lip' + str(i) + '_poc')
            cmds.connectAttr(guideCrvShape[0]+'.worldSpace',  poc + '.inputCurve')   
            cmds.setAttr(poc + '.turnOnPercentage', 1)    
            cmds.setAttr(poc + '.parameter', increment)        
            
            #- create detail lip ctrl        
            if i==0 or i== vNum-1:
                if upLow == self.uploPrefix[0]:
                    corners = self.createLipJoint(upLow, self.lipYPos, poc, lipJotGrp, i)
                    print corners
                    self.createDetailCtl(upLow, i)
                    cmds.parent(upLow +'LipDetailP'+ str(i), lipDetailP)
                    cmds.setAttr(upLow +'LipDetailP'+ str(i)+'.tx', linearDist*i)
                    cmds.setAttr(upLow +'LipDetailP'+ str(i)+'.ty', -1.5)
                    cmds.setAttr(upLow +'LipDetailP'+ str(i)+'.tz', 0)
                    cmds.setAttr(upLow +'LipDetailP'+ str(i)+'.sx', 0.25)
            else:
                self.createLipJoint(upLow, self.lipYPos, poc, lipJotGrp, i) 
                self.createDetailCtl(upLow, i)           
                cmds.parent(upLow +'LipDetailP'+ str(i), lipDetailP)
                cmds.setAttr(upLow +'LipDetailP'+ str(i) + '.tx', linearDist*i) 
                cmds.setAttr(upLow +'LipDetailP'+ str(i) + '.ty', 0)
                cmds.setAttr(upLow +'LipDetailP'+ str(i) + '.tz', 0)

            #- create lipCtrl curve POC
            lipCrvPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow +'LipCrv' + str(i) + '_poc')
            cmds.connectAttr(lipCrvShape[0] + ".worldSpace",  lipCrvPoc + '.inputCurve')   
            cmds.setAttr(lipCrvPoc  + '.turnOnPercentage', 1)    
            cmds.setAttr(lipCrvPoc  + '.parameter', increment)
            
            lipTYPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow +'LipTy' + str(i) + '_poc')
            cmds.connectAttr(tylipCrvShape[0] + ".worldSpace",  lipTYPoc + '.inputCurve')
            cmds.setAttr(lipTYPoc  + '.turnOnPercentage', 1)    
            cmds.setAttr(lipTYPoc  + '.parameter', increment) 
                    
            #- create lipCtrl curve POC
            ctlPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow +'LipCtl' + str(i) + '_poc')
            cmds.connectAttr(lipCtlCrvShape[0] + ".worldSpace",  ctlPoc + '.inputCurve')   
            cmds.setAttr(ctlPoc  + '.turnOnPercentage', 1)    
            cmds.setAttr(ctlPoc  + '.parameter', increment) 
            
            #- create lipRoll curve POC  lipRollCrv, lipRollYZCrv
            lipRollPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow +'LipRoll' + str(i) + '_poc')
            cmds.connectAttr(lipRollCrvShape[0] + ".worldSpace",  lipRollPoc + '.inputCurve')  
            cmds.setAttr(lipRollPoc + '.turnOnPercentage', 1)   
            cmds.setAttr(lipRollPoc + '.parameter', increment) 
            
            lipRollYZPoc = cmds.shadingNode('pointOnCurveInfo', asUtility =True, n = upLow +'LipRollYZ' + str(i) + '_poc')
            cmds.connectAttr(lipRollYZCrvShape[0] + ".worldSpace",  lipRollYZPoc + '.inputCurve')  
            cmds.setAttr(lipRollYZPoc  + '.turnOnPercentage', 1)   
            cmds.setAttr(lipRollYZPoc  + '.parameter', increment)
            
            increment = increment + linearDist
        
        if upLow == self.uploPrefix[1]:
            self.__bridgeJoints()
Esempio n. 52
0
if len(cubeList) >0:
    cmds.delete( cubeList )
result = cmds.polyCube ( w = 1, h= 1, d = 1, name= 'theCube#')
'''
result = cmds.ls (orderedSelection = True)

print 'result: %s' % (result)


if len (result) >= 2:
    floor = result[0]
    windows = result[1]
    floorGroup = cmds.group(empty = True, name= floor + '_floor_grp#')
    windowGroup = cmds.group(empty = True, name= floor + '_window_grp#')
    for i in range (0, 8):
        floorInstance = cmds.instance( floor, name=floor + '_instance#')
        cmds.parent (floorInstance, floorGroup)
        x = 0
        y = (i*30) + 15
        z = -900
        cmds.move(x, y, z, floorInstance )
        
        floorScale = cmds.xform( q=True, s=True)
        #print 'floorX: %s' % (floorScale[0])
        if i<7:
            windowInstance = cmds.instance(windows, name=windows+'_instance#')
            cmds.parent (windowInstance, windowGroup)
            x = -52#-floorScale[0]/2
            y = (i*30) -60#+ 30
            z = -32#-900
            cmds.move(x, y, z, windowInstance )
Esempio n. 53
0
def rsObjectsInPath(l_curves, i_number=3, i_type=0, b_consPos=True, b_consOri=True, b_orientWorld=True, b_parentHierarchy=False, b_selectNewObjs=True, o_toCurve=None, i_instance=0, i_loft=0):
    l_selIn = cmds.ls(sl=True, o=False)
    cmds.select(cl=True)
    l_list = []
    try:
        if cmds.objExists(l_curves):
            l_list.append(l_curves)
    except:
        pass
    for o_obj in l_curves:
        if cmds.objExists(o_obj):
            l_list.append(o_obj)
    if len(l_list) == 0:
        cmds.warning("Wrong input argument")
        return False
    l_curves = l_list
    d_type = {0: "group", 1: "spaceLocator", 2: "joint", 3: "Scene object"}
    l_targets = []
    l_objReturns = []
    for o_obj in l_curves:
        if cmds.objExists(o_obj):
            l_shapes = cmds.listRelatives(o_obj, s=True)
            for o_shape in l_shapes:
                if cmds.nodeType(o_shape) == "nurbsCurve" or cmds.nodeType(o_shape) == "bezierCurve":
                    l_targets.append(o_shape)
        else:
            cmds.warning("%s > A Does not exist" % (o_obj))
    if len(l_targets) > 0:
        l_loft = []
        for o_target in l_targets:
            l_tmpObjReturns = []
            i_openCloseVal = cmds.getAttr("%s.f" % (o_target))
            if i_openCloseVal == 0:
                f_div = 1.00 / (i_number - 1)
            else:
                f_div = 1.00 / i_number
            l_uValues = []
            for z in range(i_number):
                l_uValues.append(f_div * z)
            for z in range(i_number):
                o_obj = None
                if i_type != 3:
                    if i_type in d_type:
                        if i_type == 0:
                            o_obj = cmds.group(em=True)
                        if i_type == 1:
                            o_obj = cmds.spaceLocator()[0]
                        if i_type == 2:
                            o_obj = cmds.joint()
                    else:
                        cmds.warning("Type not recognized")
                        break
                else:
                    if cmds.objExists(o_toCurve):
                        if i_instance == 0:
                            o_obj = cmds.duplicate(o_toCurve)[0]
                        else:
                            o_obj = cmds.instance(o_toCurve)[0]
                    else:
                        cmds.warning("%s > B Does not exist" % (o_toCurve))
                        break
                l_objReturns.append(o_obj)
                l_tmpObjReturns.append(o_obj)
                o_path = cmds.pathAnimation(o_obj, o_target, f=b_consOri, fractionMode=True, followAxis="y", upAxis="z", worldUpType="vector")
                o_incomingConnection = cmds.listConnections("%s.uValue" % (o_path), destination=False, source=True)[0]
                cmds.cycleCheck(e=0)
                cmds.delete(o_incomingConnection)
                cmds.cycleCheck(e=1)
                cmds.setAttr("%s.uValue" % (o_path), l_uValues[z])
                if not b_consOri and not b_consPos:
                    o_incoming = cmds.listConnections("%s.rotateX" % (o_obj), destination=False, source=True)[0]
                    cmds.cycleCheck(e=0)
                    cmds.delete(o_incoming)
                    cmds.cycleCheck(e=1)
                if b_consOri and not b_consPos:
                    o_incomingX = cmds.listConnections("%s.translateX" % (o_obj), plugs=True, destination=False, source=True)[0]
                    o_incomingY = cmds.listConnections("%s.translateY" % (o_obj), plugs=True, destination=False, source=True)[0]
                    o_incomingZ = cmds.listConnections("%s.translateZ" % (o_obj), plugs=True, destination=False, source=True)[0]
                    cmds.disconnectAttr(o_incomingX, "%s.translateX" % (o_obj))
                    cmds.disconnectAttr(o_incomingY, "%s.translateY" % (o_obj))
                    cmds.disconnectAttr(o_incomingZ, "%s.translateZ" % (o_obj))
                if not b_consOri and b_consPos:
                    o_incomingX = cmds.listConnections("%s.rotateX" % (o_obj), plugs=True, destination=False, source=True)[0]
                    o_incomingY = cmds.listConnections("%s.rotateY" % (o_obj), plugs=True, destination=False, source=True)[0]
                    o_incomingZ = cmds.listConnections("%s.rotateZ" % (o_obj), plugs=True, destination=False, source=True)[0]
                    cmds.disconnectAttr(o_incomingX, "%s.rotateX" % (o_obj))
                    cmds.disconnectAttr(o_incomingY, "%s.rotateY" % (o_obj))
                    cmds.disconnectAttr(o_incomingZ, "%s.rotateZ" % (o_obj))
                    cmds.setAttr("%s.follow" % (o_path), b_consOri)
                if not b_consOri and b_orientWorld:
                    cmds.setAttr("%s.rotateX" % (o_obj), 0)
                    cmds.setAttr("%s.rotateY" % (o_obj), 0)
                    cmds.setAttr("%s.rotateZ" % (o_obj), 0)
                cmds.select(cl=True)
            o_loft = ""
            if i_loft > 0:
                if i_loft == 1:
                    o_loftPoly = cmds.loft(l_tmpObjReturns, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=1, rsn=True)
                    o_outcoming = cmds.listConnections("%s.outputSurface" % (o_loftPoly[1]), plugs=False, destination=True, source=False)[0]
                    o_loft = o_loftPoly[1]
                    l_loft.append(o_loftPoly[0])
                    cmds.setAttr("%s.polygonType" % (o_outcoming), 1)
                    cmds.setAttr("%s.format" % (o_outcoming), 2)
                    cmds.setAttr("%s.uType" % (o_outcoming), 3)
                    cmds.setAttr("%s.uNumber" % (o_outcoming), 1)
                    cmds.setAttr("%s.vType" % (o_outcoming), 3)
                    cmds.setAttr("%s.vNumber" % (o_outcoming), 1)
                if i_loft == 2:
                    cmds.loft(l_tmpObjReturns, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=0, rsn=True)
                if i_loft > 2:
                    cmds.warning("Loft type not recognized")
            cmds.select(cl=True)
            if b_parentHierarchy:
                if not b_consPos and not b_consOri:
                    l_tmpObjReturns.reverse()
                    for z in range(len(l_tmpObjReturns) - 1):
                        cmds.parent(l_tmpObjReturns[z], l_tmpObjReturns[z + 1])
                else:
                    cmds.warning("Objects cannot be in hierarchy, , they have transformations constraints")
            cmds.select(cl=True)
        if b_selectNewObjs:
            if l_objReturns != []:
                cmds.select(l_objReturns)
                if len(l_loft) > 0:
                    cmds.select(l_loft, add=True)
            else:
                if l_selIn != []:
                    cmds.select(l_selIn)
        else:
            if l_selIn != []:
                cmds.select(l_selIn)
    return(l_objReturns, l_targets, l_loft)
Esempio n. 54
0
def pixelizer():
	#grab object name
	objname = cmds.ls(sl=True).pop()
	
	#initial cube to be instanced
	cmds.polyCube(n='pixelcube')
	cmds.hide('pixelcube')
	
	#reselect the object to be pixelized
	cmds.select(objname)
	
	#selects all vertices
	cmds.ConvertSelectionToVertices()
	listofvertices = cmds.ls(selection=True)
	
	#this grabs the string that will be parsed to get the max number of vertices of the geo selected
	lestring = listofvertices.pop()
	
	#find the index of the last ':' and the index of the last ']' and grab the string in between these indices to get the max vertex number
	#ex: pCube1.vtx[0:7]
	begin = lestring.rfind(':')+1
	end = lestring.index(']')
	totalvertices = int(lestring[begin:end]) + 1
	
	print totalvertices
	
	#create a dictionary that stores 3-slot arrays that tell position of a vertex already drawn
	drawnvtxdict = {}
	
	#store number of boxes drawn
	boxnum = 0
	
	#for loop through number of vertices
	for vtxnum in range(0, totalvertices):
		#gets string to select specified vertex
		nextvtx = objname + '.vtx[' + str(vtxnum) + ']'
		cmds.select(nextvtx)
		#to get value of position (a 3 slot array), make the new instanced cubename, then create an array of the int values
		pos = cmds.xform(ws=True, q=True, t=True)
		x1 = str(int(pos[0]))
		y1 = str(int(pos[1]))
		z1 = str(int(pos[2]))
		intposstr = x1+','+y1+','+z1
		 
		#check if dictionary empty!!!!!! 
		if (drawnvtxdict.__len__() == 0):
			newcubename = 'pixelcube' + str(boxnum)
			cmds.select('pixelcube')
			cmds.instance(n=newcubename)
			cmds.xform(t=(int(pos[0]), int(pos[1]), int(pos[2])))
			cmds.showHidden(newcubename)
			drawnvtxdict[intposstr] = True
			boxnum+=1
		else:
			if (not intposstr in drawnvtxdict.keys()):
				newcubename = 'pixelcube' + str(boxnum)
				cmds.select('pixelcube')
				cmds.instance(n=newcubename)
				cmds.xform(t=(int(pos[0]), int(pos[1]), int(pos[2])))
				cmds.showHidden(newcubename)
				drawnvtxdict[intposstr] = True
				boxnum += 1
		
		print str(boxnum) + ' boxes drawn : ' + str(vtxnum+1) + ' of ' + str(totalvertices) + ' done'
	
	#selects all newly created blocks
	cmds.select('pixelcube*')
	
	#groups them together
	cmds.group(n='pixelated_obj')
	
	cmds.hide(objname)
Esempio n. 55
0
def make_uv_instance(*args):
    cmds.instance()
Esempio n. 56
0
	def tileScatter(self, copy_type="duplicate", pattern="even", align_axis = 1, srandom_rotate=Point(), srandom_translate=Point(),\
		srandom_scale=Point(), facing_sun = 0.0):
		""" copy_type = duplicate instance combine """
		""" pattern = even straight """
		selectionList = OpenMaya.MSelectionList()
		OpenMaya.MGlobal.getActiveSelectionList(selectionList)

		tileDAG = OpenMaya.MDagPath()
		selectionList.getDagPath(1, tileDAG)
		#print tileDAG.fullPathName()
		meshFn = OpenMaya.MFnMesh(tileDAG)
		bbox = meshFn.boundingBox()

		tile_bbox = BBox(min = Vector(bbox.min().x,bbox.min().y,bbox.min().z),max = Vector(bbox.max().x,bbox.max().y,bbox.max().z))
		if copy_type=="combine":
			tile_mesh = MayaMesh(dag=tileDAG)
			combine_tile_mesh = MayaMesh(dag=tileDAG,empty=1)
		else:
			tiles_group = cmds.group(empty=True, name="tile_scatter")
		for face in xrange(len(self.faces)):
			#print face,self.faces[face]
			maxy = self.vertices[self.faces[face][0]][align_axis]
			maxid1 = self.faces[face][0]
			face_vertices = []
			for i in xrange(len(self.faces[face])):
				vert = self.vertices[self.faces[face][i]]
				face_vertices += [Point(vert.x,vert.y,vert.z)]
				newy = vert[align_axis]
				if newy > maxy:
					maxy = newy
					maxid1 = self.faces[face][i]
			neighbors = self.findVertexNeighbor(maxid1,[face])
			maxy = self.vertices[neighbors[0]][align_axis]
			maxid2 = neighbors[0]
			for neighbor in neighbors:
				newy = self.vertices[neighbor][align_axis]
				if newy > maxy:
					maxy = newy
					maxid2 = neighbor
			normal = self.getNormal(face)
			edge = self.vertices[maxid2]-self.vertices[maxid1]

			oriented = Transform()
			oriented.from2Vectors(edge,normal)
			t_lookat = Transform()
			t_lookat.lookAt(Point(),edge,normal)
			
			for i in xrange(len(self.faces[face])):
				face_vertices[i] = oriented.applyTransform(face_vertices[i])

				#print face_vertices[i]
				#self.addVertex(face_vertices[i])
				if i == 0:
					minx = face_vertices[0].x
					maxx = face_vertices[0].x
					miny = face_vertices[0].y
					maxy = face_vertices[0].y
					z = face_vertices[0].z
				else:
					minx = min(minx,face_vertices[i].x)
					maxx = max(maxx,face_vertices[i].x)
					miny = min(miny,face_vertices[i].y)
					maxy = max(maxy,face_vertices[i].y)
			#self.addVertex(Point(minx,miny,z+0.3))
			#self.addVertex(Point(maxx,maxy,z+0.3))
			
			countx = int((maxx-minx)/float(tile_bbox[1].z-tile_bbox[0].z))
			county = int((maxy-miny)/float(tile_bbox[1].x-tile_bbox[0].x))
			if countx==0 or county==0: continue
			
			stepx = tile_bbox[1].z-tile_bbox[0].z
			stepy = tile_bbox[1].x-tile_bbox[0].x

			oriented.invert()

			enlarge = Transform()
			enlarge.scaleLocal(Vector((maxx-minx+stepx)/float(maxx-minx)*5,\
				(maxy-miny+stepy)/float(maxy-miny)*5,1),Vector(maxx*0.5+minx*0.5,maxy*0.5+miny*0.5,0))
			for i in xrange(len(face_vertices)):
				face_vertices[i] = enlarge.applyTransform(face_vertices[i])
				#self.addVertex(face_vertices[i])

			if copy_type=="duplicate" or copy_type=="instance":
				tile_group = cmds.group(empty=True, name="tile"+str(face))
				cmds.parent(tile_group, tiles_group, relative=True)
			for i in xrange(countx+1):
				random_translate = Point(random.uniform(-srandom_translate.x,srandom_translate.x),\
						random.uniform(-srandom_translate.y,srandom_translate.y),\
						random.uniform(-srandom_translate.z,srandom_translate.z))
				#print random_translate
				for j in xrange(county+1):
					
					random_rotate = Point(random.uniform(-srandom_rotate.x,srandom_rotate.x),\
						random.uniform(-srandom_rotate.y,srandom_rotate.y),\
						random.uniform(-srandom_rotate.z,srandom_rotate.z))
					
					if pattern == "even" and j%2: 
						newPoint = Point(stepx*0.5+minx+stepx*i+random_translate.x,\
							miny+stepy*j+random_translate.y,z+random_translate.z)
						self.addVertex(newPoint)
						if not pointInPoly(newPoint,face_vertices): continue
						newPoint = oriented.applyTransform(Point(stepx*0.5+minx+stepx*i+random_translate.x,\
							miny+stepy*j+random_translate.y,z+random_translate.z))
					
					if (pattern == "even" and not j%2) or pattern=="straight":
						newPoint = Point(minx+stepx*i+random_translate.x,\
							miny+stepy*j+random_translate.y,z+random_translate.z)
						self.addVertex(newPoint)
						if not pointInPoly(newPoint,face_vertices): continue
						newPoint = oriented.applyTransform(Point(minx+stepx*i+random_translate.x,\
							miny+stepy*j+random_translate.y,z+random_translate.z))

					rot = t_lookat.getEuler()
					if copy_type=="duplicate" or copy_type=="instance":

						if copy_type=="duplicate": newObjectDAG = cmds.duplicate(tileDAG.fullPathName(), ic=0)
						else: newObjectDAG = cmds.instance(tileDAG.fullPathName())
						scalePivot = cmds.xform(newObjectDAG, query=True, ws=True, sp=True)
						transform = cmds.xform(newObjectDAG, query=True, ws=True, t=True)
						cmds.xform(newObjectDAG, t=( (transform[0]-scalePivot[0])+newPoint.x,\
							(transform[1]-scalePivot[1])+newPoint.y, (transform[2]-scalePivot[2])+newPoint.z ))
						cmds.rotate(math.degrees(rot.x)+random_rotate.x,math.degrees(rot.y)+random_rotate.y,\
							math.degrees(rot.z)+random_rotate.z,newObjectDAG, os=True, r=True, rotateXYZ=True)
						cmds.parent(newObjectDAG, tile_group, relative=True)
					if copy_type=="combine":
						t_final = Transform()
						t_final.translate(newPoint)
						tx,ty,tz = Transform(),Transform(),Transform()
						if facing_sun!=0.0:
							rot = rot.lerp(Vector(),facing_sun)
						tx.rotateX(rot.x+random_rotate.x/50.0)
						ty.rotateY(rot.y+random_rotate.y/50.0)
						tz.rotateZ(rot.z+random_rotate.z/50.0)
						t_final = t_final*tx*ty*tz
						combine_tile_mesh.multiDuplicateTransform(tile_mesh,t_final)
			#end copy for
		if copy_type=="combine": combine_tile_mesh.meshToMaya()
Esempio n. 57
0


import maya.cmds as cmds
import maya.OpenMaya as OpenMaya

selection = cmds.ls(sl=True)

# Check if two or more obj selected
if len(selection) < 2:
    OpenMaya.MGlobal.displayError("Select at least two objects")

for object in selection[:-1]:
    
    cmds.select(selection[-1:])
    new_obj = cmds.instance()
    
    trans = cmds.xform(object, q=True, ws=True, rp=True)
    cmds.xform(new_obj, a=True, ws=True, t=trans)
    cmds.parent(new_obj, object)



VERSION 1.1



# Copy to locator

import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
Esempio n. 58
0
#this code randomises a selected instance
#select one object to scatter it around randomly
import maya.cmds as cmds
import random

#random.seed(90) - if you want the same random pattern
cubeList = cmds.ls( '*SID*' )
if len(cubeList)!=0:
	cmds.delete(cubeList)
	
sel=cmds.ls(orderedSelection=1)
item=sel[0]

obj_group = cmds.group( empty=True, name='RandomInstanceGrp#')

for i in range(0,50): #50 instances of obj
    curr = cmds.instance(item, name='instance#')
    cmds.parent(curr, obj_group)
    x=random.uniform(-10,10)
    y=random.uniform(0,20)
    z=random.uniform(-10,10)
    cmds.move(x, y, z, curr)
    
    xRot = random.uniform(0,360)
    yRot = random.uniform(0,360)#add random spin..
    zRot = random.uniform(0,360)
    
    cmds.rotate(xRot, yRot, zRot, curr) #move to location!
Esempio n. 59
0
cubeList = cmds.ls ('myCube*')

instanceGroupName = cmds.group(empty=True, name=transformName + '_instance_grp#')

if len(cubeList) > 0:
    cmds.delete(cubeList)

result = cmds.polyCube(w=1,h=1,d=1,name='myCube#')

#print 'result: ' + str(result)

transformName=result[0]

for i in range(0, 50):

    instanceResult=cmds.instance(transformName, name=transformName+'_instance#')
    
    #print 'instanceResult ' + str( instanceResult )
    
    cmds.parent(instanceResult, instanceGroupName)
    
    x=random.uniform(-10, 10)
    y=random.uniform(0,20)
    z=random.uniform(-10, 10)
    cmds.move(x, y, z, instanceResult)
    xRot=random.uniform(0,360)
    yRot=random.uniform(0,360)
    zRot=random.uniform(0,360)
    cmds.rotate(xRot,yRot,zRot, instanceResult)
    
    scalingFactor = random.uniform(0.3,1.5)
Esempio n. 60
0
		cmds.delete(sphereList)
	iterations = int(cmds.promptDialog(query=True, text=True))
	#area=(0.8, 0.8, 0.8) #initial growth area
	radius=0.5
	mandelbulbInstanceGrp=cmds.group(empty=True,name=thename+'_InstanceGrp#')
	mainSphereInstance=cmds.polySphere(n=thename+'_SphereMain', r=radius)
	
	itertemp=iterations
	newx=newy=newz=0
	for x in frange(0.5, 10, 0.5 ):
		for y in frange(0.5, 10, 0.5):
			for z in frange( 0.5, 10, 0.5):
				while(iterations):
					r = (x*x + y*y + z*z )**0.5
					theta = math.atan2((x*x + y*y)**0.5 , z)
					phi = math.atan2(y,x)
		
					newx = r**iterations * math.sin(theta*iterations) * math.cos(phi*iterations)
					newy = r**iterations * math.sin(theta*iterations) * math.sin(phi*iterations)
					newz = r**iterations * math.cos(theta*iterations)
					print "Processing: ", x, y, z, "for ", newx, newy, newz
					if (newx**2 + newy**2 + newz**2) < 8:
						break
					iterations=iterations-1
				currInstance=cmds.instance(mainSphereInstance, name=thename+'_Instance#')
				cmds.parent(currInstance, mandelbulbInstanceGrp)
				cmds.move( x, y, z, currInstance )
				newx=newy=newz=0
				iterations=itertemp