Search - User list
Full Version: Save ramp presets
Root » Technical Discussion » Save ramp presets
papsphilip
How can i save ramps presets without using the "save preset" button from the gear icon?

i have an hda with lots of parameters and i don't want to create a new preset for every ramp i want to save.
Ideal interface would be a drop down menu and a save button next to my ramp parameter.

Could i export the ramp as a json file in my HIP dir and append to that each time i press save? then load the selected ramp from the drop down menu somehow (menu would be populated by the json file).
i am thinking python module but i am not sure about this

if writing the ramps in an external file is the way to go, how would i do that and then read the data back?

Any tips on the workflow would be much appreciated!
papsphilip
baby step 1

made a dictionary of the ramp parameters

import json

node = kwargs['node']
ramp = node.parm('ramp').multiParmInstances()
num = node.parm('ramp').multiParmInstancesPerItem()

dict = {
    'point': []
}

for p in ramp:
    data = {}
    for i in range(num): 
        if str(i+1) in p.name():
            value = p.eval()
            name = p.name()
           
            data[name] = value 
    dict['point'].append(data)
            
print(dict)

next step is to make a correct json structure (one entry per ramp point holding pos val and interpolation values) and save it to disk
papsphilip
baby step 2
corrected the json structure

import json

node = kwargs['node']
ramp = node.parm('ramp').multiParmInstances()
num = node.parm('ramp').multiParmInstancesPerItem()

dict = {
    'point': []
}

for i in range(num): 
    data={}
    for p in ramp:
        if str(i+1) in p.name():
            value = p.eval()
            name = p.name()
        
            data[name] = value 
            
    dict['point'].append(data)   
    
print(dict)

next step is to append different ramp presets to the same json
and the step after that is to load them
papsphilip
baby step 3
append or overwrite options with pop up window
import json
import os

path = hou.hipFile.path().rsplit('/',1)[0] + '/ramp_presets/'
if not os.path.exists(path):
    os.makedirs(path)

node=kwargs['node']
parm = node.parm('ramp')
ramp = parm.evalAsRamp()
interplookup = [hou.rampBasis.Constant, hou.rampBasis.Linear, hou.rampBasis.CatmullRom, hou.rampBasis.MonotoneCubic, hou.rampBasis.Bezier, hou.rampBasis.BSpline, hou.rampBasis.Hermite]

keylist = []
for i,key in enumerate(ramp.keys()):
    data = { "pos": i,
             "value": ramp.values()[i],
             "interp": interplookup.index(ramp.basis()[i])}    
    keylist.append(data)

dict = { 'ramp_name': keylist }

filepath = path + 'test.json'
json_data = json.dumps(dict, indent=4)

if os.path.isfile(filepath) and os.path.getsize(filepath)>0: #if file exists and is not zero bytes
    user = hou.ui.displayMessage('a file already exists',buttons=('Append','Overwrite',)) 
    
    if user==0:
        with open(filepath,'a') as f:
            f.write(json_data)
    if user==1:
        os.remove(filepath)
        with open(filepath,'w') as f:
            f.write(json_data)       
else:
    with open(filepath,'w') as f:
        f.write(json_data)

by the way a different approach to constructing the dictionary was given by tamte aka Tomas Slancik
papsphilip
after lots of baby steps...
ok i finished the HDA for saving ramp presets and loading them back in.
Saman_batham
can we change ramps using a slider is that possible if we have same no. of points in ramp
papsphilip
Do you mean a slider for each point on the ramp?
Jikian
Saman_batham
can we change ramps using a slider is that possible if we have same no. of points in ramp

Ramp parameters are essentially multiparms - you can reference each point's position/value parameter directly if you read the "index" value. If you have a ramp parameter with a fixed number of points, you can channel-reference each point's Value independently.
Yader
papsphilip
after lots of baby steps...
ok i finished the HDA for saving ramp presets and loading them back in.

Thanks a bunch for this, but I get an error message for folder where I have read/write rights:

