Beispiel #1
0
def cam_bake():

    # creating a fresh camera 
    new_cam,new_cam_shape = cmds.camera(n = 'MM_camera')
    
    # parenting that camera with the selected camera  
    parent_newcam_node = cmds.parentConstraint(sele, new_cam, maintainOffset = False)


    # copying the selected camera image plane values including the sequence path and pasting that in to a newly created image plane which is connected to the new camera. 
    # If no source image available then its directly move on to the bake process. 
    source_image = cmds.listRelatives(cmds.listRelatives(sele))
    if source_image:
        source_image_shape = cmds.listRelatives(source_image)
        source_image_path = cmds.getAttr('%s.imageName' %source_image[0])    
       
        new_cam_image, new_cam_image_shape = cmds.imagePlane(camera = new_cam, fileName = source_image_path)
        cmds.copyAttr( source_image_shape, new_cam_image_shape, inConnections = True, values = True)
        cmds.setAttr ('%s.useFrameExtension'  %new_cam_image_shape, 0)

    # baking the new camera channels and deleting the constraint. 
    cmds.bakeResults( new_cam , time=(StartTime,EndTime) )
    cmds.delete(parent_newcam_node)
    
    # will enable the Image sequence option inside image plane. 
    if source_image:
        cmds.setAttr ('%s.useFrameExtension'  %new_cam_image_shape, 1)

    # transferring the camera setting 
    cmds.copyAttr( sele_shape,new_cam_shape,values = True)

    # cheching for any curves inside the camera shape, this is mainly to get the focal curve incase if available. And pasting that in to the new camera. 
    copy_keys = cmds.copyKey(sele_shape)
    if copy_keys:
        cmds.pasteKey(new_cam_shape)
    
    # creating a new group for the newly created camera. Add that under this group. 
    Render_camera_grp = cmds.group(n = 'RenderCamGroup', empty = True)
    cmds.parent(new_cam, Render_camera_grp)

    # locking the attributes. 
    cam_attr = ['translate', 'rotate', 'scale', 'focalLength', 'horizontalFilmAperture', 'verticalFilmAperture' ]

    for attr in cam_attr:
        cmds.setAttr('%s.%s' % (new_cam, attr) , lock = True)
    for i in range (0,3):
        cmds.setAttr('%s.%s' % (Render_camera_grp, cam_attr[i]) , lock = True)
def overrideTransfer(layerName):
    sourceObjSplit = sourceObj[0].split("|")
    sourceShapeSplit = sourceShape[0].split("|")                
    rawOverrides = mc.editRenderLayerAdjustment(layerName, query=True, layer=True )
    allOverrides = []
    if layerName == "defaultRenderLayer":
        pass
    else:    
        if rawOverrides == None:
            pass
        else:
            for x in rawOverrides:
                if "instObjGroup" in x:
                    pass
                elif x in allOverrides:
                    pass
                else:
                    allOverrides.append(x)
    
            for eachOverride in allOverrides:
                attrName=eachOverride.split(".")
                # match transform node overrides
                srcObjAttrCheck = mc.attributeQuery(attrName[-1],node=sourceObj[0],ex=True)
                if srcObjAttrCheck == True:            
                    if sourceObjSplit[-1]+"."+attrName[-1] in eachOverride:
                        for eachTarget in targetObjs:
                            mc.editRenderLayerAdjustment(eachTarget+"."+attrName[-1])
                            mc.copyAttr(sourceObj,eachTarget,values=True,attribute=[attrName[-1]])
                # match shape node overrides
                srcShapeAttrCheck = mc.attributeQuery(attrName[-1],node=sourceShape[0],ex=True)
                if srcShapeAttrCheck == True:
                    if sourceShapeSplit[-1]+"."+attrName[-1] in eachOverride:
                        attrType = mc.getAttr(eachOverride,type=True)                
                        if "float3" in attrType:
                            valueX = mc.getAttr(sourceShape[0]+"."+attrName[-1]+"X") 
                            valueY = mc.getAttr(sourceShape[0]+"."+attrName[-1]+"Y")
                            valueZ = mc.getAttr(sourceShape[0]+"."+attrName[-1]+"Z")                   
                            for eachShape in targetShapes:                                
                                mc.editRenderLayerAdjustment(eachShape+"."+attrName[-1])
                                mc.setAttr(eachShape+"."+attrName[-1]+"X",valueX)
                                mc.setAttr(eachShape+"."+attrName[-1]+"Y",valueY)
                                mc.setAttr(eachShape+"."+attrName[-1]+"Z",valueZ)
                        else:
                            value = mc.getAttr(sourceShape[0]+"."+attrName[-1])
                            for eachShape in targetShapes:
                                mc.editRenderLayerAdjustment(eachShape+"."+attrName[-1])
                                mc.setAttr(eachShape+"."+attrName[-1],value)
def copyAttrs(srcNode, destNode, *sAttrList, **kwargs):
    logMsg(log='all')

    if "values" not in kwargs:
        kwargs["values"] = True

    bDelete = kwargs.pop("delete", False)
    bCreate = kwargs.pop("create", False)

    sSrcNode = argToStr(srcNode)
    sDestNode = argToStr(destNode)

    mObj = api.getNode(sSrcNode)
    fnNode = om.MFnDependencyNode(mObj)

    sCopyAttrList = []
    for sAttr in sAttrList:
        if not getObject(sDestNode + "." + sAttr):
            if bCreate:
                mAttr = om.MFnAttribute(fnNode.attribute(sAttr))
                sAddAttrCmd = mAttr.getAddAttrCmd(False).replace(";", " {};".format(sDestNode))

                logMsg("Copy attr. '{}' from '{}' to '{}'."
                       .format(sAttr, sSrcNode, sDestNode), log="info")
                pm.mel.eval(sAddAttrCmd)
            else:
                sAttr = ""
        else:
            if bCreate:
                logMsg("Attr. '{}' already exists on '{}'.".format(sAttr, sDestNode), log="info")

        if sAttr:
            sCopyAttrList.append(sAttr)

    mc.copyAttr(sSrcNode, sDestNode, attribute=sCopyAttrList, **kwargs)
    #copyAttrState(sSrcNode, sDestNode , *sCopyAttrList)

    if bDelete:
        for sAttr in sCopyAttrList:
            mc.deleteAttr(sSrcNode + "." + sAttr)

    return sCopyAttrList
def copyAttrs(srcNode, destNode, *sAttrList, **kwargs):
    logMsg(log='all')

    if "values" not in kwargs:
        kwargs["values"] = True

    bDelete = kwargs.pop("delete", False)
    bCreate = kwargs.pop("create", False)

    sSrcNode = argToStr(srcNode)
    sDestNode = argToStr(destNode)

    mObj = api.getNode(sSrcNode)
    fnNode = om.MFnDependencyNode(mObj)

    sCopyAttrList = []
    for sAttr in sAttrList:
        if not getObject(sDestNode + "." + sAttr):
            if bCreate:
                mAttr = om.MFnAttribute(fnNode.attribute(sAttr))
                sAddAttrCmd = mAttr.getAddAttrCmd(False).replace(";", " {};".format(sDestNode))

                logMsg("Copy attr. '{}' from '{}' to '{}'."
                       .format(sAttr, sSrcNode, sDestNode), log="info")
                pm.mel.eval(sAddAttrCmd)
            else:
                sAttr = ""
        else:
            if bCreate:
                logMsg("Attr. '{}' already exists on '{}'.".format(sAttr, sDestNode), log="info")

        if sAttr:
            sCopyAttrList.append(sAttr)

    mc.copyAttr(sSrcNode, sDestNode, attribute=sCopyAttrList, **kwargs)
    #copyAttrState(sSrcNode, sDestNode , *sCopyAttrList)

    if bDelete:
        for sAttr in sCopyAttrList:
            mc.deleteAttr(sSrcNode + "." + sAttr)

    return sCopyAttrList
Beispiel #5
0
def makeCtrls(jnt):
     #grab selected joints
    selectedFK=cmds.ls(selection=True)
    #create nurbs circle(ctrl)
    controlx=cmds.circle(n=jnt + '_ctrl')
    #rotate and scale
    cmds.xform(ro=(90,0,0), s=(4.5,4.5,4.5))
    #selfGroup and name after joint
    grp=cmds.group(n=jnt + '_ctrl_grp')#*******I
    #position ctrl on selected joint
    con=cmds.parentConstraint( jnt, controlx[0] )
    cmds.delete(con)
    #freeze transformations of ctrl
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    #position grp on selected joint
    cmds.copyAttr(controlx[0],grp,v=True,at=['tx','ty','tz'])
    #center piviot of grp
    cmds.xform(cp=True)
    #freeze transformations of grp
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
Beispiel #6
0
def camTrackToCamDisp(camTrackName, camDispName):
    """ Create new camera from camTrack
        @param camTrackName: (str) : Camera track name
        @param camDispName: (str) : Camera disp name
        @return: (str) : Camera disp real name """
    print "Cam track to cam disp ..."
    #-- New Cam --#
    print "\tCreate new cam %s ..." % camDispName
    newCam = mc.camera()
    camDisp = mc.rename(newCam[0], camDispName)
    if mc.objExists(camTrackName) and mc.objExists(camDisp):
        #-- Transform --#
        print "\tTransfert cam track attributes and connections ..."
        mc.copyAttr(camTrackName, camDisp, ic=True, v=True)
        #-- Shape --#
        camTrackShape = mc.listRelatives(camTrackName, s=True, ni=True)[0]
        camDispShape = mc.listRelatives(camDisp, s=True, ni=True)[0]
        print "\tTransfert cam track shape attributes and connections ..."
        mc.copyAttr(camTrackShape, camDispShape, ic=True, v=True)
        return camDisp
    else:
        raise IOError, "!!! ERROR: Camera not valid !!!"
def overrideTransfer(layerName):
    sourceObjSplit = sourceObj[0].split("|")
    sourceShapeSplit = sourceShape[0].split("|")
    rawOverrides = mc.editRenderLayerAdjustment(layerName,
                                                query=True,
                                                layer=True)
    allOverrides = []
    if layerName == "defaultRenderLayer":
        pass
    else:
        if rawOverrides == None:
            pass
        else:
            for x in rawOverrides:
                if "instObjGroup" in x:
                    pass
                elif x in allOverrides:
                    pass
                else:
                    allOverrides.append(x)

            for eachOverride in allOverrides:
                attrName = eachOverride.split(".")
                # match transform node overrides
                srcObjAttrCheck = mc.attributeQuery(attrName[-1],
                                                    node=sourceObj[0],
                                                    ex=True)
                if srcObjAttrCheck == True:
                    if sourceObjSplit[-1] + "." + attrName[-1] in eachOverride:
                        for eachTarget in targetObjs:
                            mc.editRenderLayerAdjustment(eachTarget + "." +
                                                         attrName[-1])
                            mc.copyAttr(sourceObj,
                                        eachTarget,
                                        values=True,
                                        attribute=[attrName[-1]])
                # match shape node overrides
                srcShapeAttrCheck = mc.attributeQuery(attrName[-1],
                                                      node=sourceShape[0],
                                                      ex=True)
                if srcShapeAttrCheck == True:
                    if sourceShapeSplit[-1] + "." + attrName[
                            -1] in eachOverride:
                        attrType = mc.getAttr(eachOverride, type=True)
                        if "float3" in attrType:
                            valueX = mc.getAttr(sourceShape[0] + "." +
                                                attrName[-1] + "X")
                            valueY = mc.getAttr(sourceShape[0] + "." +
                                                attrName[-1] + "Y")
                            valueZ = mc.getAttr(sourceShape[0] + "." +
                                                attrName[-1] + "Z")
                            for eachShape in targetShapes:
                                mc.editRenderLayerAdjustment(eachShape + "." +
                                                             attrName[-1])
                                mc.setAttr(
                                    eachShape + "." + attrName[-1] + "X",
                                    valueX)
                                mc.setAttr(
                                    eachShape + "." + attrName[-1] + "Y",
                                    valueY)
                                mc.setAttr(
                                    eachShape + "." + attrName[-1] + "Z",
                                    valueZ)
                        else:
                            value = mc.getAttr(sourceShape[0] + "." +
                                               attrName[-1])
                            for eachShape in targetShapes:
                                mc.editRenderLayerAdjustment(eachShape + "." +
                                                             attrName[-1])
                                mc.setAttr(eachShape + "." + attrName[-1],
                                           value)
    def Rebuild(self):
        try:
            libraryPath = '//vfx-data-server/dsPipe/Library/asset/3D/lego/mBrick/'
            texturePath = '//vfx-data-server/dsPipe/Library/asset/3D/lego/mBrick/LEGO_Colors/'
            LODType = 'Cl.ma'
            try:
                name = cmds.ls('m*',long=True,type='transform',geometry=False,dependencyNodes=False,dagObjects=False,shapes=False,textures=False,materials=False)
                for each in name:
                    shapeList=[]
                    #print 'each='+each
                    meshName = each.split('|')[-1]
                    #print 'meshName='+str(meshName)
                    shapeName = cmds.listRelatives(each,type='shape')[-1]
                    shapeList = cmds.ls(shapeName, long=True)[0]
                    #print 'shapeName='+shapeName
                    #print 'shapeList='+shapeList
                    materialID = 0
                    try:
                        IDPath = shapeList+'.LEGO_materialID'
                        #print 'IDPath='+IDPath
                        materialID = cmds.getAttr(IDPath)
                        materialID = '%03d' % materialID
                        #print 'materialID=',materialID
                    except:
                        try:
                            shapeS = cmds.listConnections( shapeName,t="shadingEngine",s=True)[0]
                            shaderS = cmds.listConnections(shapeS,t="phongE")[0]
                            pattern = "(\D+)"
                            nameShader = re.search(pattern,shaderS)
                            nameShader = nameShader.group()
                            #print nameShader
                            lRed = cmds.getAttr(shaderS+'.colorR')
                            lGreen = cmds.getAttr(shaderS+'.colorG')
                            lBlue = cmds.getAttr(shaderS+'.colorB')
                            lRGB = int(lRed*255), int(lGreen*255) , int(lBlue*255)
                            #print lRGB
                            root = Lego_Assign_Shader.readLegoSXML()
                            for child in root:
                                if child.get("oldRGB") == lRGB:
                                    materialID = child.get("ID")
                                else:
                                    if child.get("name") == nameShader:
                                        materialID = child.get("ID")
                        except:
                            materialID = "000"
                            pass
                    #print materialID
                    removeLong = meshName.split('|')[-1]
                    #print 'removeLong='+removeLong
                    nName = removeLong.split('_')[0]
                    #print 'nName='+nName
                    filePath = libraryPath + nName + '/dev/maya/'
                    #Print files in filePath
                    os.chdir(filePath)
                    for files in os.listdir("."):
                        if files.endswith(".ma"):
                            filesRe = files.split("_") 
                            if filesRe[-1] == LODType:
                                files = files
                    filePath = filePath + files
                    if not os.path.exists(filePath):
                        print 'Not cleaned = ' + filePath
                        pass
                    else:
                        #print 'filePath='+filePath
                        importedFile = cmds.file( filePath, r=True, type='mayaAscii',returnNewNodes=True, namespace="LOD")
                        last = importedFile[-1]
                        #print 'last='+last
                        lastSplit = last.split('|')[1]
                        shadingAssign = last.split('|')[2]
                        #print 'lastSplit='+lastSplit
                        if materialID == 0:
                            shadingGrp = cmds.listConnections(shapeList, type="shadingEngine")[0]
                            #print 'shadingGrp='+shadingGrp
                            cmds.sets(shadingAssign, forceElement = shadingGrp)
                        else:
                            ### It looks at the materialID fetches that texture and assigns it to a Vray shader and assign it too the brick....
                            try:
                                print materialID
                                shader = Lego_Assign_Shader.main(materialID)

                            except Exception as e:
                                print e
                                print 'fail creating shadingNode'
                                pass
                            try:
                                cmds.sets(name='LegoS_'+str(materialID)+'SG', empty = True,renderable = True,noSurfaceShader = True)
                            except:
                                print 'fail creating SG'
                                pass
                            try:
                                cmds.connectAttr('LegoS_'+str(materialID)+'.outColor', 'LegoS_'+str(materialID)+'SG.surfaceShader',f = True)
                            except:
                                print 'fail connecting'
                                pass
                            try:
                                cmds.sets(shadingAssign, forceElement = 'LegoS_'+str(materialID)+'SG')
                            except:
                                print 'fail connecting mesh to shader'
                                pass
                        ### Parents back to the groupe it was from...
                        cmds.parent( lastSplit, cmds.pickWalk( each, direction='up' ))
                        ### Copys location and so on..
                        cmds.copyAttr(each ,lastSplit ,inConnections=True,values=True)
                        ### Deletes the old brick...
                        cmds.delete(each)
            except Exception as e:
                print 'ERROR:', e
                print 'Fail sort names'
                pass
        except Exception as e:
            print 'ERROR:', e
            print 'fail'
            pass
    def doConvert(self):
        #set current time to firsttime
        cmds.currentTime(self.firstframe)

        #delete old AbsoluteCamera.
        origNodes = cmds.ls('AbsoluteCamera*')
        if origNodes != []:
            for i in origNodes:
                try:
                    cmds.delete(i)
                except:
                    pass

        #########################################################################################################
        #create new camera to save translate data.
        self.newcameraShape = cmds.createNode('camera',
                                              skipSelect=True,
                                              n='AbsoluteCameraShape')
        self.newcameraTrans = cmds.listRelatives('AbsoluteCameraShape',
                                                 allParents=True)[0]

        #########################################################################################################
        #copy all the attribute of original camera to new camera
        cmds.copyAttr(self.camNode, self.newcameraTrans, values=True)
        cmds.copyAttr(self.camNodeShape, self.newcameraShape, values=True)
        camAnimList = cmds.listConnections(self.camNode,
                                           d=False,
                                           type='animCurve',
                                           scn=True)
        for i in camAnimList:
            attrName = cmds.connectionInfo(i + '.output',
                                           destinationFromSource=True)
            attrName = attrName[0].split('.')[-1]
            cmds.copyKey(self.camNode,
                         time=(self.firstframe, self.lastframe),
                         attribute=attrName,
                         option="curve")
            cmds.pasteKey(self.newcameraTrans,
                          time=(self.firstframe, self.lastframe),
                          attribute=attrName,
                          option='replace')

        #########################################################################################################
        #Change the relative animation of AbsoluteCameraShape to absolute.
        grdAnimList = cmds.listConnections(self.grdNode,
                                           d=False,
                                           type='animCurve',
                                           scn=True)
        camConnectNode = None
        #newcamAnimList = cmds.listConnections( self.newcameraTrans , d = False , type = 'animCurve' , scn = True)
        if grdAnimList != None:
            for i in grdAnimList:
                i = i.encode('utf8')
                attrName = cmds.connectionInfo(i + '.output',
                                               destinationFromSource=True)
                attrName = attrName[0].split('.')[-1]
                firstframevalue = cmds.getAttr(i + ".output",
                                               time=self.firstframe)

                for frame in range(int(self.firstframe),
                                   int(self.lastframe) + 1):
                    camvalue = cmds.getAttr(self.camNode + "." + attrName,
                                            time=frame)
                    cmds.setKeyframe(self.newcameraTrans,
                                     at=attrName,
                                     t=frame,
                                     v=camvalue,
                                     itt='Spline',
                                     ott='Spline')

                for frame in range(int(self.firstframe),
                                   int(self.lastframe) + 1):
                    grdvalue = cmds.getAttr(i + ".output", time=frame)
                    camvalue = cmds.getAttr(self.camNode + "." + attrName,
                                            time=frame)
                    temp = firstframevalue - grdvalue + camvalue
                    #print temp
                    cmds.setKeyframe(self.newcameraTrans,
                                     at=attrName,
                                     t=frame,
                                     v=temp,
                                     itt='Spline',
                                     ott='Spline')

        #########################################################################################################
        #Change the relative animation of train to absolute.
        if self.CtrNode != '':
            grdAnimList = cmds.listConnections(self.grdNode,
                                               d=False,
                                               type='animCurve',
                                               scn=True)
            if grdAnimList != None:
                for i in grdAnimList:
                    print i
                    i = i.encode('utf8')
                    attrName = cmds.connectionInfo(i + '.output',
                                                   destinationFromSource=True)
                    attrName = attrName[0].split('.')[-1]
                    firstframevalue = cmds.getAttr(i + ".output",
                                                   time=self.firstframe)

                    for frame in range(int(self.firstframe),
                                       int(self.lastframe) + 1):
                        Ctrvalue = cmds.getAttr(self.CtrNode + "." + attrName,
                                                time=frame)
                        cmds.setKeyframe(self.CtrNode,
                                         at=attrName,
                                         t=frame,
                                         v=Ctrvalue,
                                         itt='Spline',
                                         ott='Spline')

                    for frame in range(int(self.firstframe),
                                       int(self.lastframe) + 1):
                        grdvalue = cmds.getAttr(i + ".output", time=frame)
                        Ctrvalue = cmds.getAttr(self.CtrNode + "." + attrName,
                                                time=frame)
                        temp = firstframevalue - grdvalue + Ctrvalue
                        #print temp
                        cmds.setKeyframe(self.CtrNode,
                                         at=attrName,
                                         t=frame,
                                         v=temp,
                                         itt='Spline',
                                         ott='Spline')

        #########################################################################################################
        #Remove the animation of ground.
        grdAnimList = cmds.listConnections(self.grdNode,
                                           d=False,
                                           type='animCurve',
                                           scn=True)
        if grdAnimList != None:
            for i in grdAnimList:
                i = i.encode('utf8')
                attrName = cmds.connectionInfo(i + '.output',
                                               destinationFromSource=True)
                attrName = attrName[0].split('.')[-1]
                #print attrName,i + ".output",self.grdNode + "." + attrName
                cmds.disconnectAttr(i + ".output",
                                    self.grdNode + "." + attrName)

        return True
Beispiel #10
0
    def doConvert(self):
        #set current time to firsttime
        cmds.currentTime(self.firstframe)

        #########################################################################################################
        #create new camera to save translate data.
        self.newcameraShape = cmds.createNode('camera',
                                              skipSelect=True,
                                              n='AbsoluteNewCameraShape')
        self.newcameraTrans = cmds.listRelatives('AbsoluteNewCameraShape',
                                                 allParents=True)[0]

        #########################################################################################################
        #copy all the attribute of original camera to new camera
        cmds.copyAttr(self.camNode, self.newcameraTrans, values=True)
        cmds.copyAttr(self.camNodeShape, self.newcameraShape, values=True)

        if cmds.listConnections(
                self.camNode, d=False, type='animCurve', scn=True) != None:
            camAnimList = cmds.listConnections(self.camNode,
                                               d=False,
                                               type='animCurve',
                                               scn=True)
            for i in camAnimList:
                attrName = cmds.connectionInfo(i + '.output',
                                               destinationFromSource=True)
                attrName = attrName[0].split('.')[-1]
                cmds.copyKey(self.camNode,
                             time=(self.firstframe, self.lastframe),
                             attribute=attrName,
                             option="curve")
                cmds.pasteKey(self.newcameraTrans,
                              time=(self.firstframe, self.lastframe),
                              attribute=attrName,
                              option='replace')
        else:
            pass

        #########################################################################################################
        #Change the relative animation of AbsoluteCameraShape to absolute.
        #grdAnimList    = ['constraintTranslateX','constraintTranslateY','constraintTranslateZ','constraintRotateX','constraintRotateY','constraintRotateZ']
        grdAnimList = [
            'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY',
            'rotateZ'
        ]
        camConnectNode = None

        #newcamAnimList = cmds.listConnections( self.newcameraTrans , d = False , type = 'animCurve' , scn = True)
        if grdAnimList != None:
            for i in grdAnimList:
                #j = i.strip('constraint')
                #j = j.replace('T','t')
                #j = j.replace('R','r')
                j = i
                #attrName = cmds.connectionInfo( self.grdNode + "." + i , destinationFromSource=True )
                for frame in range(int(self.firstframe),
                                   int(self.lastframe) + 1):
                    print self.grdNode + "." + i, self.camNode + "." + j
                    grdvalue = cmds.getAttr(self.grdNode + "." + i, time=frame)
                    camvalue = cmds.getAttr(self.camNode + "." + j, time=frame)
                    temp = grdvalue + camvalue
                    print grdvalue, camvalue
                    cmds.setKeyframe(self.newcameraTrans,
                                     at=j,
                                     t=frame,
                                     v=temp,
                                     itt='Spline',
                                     ott='Spline')

        return True
    def Rebuild(self):
        try:
            libraryPath = '/dsPipe/Library/asset/3D/Bricks/mBricks/'
            texturePath = '/dsPipe/Library/asset/3D/Bricks/LEGO_Colors/'
            #libraryPath = 'C:\Users\Per\Documents\Test'
            #print 'libraryPath='+libraryPath
            try:
                name = cmds.ls('m*',long=True,type='transform',geometry=False,dependencyNodes=False,dagObjects=False,shapes=False,textures=False,materials=False)
                for each in name:
                    shapeList=[]
                    #print 'each='+each
                    meshName = each.split('|')[-1]
                    #print 'meshName='+str(meshName)
                    shapeName = cmds.listRelatives(each,type='shape')[-1]
                    shapeList = cmds.ls(shapeName, long=True)[0]
                    #print 'shapeName='+shapeName
                    #print 'shapeList='+shapeList
                    materialID = 0
                    try:
                        IDPath = shapeList+'.LEGO_materialID'
                        #print 'IDPath='+IDPath
                        materialID = cmds.getAttr(IDPath)
                        materialID = '%03d' % materialID
                        #print 'materialID=',materialID
                    except:
                        try:
                            shapeS = cmds.listConnections( shapeName,t="shadingEngine",s=True)[0]
                            shaderS = cmds.listConnections(shapeS,t="phongE")[0]
                            pattern = "(\D+)"
                            nameShader = re.search(pattern,shaderS)
                            nameShader = nameShader.group()
                            #print nameShader
                            lRed = cmds.getAttr(shaderS+'.colorR')
                            lGreen = cmds.getAttr(shaderS+'.colorG')
                            lBlue = cmds.getAttr(shaderS+'.colorB')
                            lRGB = int(lRed*255), int(lGreen*255) , int(lBlue*255)
                            #print lRGB
                            root = Lego_Assign_Shader.readLegoSXML()
                            for child in root:
                                if child.get("oldRGB") == lRGB:
                                    materialID = child.get("ID")
                                else:
                                    if child.get("name") == nameShader:
                                        materialID = child.get("ID")
                        except:
                            materialID = "000"
                            pass
                    #print materialID
                    removeLong = meshName.split('|')[-1]
                    #print 'removeLong='+removeLong
                    nName = removeLong.split('_')[0]
                    #print 'nName='+nName
                    #filePath = libraryPath +"/" + nName +'_LOD2.ma'
                    filePath = libraryPath + nName + '/dev/maya/' + nName +'_Cl.ma'
                    #print 'file dont exist = '+filePath
                    if not os.path.exists(filePath):
                        print 'Not cleaned = '+filePath
                        pass
                    else:
                        #print 'filePath='+filePath
                        importedFile = cmds.file( filePath, r=True, type='mayaAscii',returnNewNodes=True, namespace='LOD')
                        last = importedFile[-1]
                        #print 'last='+last
                        lastSplit = last.split('|')[1]
                        shadingAssign = last.split('|')[2]
                        #print 'lastSplit='+lastSplit
                        if materialID == 0:
                            shadingGrp = cmds.listConnections(shapeList, type="shadingEngine")[0]
                            #print 'shadingGrp='+shadingGrp
                            cmds.sets(shadingAssign, forceElement = shadingGrp)
                        else:
                            ### It looks at the materialID fetches that texture and assigns it to a Vray shader and assign it too the brick....
                            try:
                                print materialID
                                shader = Lego_Assign_Shader.main(materialID)
                                '''shader = 'LegoS_'+str(materialID)
                                cmds.shadingNode( 'VRayMtl' , asShader=True, name=shader)
                                texturePath = '/dsPipe/Library/Asset/Bricks/LEGO_Colors/'+str(materialID)+'.png'
                                inTexture = 'color_'+str(materialID)
                                outTexture = 'place2dTexture_color_'+str(materialID)
                                cmds.shadingNode('file',name = inTexture, asTexture=True);
                                cmds.shadingNode('place2dTexture',name = outTexture, asUtility = True)
                                cmds.connectAttr(outTexture+'.outUV', inTexture+'.uvCoord', f=True)
                                cmds.connectAttr(outTexture+'.outUvFilterSize', inTexture+'.uvFilterSize', f=True)
                                cmds.connectAttr(outTexture+'.coverage', inTexture+'.coverage', f=True)
                                cmds.connectAttr(outTexture+'.translateFrame', inTexture+'.translateFrame', f=True)
                                cmds.connectAttr(outTexture+'.rotateFrame', inTexture+'.rotateFrame', f=True)
                                cmds.connectAttr(outTexture+'.mirrorU', inTexture+'.mirrorU', f=True)
                                cmds.connectAttr(outTexture+'.mirrorV', inTexture+'.mirrorV', f=True)
                                cmds.connectAttr(outTexture+'.stagger', inTexture+'.stagger', f=True)
                                cmds.connectAttr(outTexture+'.wrapU', inTexture+'.wrapU', f=True)
                                cmds.connectAttr(outTexture+'.wrapV', inTexture+'.wrapV', f=True)
                                cmds.connectAttr(outTexture+'.repeatUV', inTexture+'.repeatUV', f=True)
                                cmds.connectAttr(outTexture+'.vertexUvOne', inTexture+'.vertexUvOne', f=True)
                                cmds.connectAttr(outTexture+'.vertexUvTwo', inTexture+'.vertexUvTwo', f=True)
                                cmds.connectAttr(outTexture+'.vertexUvThree', inTexture+'.vertexUvThree', f=True)
                                cmds.connectAttr(outTexture+'.vertexCameraOne', inTexture+'.vertexCameraOne', f=True)
                                cmds.connectAttr(outTexture+'.noiseUV', inTexture+'.noiseUV', f=True)
                                cmds.connectAttr(outTexture+'.offset', inTexture+'.offset', f=True)
                                cmds.connectAttr(outTexture+'.rotateUV', inTexture+'.rotateUV', f=True)
                                cmds.setAttr(inTexture+'.fileTextureName',str(texturePath),type = "string" )
                                cmds.defaultNavigation(destination=shader, source=inTexture, connectToExisting=True)
                                cmds.setAttr(inTexture+'.filterType', 0)

                                cmds.setAttr(shader+'.brdfType', 0)
                                cmds.setAttr(shader+'.traceReflections', 0)
                                cmds.setAttr(shader+'.hilightGlossinessLock', 0)
                                cmds.setAttr(shader+'.reflectionColor',0.2, 0.2, 0.2, type="double3" )
                                cmds.setAttr(shader+'.hilightGlossiness',0.4)
                                cmds.setAttr(shader+'.reflectionsMaxDepth', 1)
                                cmds.setAttr(shader+'.refractionsMaxDepth', 1)'''
                            except Exception as e:
                                print e
                                print 'fail creating shadingNode'
                                pass
                            try:
                                cmds.sets(name='LegoS_'+str(materialID)+'SG', empty = True,renderable = True,noSurfaceShader = True)
                            except:
                                print 'fail creating SG'
                                pass
                            try:
                                cmds.connectAttr('LegoS_'+str(materialID)+'.outColor', 'LegoS_'+str(materialID)+'SG.surfaceShader',f = True)
                            except:
                                print 'fail connecting'
                                pass
                            try:
                                cmds.sets(shadingAssign, forceElement = 'LegoS_'+str(materialID)+'SG')
                            except:
                                print 'fail connecting mesh to shader'
                                pass
                        ### Parents back to the groupe it was from...
                        cmds.parent( lastSplit, cmds.pickWalk( each, direction='up' ))
                        ### Copys location and so on..
                        cmds.copyAttr(each ,lastSplit ,inConnections=True,values=True)
                        ### Deletes the old brick...
                        cmds.delete(each)
            except Exception as e:
                print 'ERROR:', e
                print 'Fail sort names'
                pass
        except Exception as e:
            print 'ERROR:', e
            print 'fail'
            pass
Beispiel #12
0
    def apply(self):
        if self.awesomeCheckbox.isChecked() == 1 and self.legendaryCheckbox.isChecked() == 1:
            cmds.error("lawyered!")
        
        if self.cb_source.currentText() == self.cb_target.currentText():
            cmds.error("source and target objects are same!")
        else:
            #setup variables 
            m_sub = self.cb_source.currentText()
            m_obj = self.cb_target.currentText()
            drawTriangle(m_sub, 
                            self.sb_source_v1.value(), 
                            self.sb_source_v2.value(), 
                            self.sb_source_v3.value())
            drawTriangle(m_obj, 
                            self.sb_target_v1.value(), 
                            self.sb_target_v2.value(), 
                            self.sb_target_v3.value())
            #setting up the locators for align two meshes.
            sub = 'triangle_' + m_sub
            obj = 'triangle_' + m_obj
            setLocators(sub)
            setLocators(obj)

            #move subjector's locators to object's locators
            sl = 'locator_normal_aim_' + sub
            ol = 'locator_normal_aim_' + obj
            cmds.copyAttr(ol, sl,values=True,attribute=['tx','ty','tz'])

            sl = 'locator_center_' + sub
            ol = 'locator_center_' + obj
            cmds.copyAttr(ol, sl,values=True,attribute=['tx','ty','tz'])

            sl = 'locator_for_z_' + sub
            ol = 'locator_for_z_' + obj
            cmds.copyAttr(ol, sl,values=True,attribute=['tx','ty','tz'])

            #set subject pivot to object center
            goto = cmds.getAttr('locator_center_' + obj +'.t')
            
            #g = np.array(goto[0])
            g = [float(goto[0][0]), float(goto[0][1]), float(goto[0][2])]
            
            cmds.move(g[0],g[1],g[2], sub + '.scalePivot')
            cmds.move(g[0],g[1],g[2], sub + '.rotatePivot')

            #set scale of subject
            s = getVertexDistance(obj,0,1) / getVertexDistance(sub,0,1)
            cmds.makeIdentity(sub, apply=1, t=0,s=1,r=0)
            cmds.scale(s,s,s, sub)
            cmds.parent(m_sub, world=1)
            cmds.parent(m_obj, world=1)
            
            sl = 'locator_normal_aim_' + sub
            ol = 'locator_normal_aim_' + obj
            cmds.delete(sl)
            cmds.delete(ol)

            sl = 'locator_center_' + sub
            ol = 'locator_center_' + obj
            cmds.delete(sl)
            cmds.delete(ol)

            sl = 'locator_for_z_' + sub
            ol = 'locator_for_z_' + obj
            cmds.delete(sl)
            cmds.delete(ol)
            
            cmds.makeIdentity(m_sub, apply=1, t=1,s=1,r=1)
            cmds.select(m_sub)
            cmds.move(0,0,0, m_sub + '.scalePivot')
            cmds.move(0,0,0, m_sub + '.rotatePivot')
            cmds.DeleteHistory()
Beispiel #13
0
def transfer_attr(source, child, inConnections):
    if inConnections:
        cmds.copyAttr(source, child, values=True, inConnections=True)
    else:
        cmds.copyAttr(source, child, values=True)