How to use Python gradientControlNoAttr

How to use Python gradientControlNoAttr

1140534355
Enthusiast Enthusiast
2,658 Views
32 Replies
Message 1 of 33

How to use Python gradientControlNoAttr

1140534355
Enthusiast
Enthusiast

Hello, everyone, I'm new to Python. I found gradientControlNoAttr layout in Python document today, but I don't know how to define this. I've been using def source_v(source_cv) function before, and I want to know how I can change it to gradientControlNoAttr, or if there is a case for reference.

####################################
def source_v(source_cv):
    attraction_profile = cmds.getAttr(source_cv + ".attractionProfile[*]")
    for cv in cmds.ls(sl=True, dag=True, typ="nurbsCurve"):
        point_num = len(cmds.getAttr(cv + ".attractionProfile[*]")) or 0  
        for i in range(point_num)[len(attraction_profile):]:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(cv, i), b=True)
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(cv, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(cv, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(cv, i), interp)
source_cv = cmds.ls(sl=True, dag=True, typ="nurbsCurve")[0]

#####################################
cmds.gradientControlNoAttr('attractionProfile', h=120)
cmds.gradientControlNoAttr('attractionProfile', ck=0,e=1)
cmds.rowLayout(nc=3)
cmds.floatFieldGrp('posFieldRadius', pre=3, l="Selected Position", nf=1, v1=0.000, s=1.0, cw=(1, 70))
cmds.floatFieldGrp('valFieldRadius', pre=3, l="Selected Value", nf=1, v1=1.000, s=1.0, cw=(1, 70))

cmds.optionMenuGrp('interpMenuRadius', cw=(1, 50), l="Interpolation")
cmds.menuItem(l="  None  ")
cmds.menuItem(l="  Linear  ")
cmds.menuItem(l="  Smooth  ")
cmds.menuItem(l="  Spline  ")
cmds.setParent( '..' )

04af9e59b891b09710cec41a2dc2b79.png 

0 Likes
Accepted solutions (4)
2,659 Views
32 Replies
Replies (32)
Message 21 of 33

1140534355
Enthusiast
Enthusiast
import maya.cmds as cmds
import maya.mel as mel

def getTheNurbsCurve():      
    source_curve = cmds.ls(sl=True, dag=True)
    if not source_curve:
        cmds.warning('No curve was selected')
        return
    else:
        source_curve = source_curve[0]
    
    # Check if the curve has "attractionProfile"
    if not cmds.objExists(source_curve + '.attractionProfile'):
        cmds.warning('{} is missing "attractionProfile"'.format(source_curve))
        source_curve = None   
    return source_curve        
    
def currentKeyChanged(currentData):
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return

    # Get the values for that key
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    if not currentData:
        return         
    a = currentData.split(',')
    posVal = float(a[currentIndex*3])
    valVal = float(a[currentIndex*3+1])
    interp = int(a[currentIndex*3+2])    
    # Update the two floatFields    
    cmds.floatFieldGrp('posFieldRadius', e = True, v =[posVal]*4)
    cmds.floatFieldGrp('valFieldRadius', e = True, v =[valVal]*4)
    interp=cmds.optionMenu(interp, query=True, value=[interp]*4)  
              
def posModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3+1] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)

def valModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)
        
def interpModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3+2] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)                
                                
    
def setUpRamp():  
    # This function will make the ramp in the UI match the existing values of the ramp curve
    attributeData = []
    for i in cmds.getAttr(source_curve + ".attractionProfile", mi = True) or []:
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Position".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(source_curve, i)))    
    # Set the data
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = str(attributeData))

def rampModified(gradient_data):
    # Convert the gradient_data from a unicode (string) to a list 
    gradient_data = gradient_data.split(',')# Split the string up 
    
    # We will convert each element from a string to a float or int
    data_list = []
    
    for i,s in enumerate(gradient_data):
        # If the elements index is a multiple of 3
        # we want it to be an int
        # since every third element represents the interpolation
        # we check for this by using modular arithmetic (the % sysmbol)
        if (i+1)%3 == 0:
            data_list.append(float(s))
        else:
            data_list.append(float(s))
            
    # Then we will split up the data into chunks of 3
    # so instead of having 1 list of data, we have a list of lists
    # where each element contains all the data for a specific cv
    print (type(len(data_list)/3))    
    attraction_profile = []
    for i in range(int(len(data_list)/3)):
        attraction_profile.append(data_list[i*3:(i*3)+3])
                
    source_curve=getTheNurbsCurve()
    # Do whatever it is you were doing with that data
    # THIS WILL AFFECT ALL THE CURVES NOT JUST THE ONE YOU 
    # SELECTED WHEN YOU LAUNCHED THE WINDOW
    for eachCurve in (cmds.ls(sl=True, dag=True) or []) + [source_curve]:
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
                
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
                        
                                                
def clear():
    # To do the clear we need to edit the attribute not the ui
    # since gradientControl keys can't be edited via command
    source_curve=getTheNurbsCurve()
    for eachCurve in (cmds.ls(sl=True, dag=True, typ="nurbsCurve") or []) + [source_curve]:
        # Remove all the data
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True)
            
        # Add the two standard keys back in with linear interpolation
        attraction_profiled = [[0,1,1],[1,1,1]]
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)                                                                                              

                       
def set__key():      
    source_curve = getTheNurbsCurve()
    for i in cmds.getAttr(source_curve + '.attractionProfile', mi = True):
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_Position'.format(i))
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_FloatValue'.format(i))
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_Interp'.format(i))                                                

    
if cmds.window("mayaTool", exists=True):
    cmds.deleteUI("mayaTool")

cmds.window("mayaTool", t="mayaTool",
          w=460, h=500, sizeable=True, mnb=True, mxb=False ,menuBar=True)
                    
 
                                        
###
cmds.scrollLayout('scrollLayout')
cmds.gradientControlNoAttr('attractionProfile', w=460, h = 120,ck=0,changeCommand = rampModified,)
cmds.rowLayout(nc=2)
cmds.button("reset", w=230, h=30, c="clear()", bgc=(0.4, 0.2, 0.3))
cmds.button("Set key", w=230, h=30, c="set__key()", bgc=(1, 0.05, 0))
cmds.setParent( '..' )    
cmds.separator(h=5)
# Add the other widgets
cmds.rowLayout(nc=3)         
cmds.floatFieldGrp('posFieldRadius', pre=3, l="Selected Position", nf=1, v1=0.000, s=1.0, cw=(1, 70), changeCommand = posModified)

cmds.floatFieldGrp('valFieldRadius', pre=3, l="Selected Value", nf=1, v1=1.000, s=1.0, cw=(1, 70), changeCommand = valModified)

cmds.gradientControlNoAttr('attractionProfile', e = True,currentKeyChanged = currentKeyChanged,)
interp=cmds.optionMenuGrp( cw=(1, 70), l="Interpolation",changeCommand = interpModified)
cmds.menuItem(l="  None  ")
cmds.menuItem(l="  Linear  ")
cmds.menuItem(l="  Smooth  ")
cmds.menuItem(l="  Spline  ")
cmds.setParent( '..' )

cmds.showWindow("mayaTool")
0 Likes
Message 22 of 33

jmreinhart
Advisor
Advisor
Accepted solution
import maya.cmds as cmds
import maya.mel as mel

def getTheNurbsCurve():      
    source_curve = cmds.ls(sl=True, dag=True)
    if not source_curve:
        cmds.warning('No curve was selected')
        return
    else:
        source_curve = source_curve[0]
    
    # Check if the curve has "attractionProfile"
    if not cmds.objExists(source_curve + '.attractionProfile'):
        cmds.warning('{} is missing "attractionProfile"'.format(source_curve))
        source_curve = None   
    return source_curve        
    
def currentKeyChanged(currentData):
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return

    # Get the values for that key
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    if not currentData:
        return         
    a = currentData.split(',')
    posVal = float(a[currentIndex*3])
    valVal = float(a[currentIndex*3+1])
    interp = int(a[currentIndex*3+2])    
    # Update the two floatFields    
    cmds.floatFieldGrp('posFieldRadius', e = True, v =[posVal]*4)
    cmds.floatFieldGrp('valFieldRadius', e = True, v =[valVal]*4)
    
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    print  interpStrings[interp]
    cmds.optionMenuGrp('interpolationMenu', e=True, value = interpStrings[interp])  
              
def posModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3+1] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)

def valModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)
        
def interpModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    val = interpStrings.index(val)

    a[currentIndex*3+2] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)                
                                
    
def setUpRamp():  
    # This function will make the ramp in the UI match the existing values of the ramp curve
    source_curve = getTheNurbsCurve()
    attributeData = []
    for i in cmds.getAttr(source_curve + ".attractionProfile", mi = True) or []:
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Position".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(source_curve, i)))    
    # Set the data
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = str(attributeData))

def rampModified(gradient_data):
    # Convert the gradient_data from a unicode (string) to a list 
    gradient_data = gradient_data.split(',')# Split the string up 
    
    # We will convert each element from a string to a float or int
    data_list = []
    
    for i,s in enumerate(gradient_data):
        # If the elements index is a multiple of 3
        # we want it to be an int
        # since every third element represents the interpolation
        # we check for this by using modular arithmetic (the % sysmbol)
        if (i+1)%3 == 0:
            data_list.append(float(s))
        else:
            data_list.append(float(s))
            
    # Then we will split up the data into chunks of 3
    # so instead of having 1 list of data, we have a list of lists
    # where each element contains all the data for a specific cv
    print (type(len(data_list)/3))    
    attraction_profile = []
    for i in range(int(len(data_list)/3)):
        attraction_profile.append(data_list[i*3:(i*3)+3])
                
    source_curve=getTheNurbsCurve()
    # Do whatever it is you were doing with that data
    # THIS WILL AFFECT ALL THE CURVES NOT JUST THE ONE YOU 
    # SELECTED WHEN YOU LAUNCHED THE WINDOW
    for eachCurve in (cmds.ls(sl=True, dag=True) or []) + [source_curve]:
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
                
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
                        
                                                
def clear():
    # To do the clear we need to edit the attribute not the ui
    # since gradientControl keys can't be edited via command
    source_curve=getTheNurbsCurve()
    for eachCurve in (cmds.ls(sl=True, dag=True, typ="nurbsCurve") or []) + [source_curve]:
        # Remove all the data
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True)
            
        # Add the two standard keys back in with linear interpolation
        attraction_profiled = [[0,1,1],[1,1,1]]
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)                                                                                              

                       
def set__key():      
    source_curve = getTheNurbsCurve()
    for i in cmds.getAttr(source_curve + '.attractionProfile', mi = True):
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_Position'.format(i))
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_FloatValue'.format(i))
        cmds.setKeyframe(source_curve + '.attractionProfile[{}].attractionProfile_Interp'.format(i))                                                

    
if cmds.window("mayaTool", exists=True):
    cmds.deleteUI("mayaTool")

cmds.window("mayaTool", t="mayaTool",
          w=460, h=500, sizeable=True, mnb=True, mxb=False ,menuBar=True)
                    
                                        
###
cmds.scrollLayout('scrollLayout')
cmds.gradientControlNoAttr('attractionProfile', w=460, h = 120,ck=0,changeCommand = rampModified,)
cmds.rowLayout(nc=2)
cmds.button("reset", w=230, h=30, c="clear()", bgc=(0.4, 0.2, 0.3))
cmds.button("Set key", w=230, h=30, c="set__key()", bgc=(1, 0.05, 0))
cmds.setParent( '..' )    
cmds.separator(h=5)
# Add the other widgets
cmds.rowLayout(nc=3)         
cmds.floatFieldGrp('posFieldRadius', pre=3, l="Selected Position", nf=1, v1=0.000, s=1.0, cw=(1, 70), changeCommand = posModified)
cmds.floatFieldGrp('valFieldRadius', pre=3, l="Selected Value", nf=1, v1=1.000, s=1.0, cw=(1, 70), changeCommand = valModified)
cmds.gradientControlNoAttr('attractionProfile', e = True,currentKeyChanged = currentKeyChanged)
cmds.optionMenuGrp('interpolationMenu', cw=(1, 70), l="Interpolation",changeCommand = interpModified)

cmds.menuItem(l="  None  ")
cmds.menuItem(l="  Linear  ")
cmds.menuItem(l="  Smooth  ")
cmds.menuItem(l="  Spline  ")
cmds.setParent( '..' )

cmds.showWindow("mayaTool")
setUpRamp()

The interp works now, and I fixed the issue where you were no longer loading the existing ramp from the selected curve.

 

 

0 Likes
Message 23 of 33

1140534355
Enthusiast
Enthusiast
Thank you, you're amazing. Can you get rid of that error? I tried many times, but I couldn't get rid of it.

Error: line 1: No object name specified. #
# Error: line 1: No object name specified. #
# Error: line 1: No object matches name: AttributeEditor|MainAttributeEditorLayout|formLayout98|AEmenuBarLayout|AErootLayout|AEStackLayout|AErootLayoutPane|AEbaseFormLayout|AEcontrolFormLayout|AttrEdnurbsCurveFormLayout|scrollLayout24|columnLayout361|frameLayout161|columnLayout771|columnLayout772|attractionProfileRampForm|attractionProfileSi
0 Likes
Message 24 of 33

jmreinhart
Advisor
Advisor

Did you run the code I sent, or copy a chunk of it over to yours?

0 Likes
Message 25 of 33

1140534355
Enthusiast
Enthusiast
Yes I reported an error when I modified the parameters, but it did not affect the use. By the way, actually, I don't want to open the UI directly to get parameters. I think there will be a default parameter for opening UI directly, such as Attraction _ Profiled = [[0,1,3], [1,1,3]]. I wanted it to be an executable function, but it doesn't seem to be executed now.
0 Likes
Message 26 of 33

jmreinhart
Advisor
Advisor

I do not get an error when I run my the code. And I can use all of the UI functions without error, except for reset.

 

What are you doing that is producing an error?

0 Likes
Message 27 of 33

1140534355
Enthusiast
Enthusiast
It will appear when I adjust the ramp curve, but it doesn't affect it. I'll change this slowly. Now I don't want to get parameters through (setUpRamp ()). I want to give UI a fixed parameter. What should I do to use it (attraction_profiled)
0 Likes
Message 28 of 33

jmreinhart
Advisor
Advisor

Use the code that is in setupRamp.

But Delete the getAttr, and put whatever data you want to have by default instead.

 

0 Likes
Message 29 of 33

jmreinhart
Advisor
Advisor

If your issue was solved please mark this post as solved.

Message 30 of 33

1140534355
Enthusiast
Enthusiast

Hello, now everything is fine in the code, but why after I reset it, the curve of UI interface will not become [[0,1,3],[1,1,3]], but [[0,1,3],[1,0,3]], even if I modify the parameters,
33d1ed4d52ec20734b59994e5fb4510.png

0 Likes
Message 31 of 33

jmreinhart
Advisor
Advisor

Could you post the code for your reset function? 

0 Likes
Message 32 of 33

1140534355
Enthusiast
Enthusiast

Hello, the current code is normal, but it needs to be changed to' 1,0,3,1,1,3'. It should be that pos and value are reversed, but I can't solve this problem after changing pos and value.

import maya.cmds as cmds
import maya.mel as mel


def getTheNurbsCurve():      
    source_curve = cmds.ls(sl=True, dag=True)
    if not source_curve:
        cmds.warning('No curve was selected')
        return
    else:
        source_curve = source_curve[0]
    
    # Check if the curve has "attractionProfile"
    if not cmds.objExists(source_curve + '.attractionProfile'):
        cmds.warning('{} is missing "attractionProfile"'.format(source_curve))
        source_curve = None   
    return source_curve        
    
def currentKeyChanged(currentData):
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return

    # Get the values for that key
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    if not currentData:
        return         
    a = currentData.split(',')
    posVal = float(a[currentIndex*3])
    valVal = float(a[currentIndex*3+1])
    interp = int(a[currentIndex*3+2])    
    # Update the two floatFields    
    cmds.floatFieldGrp('posFieldRadius', e = True, v =[posVal]*4)
    cmds.floatFieldGrp('valFieldRadius', e = True, v =[valVal]*4)
    
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    print  (interpStrings[interp])
    cmds.optionMenuGrp('interpolationMenu', e=True, value = interpStrings[interp])  
              
def posModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3+1] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)

def valModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)
        
def interpModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    val = interpStrings.index(val)

    a[currentIndex*3+2] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)                
                                
    
def setUpRamp():  
    # This function will make the ramp in the UI match the existing values of the ramp curve
    source_curve = getTheNurbsCurve()
    attributeData = []
    for i in cmds.getAttr(source_curve + ".attractionProfile", mi = True) or []:
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Position".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(source_curve, i)))    
    # Set the data
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = str(attributeData))

def rampModified(gradient_data):
    # Convert the gradient_data from a unicode (string) to a list 
    gradient_data = gradient_data.split(',')# Split the string up 
    
    # We will convert each element from a string to a float or int
    data_list = []
    
    for i,s in enumerate(gradient_data):
        # If the elements index is a multiple of 3
        # we want it to be an int
        # since every third element represents the interpolation
        # we check for this by using modular arithmetic (the % sysmbol)
        if (i+1)%3 == 0:
            data_list.append(float(s))
        else:
            data_list.append(float(s))
            
    # Then we will split up the data into chunks of 3
    # so instead of having 1 list of data, we have a list of lists
    # where each element contains all the data for a specific cv
    print (type(len(data_list)/3))    
    attraction_profile = []
    for i in range(int(len(data_list)/3)):
        attraction_profile.append(data_list[i*3:(i*3)+3])
                
    source_curve=getTheNurbsCurve()
    # Do whatever it is you were doing with that data
    # THIS WILL AFFECT ALL THE CURVES NOT JUST THE ONE YOU 
    # SELECTED WHEN YOU LAUNCHED THE WINDOW
    for eachCurve in (cmds.ls(sl=True, dag=True) or []) + [source_curve]:
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
                
        for i, (pos, value, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
                                                 

#########################

def clear(): 
    # To do the clear we need to edit the attribute not the ui # since gradientControl keys can't be edited via command 
    source_curve=getTheNurbsCurve()
        
    for eachCurve in (cmds.ls(sl=True, dag=True, typ="nurbsCurve") or []) + [source_curve]: 
    # Remove all the data
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []: 
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
    # Add the two standard keys back in with linear interpolation 
            attraction_profile = [[0,1,3],[1,1,3]] 
            for i, (pos, value, interp) in enumerate(attraction_profile):
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), pos) 
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), value)
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
            # Reset the ramp in the UI 
                currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = '1,0,3,1,1,3') 
        
#wingdow       
if cmds.window("mayaTool", exists=True):
    cmds.deleteUI("mayaTool")

cmds.window("mayaTool", t="mayaTool",
          w=460, h=500, sizeable=True, mnb=True, mxb=False ,menuBar=True)  
cmds.scrollLayout('scrollLayout')
#######                    
cmds.gradientControlNoAttr('attractionProfile', w=460, h = 120,ck=0,changeCommand = rampModified,currentKeyChanged = currentKeyChanged)

cmds.rowLayout(nc=8)    
cmds.button("rest", w=90, c="clear()")
#setUpRamp()
cmds.text("Position:")
cmds.floatFieldGrp('valFieldRadius', pre=3, nf=1, v1=1.000, s=1.0, cw=(1, 50), changeCommand = valModified)

cmds.text("Value:")
cmds.floatFieldGrp('posFieldRadius', pre=3,nf=1, v1=0.000, s=1.0, cw=(1, 50), changeCommand = posModified)


cmds.text("Interpolation:")
cmds.optionMenuGrp('interpolationMenu', cw=(1, 20),changeCommand = interpModified)

cmds.menuItem(l="  None  ")
cmds.menuItem(l="  Linear  ")
cmds.menuItem(l="  Smooth  ")
cmds.menuItem(l="  Spline  ")
                                        
                                                                                              
cmds.showWindow("mayaTool")  

setUpRamp()   

b556e43adaf8cf0eada2f84c5d063ee.png

0 Likes
Message 33 of 33

jmreinhart
Advisor
Advisor
Accepted solution

I reordered those bits of code so that the order is floatValue, Position, Interp Value for everything and now it behaves the way you want.

 

import maya.cmds as cmds
import maya.mel as mel


def getTheNurbsCurve():      
    source_curve = cmds.ls(sl=True, dag=True)
    if not source_curve:
        cmds.warning('No curve was selected')
        return
    else:
        source_curve = source_curve[0]
    
    # Check if the curve has "attractionProfile"
    if not cmds.objExists(source_curve + '.attractionProfile'):
        cmds.warning('{} is missing "attractionProfile"'.format(source_curve))
        source_curve = None   
    return source_curve        
    
def currentKeyChanged(currentData):
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return

    # Get the values for that key
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    if not currentData:
        return         
    a = currentData.split(',')
    posVal = float(a[currentIndex*3])
    valVal = float(a[currentIndex*3+1])
    interp = int(a[currentIndex*3+2])    
    # Update the two floatFields    
    cmds.floatFieldGrp('posFieldRadius', e = True, v =[posVal]*4)
    cmds.floatFieldGrp('valFieldRadius', e = True, v =[valVal]*4)
    
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    print  (interpStrings[interp])
    cmds.optionMenuGrp('interpolationMenu', e=True, value = interpStrings[interp])  
              
def posModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3+1] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)

def valModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    a[currentIndex*3] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)
        
def interpModified(val):
    # Change the position of the selected key
    currentIndex = cmds.gradientControlNoAttr('attractionProfile', q = True, currentKey = True)
    if currentIndex == -1:
        return
    
    currentData = cmds.gradientControlNoAttr('attractionProfile', q = True, asString = True)
    a = currentData.split(',')
    interpStrings = ['  None  ','  Linear  ','  Smooth  ','  Spline  ']  
    val = interpStrings.index(val)

    a[currentIndex*3+2] = str(val)
    newData = ','.join(a)
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = newData)                
                                
    
def setUpRamp():  
    # This function will make the ramp in the UI match the existing values of the ramp curve
    source_curve = getTheNurbsCurve()
    attributeData = []
    for i in cmds.getAttr(source_curve + ".attractionProfile", mi = True) or []:
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Position".format(source_curve, i)))
        attributeData.append(cmds.getAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(source_curve, i)))    
    # Set the data
    currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = str(attributeData))

def rampModified(gradient_data):
    # Convert the gradient_data from a unicode (string) to a list 
    gradient_data = gradient_data.split(',')# Split the string up 
    
    # We will convert each element from a string to a float or int
    data_list = []
    
    for i,s in enumerate(gradient_data):
        # If the elements index is a multiple of 3
        # we want it to be an int
        # since every third element represents the interpolation
        # we check for this by using modular arithmetic (the % sysmbol)
        if (i+1)%3 == 0:
            data_list.append(float(s))
        else:
            data_list.append(float(s))
            
    # Then we will split up the data into chunks of 3
    # so instead of having 1 list of data, we have a list of lists
    # where each element contains all the data for a specific cv
    print (type(len(data_list)/3))    
    attraction_profile = []
    for i in range(int(len(data_list)/3)):
        attraction_profile.append(data_list[i*3:(i*3)+3])
                
    source_curve=getTheNurbsCurve()
    # Do whatever it is you were doing with that data
    # THIS WILL AFFECT ALL THE CURVES NOT JUST THE ONE YOU 
    # SELECTED WHEN YOU LAUNCHED THE WINDOW
    for eachCurve in (cmds.ls(sl=True, dag=True) or []) + [source_curve]:
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []:
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
                
        for i, (value, pos, interp) in enumerate(attraction_profile):
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), value)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), pos)
            cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
                                                 

#########################

def clear(): 
    # To do the clear we need to edit the attribute not the ui # since gradientControl keys can't be edited via command 
    source_curve=getTheNurbsCurve()
        
    for eachCurve in (cmds.ls(sl=True, dag=True, typ="nurbsCurve") or []) + [source_curve]: 
    # Remove all the data
        for i in cmds.getAttr(eachCurve + ".attractionProfile", mi = True) or []: 
            cmds.removeMultiInstance("{}.attractionProfile[{}]".format(eachCurve, i), b=True) 
    # Add the two standard keys back in with linear interpolation 
            attraction_profile = [[1,0,3],[1,1,3]] 
            for i, (value, pos, interp) in enumerate(attraction_profile):
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_FloatValue".format(eachCurve, i), value)
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Position".format(eachCurve, i), pos) 
                cmds.setAttr("{}.attractionProfile[{}].attractionProfile_Interp".format(eachCurve, i), interp)
                
            # Reset the ramp in the UI 
                currentData = cmds.gradientControlNoAttr('attractionProfile', e = True, asString = '1,0,3,1,1,3') 
        
#wingdow       
if cmds.window("mayaTool", exists=True):
    cmds.deleteUI("mayaTool")

cmds.window("mayaTool", t="mayaTool",
          w=460, h=500, sizeable=True, mnb=True, mxb=False ,menuBar=True)  
cmds.scrollLayout('scrollLayout')
#######                    
cmds.gradientControlNoAttr('attractionProfile', w=460, h = 120,ck=0,changeCommand = rampModified,currentKeyChanged = currentKeyChanged)

cmds.rowLayout(nc=8)    
cmds.button("reset", w=90, c="clear()")
#setUpRamp()
cmds.text("Position:")
cmds.floatFieldGrp('valFieldRadius', pre=3, nf=1, v1=1.000, s=1.0, cw=(1, 50), changeCommand = valModified)

cmds.text("Value:")
cmds.floatFieldGrp('posFieldRadius', pre=3,nf=1, v1=0.000, s=1.0, cw=(1, 50), changeCommand = posModified)


cmds.text("Interpolation:")
cmds.optionMenuGrp('interpolationMenu', cw=(1, 20),changeCommand = interpModified)

cmds.menuItem(l="  None  ")
cmds.menuItem(l="  Linear  ")
cmds.menuItem(l="  Smooth  ")
cmds.menuItem(l="  Spline  ")
                                        
                                                                                              
cmds.showWindow("mayaTool")  

setUpRamp()   

 

0 Likes