Traceback (most recent call last):
File "FP::dev::Sop/ramp::1.2/save", line 1, in <module>
File "FP::dev::Sop/ramp::1.2, PythonModule", line 57, in Save
PermissionError: [ErrnoTraceback (most recent call last):
File "

And is it also possible to save RGB ramps?

Thanks in advance!
fr_3D
Thanks @papsphilip and @tamte for this solution! For an HDA with many parameters I wanted to export all parameters including color and float ramps as well as multiparms, so I extended the script a bit. Now it seems like all standard parameter types are supported. While ramps are detected automatically, for now multiparms need to be manually defined in the script. Does anyone know a way to isolate multiparms in Python?

### Global

import json, os

# Manually Define Multiparms Here
mplist = ['mp_a', 'mp_b', 'mp_c']

# Wrappers for Separating Ramp, Standard and Multiparm Data in the .json File
stdgroup = 'standard'
rampgroup = 'ramps'
mpgroup = 'multiparms'

### Export Parameters

def write_params(kwargs):
        
    hda = kwargs['node']
    params = hda.parmsInFolder(['Parameters'])

    from sys import platform
    
    dir = hda.parm('path').evalAsString() + '/cache/'
    # Windows and MacOS Handle File Paths Slightly Different
    if platform == 'darwin':
        dir = hda.parm('path').evalAsString() + 'cache/'
    
    filepath = dir + '_config_' + hda.parm('preset').evalAsString() + '.json'
    
    data = {}
    ramp = {}
    ramps = {}
    mp = {}

    for parm in params:
        if not parm.isHidden():
  
            # Loop Through Ramp Parameters
            if parm.isMultiParmParent():
            
                rampname = parm.name()
                ramp = parm.evalAsRamp()
                interplookup = [hou.rampBasis.Constant, hou.rampBasis.Linear, hou.rampBasis.CatmullRom, hou.rampBasis.MonotoneCubic, hou.rampBasis.Bezier, hou.rampBasis.BSpline, hou.rampBasis.Hermite]
    
                keylist = []
                for i,key in enumerate(ramp.keys()):
                    rampdata = { 'posindex': i,
                        'pos' : key,   
                        'value': ramp.values()[i],
                        'interp': interplookup.index(ramp.basis()[i])}    
                    keylist.append(rampdata)

                ramp = { rampname: keylist }
                ramps.update(ramp)
                
                # <continue> ends the for loop’s current iteration
                continue

            # Write Standard Parameters
            data[parm.name()] = parm.eval()

    # Loop Through Multiparms
    for mpi in mplist:
        mparam = hda.parm(mpi)

        mp_inst = {
            mpi: []
        }
        
        num = hda.parm(mpi).evalAsInt()
        instances = hda.parm(mpi).multiParmInstances()

        for i in range(num):
    
            block_data = {}
            for instance in instances:
                if instance.name().find(str(i+1)) >=0:
                    name = instance.name()
                    value = instance.eval()
                    block_data[name] = value
            mp_inst[mpi].append(block_data)
            mp.update(mp_inst)
            #print('........\n')

    # Wrapper for Standard Parameters
    datas = { stdgroup: data }

    # Wrapper for Ramp Parameters
    ramps = { rampgroup: ramps } 

    # Wrapper for Multiparms
    mps = { mpgroup: mp }

    # Append Ramp Values to the Final Dictionary
    datas.update(ramps)

    # Append the Mltiparm Values to the Final Dictionary
    datas.update(mps)
            
    if not os.path.exists(dir):
        os.makedirs(dir)
            
    with open(filepath, 'w') as outfile:
        json.dump(datas, outfile, indent=4)

    print('Parameters exported to:', filepath)
        
### Import Parameters

def read_params(kwargs):
    
    hda = kwargs['node']
    params = hda.parmsInFolder(['Parameters'])
    
    from sys import platform
    
    dir = hda.parm('path').evalAsString() + '/cache/'
    if platform == 'darwin':
        dir = hda.parm('path').evalAsString() + 'cache/'
        
    filepath = dir + '_config_' + hda.parm('preset').evalAsString() + '.json'
        
    if len(filepath) > 0 and os.path.isfile(filepath):
        # Read JSON for Standard Parameters
        with open(filepath, 'r') as outfile:
            parameters = json.load(outfile)[stdgroup]

        # Read JSON for Ramp Parameters
        with open(filepath, 'r') as outfile:
            rparameters = json.load(outfile)[rampgroup]

        # Read JSON for Multiparms
        with open(filepath, 'r') as outfile:
            mparameters = json.load(outfile)[mpgroup]

        # Set Standard Parameters
        for parm_name, value in parameters.items():
            parm = hda.parm(parm_name)
            if parm is not None:
                parm.set(value)

        # Set Ramp Parameters
        # Outer Loop Runs Over Every Ramp Parameter Name
        for parm_name, value in rparameters.items():
            parm = hda.parm(parm_name)

            if parm is not None:
                keys = []
                values = []
                bases = []
                interplookup = [hou.rampBasis.Constant, hou.rampBasis.Linear, hou.rampBasis.CatmullRom, hou.rampBasis.MonotoneCubic, hou.rampBasis.Bezier, hou.rampBasis.BSpline, hou.rampBasis.Hermite]
                # Inner Loop - We Query the Current Ramp Name With <[parm_name]>
                for i in rparameters[parm_name]:
                    keys.append(i['pos'])
                    values.append(i['value'])
                    bases.append(interplookup[i['interp']])

                # Initialize New Ramp
                ramp = hou.Ramp(bases, keys, values)
                # Set Ramp Parameters
                parm.set(ramp)

        # Set Multiparms
        # Outer Loop Runs Over Every Multiparm Name
        for parm_name, value in mparameters.items():
            parm = hda.parm(parm_name)
            parm.set(0)

            if len(mparameters) > 0:
                blocks = mparameters[parm_name]

                for i in range(len(blocks)):
                    parm.insertMultiParmInstance(i)
                
                    for name, value in blocks[i].items():
                        hda.parm(name).set(value)
                
        print('Parameters imported from:', filepath)
        
    else:
        hou.ui.displayMessage('Couldnt find the file!!')
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB