Using MAXScript to Work with V-Ray

Overview

The scripts listed on this page are often used by the Chaos Support team while working with users' scenes. They can be used as a reference point for automating one's daily work.

Here we answer questions such as:

  • How to automate the rendering of multiple *.vrscene files?
  • How to write scripts to automate repetitive or time-consuming tasks?

 

Automatically Render All *.vrscene Files in a Specific Directory.

Note: -imgfile="%%a.jpg" attribute overrides the output file name and format. Use this
parameter only if output is not specified in *.vrscene files.

Batch Script:
echo off 
FOR %%I in (*.vrscene) DO ( 
    FOR /F "tokens=1 delims=. " %%a in ("%%I") DO ( 
        "C:\Program Files\Chaos Group\V-Ray\Standalone for x64\bin\vray.exe" -scenefile="%%I" -autoclose=1 -imgfile="%%a.jpg" 
    ) 
)

 

Change the Mode of All VRayLightSelect Render Elements to Direct Diffuse

MAXScript:

manager = maxOps.getCurRenderElementMgr() 
numElements = manager.numrenderelements() 
for n = 0 to (numElements-1) do 
( 
    element = manager.getRenderElement n 
    if classof element == VRayLightSelect then 
    ( 
        element.mode = 2 
    ) 
)

 

Select All VRayProxy Objects Sharing the Same *.vrmesh File as the Selected Proxy

MAXScript:

if classof($) == VRayProxy then 
( 
    searchFileName = $.fileName 
) 
else 
( 
    print "Not a VRayProxy" 
    deselect $ 
) 
for each in Objects do 
( 
    if classof(each) == VRayProxy and each.fileName == searchFileName then 
    ( 
        selectmore each 
    ) 
) 
searchFileName = null

 

Turn off Unlocked Highlight Glossiness of All VRayMtl Nodes in the Scene

MAXScript:

for each in SceneMaterials where 
classof each == VRayMtl do 
( 
each.reflection_lockGlossiness = true 
)

 

Export All Objects in 3ds Max Selection Set to *.vrmesh Files

Note: Works with wildcards.

Note: Replace "OUTPUT_FOLDER" with the path where the the *.vrmesh files will be exported.
For example "C:\proxy-library\"

MAXScript:

rollout ProxyExport "Proxy Export" width:300 
(   
    label label1 "Enter Selection Set Name (wildcards * or partial-name):" 
    edittext setQuery 
    button createBtn "Create" 
    on createBtn pressed do 
    ( 
        for i = 1 to getNumNamedSelSets() do 
        ( 
            if matchPattern (getNamedSelSetName i) pattern:(setQuery.text) then select selectionSets[i] 
        ) 
            vrayMeshExport meshFile: @"OUTPUT_FOLDER" 
        ) 
) 
createDialog ProxyExport

 

Change the Specified V-Ray Object Properties of the Selected Objects.

Note: V-Ray Object Property names could be found in:
3ds Max Object Properties > User Defined Tab
Note: the property names are written only if the V-Ray Objects Properties window has
been opened at least once.

MAXScript:

for each in Selection do 
( 
    try(setUserProp each "VRay_GI_Generate" true)catch() 
    try(setUserProp each "VRay_GI_Receive" true)catch() 
)

 

Find 3ds Max Hair and Fur Effect and Adjust Motion Blur Duration and Interval Type.

Note: It is important to specify the X and Y values for the Duration and respectively, for
the Interval Type.

MAXScript:

TheEffects = (for i = 1 to numEffects where classof (getEffect i) == HairEffect collect (getEffect i)) 
theEffects[1].mbDuration = X 
theEffects[1].mbIntervalType = Y

 

Find and Disconnect All VRayDirt Maps

MAXScript:

maps = getClassInstances VRayDirt asTrackViewPick:on 
for map in maps do 
    for ref = 1 to refs.getNumRefs map.client where refs.getReference map.client ref == map.anim do 
    ( 
        refs.replaceReference map.client ref undefined 
        notifyDependents map.client 
    )

 

Reset the Self-illumination Parameters of All Assigned VRayMtl Instances to Default.

Note: This script works only with materials assigned to scene objects.

MAXScript:

for each in sceneMaterials do 
( 
    if classOf each == VRayMtl then 
    ( 
        each.selfIllumination = color 0 0 0; 
        each.selfIllumination_gi = false; 
        each.selfIllumination_multiplier = 1.0; 
        each.texmap_self_illumination = undefined; 
        each.texmap_self_illumination_on = true; 
        each.texmap_self_illumination_multiplier = 100.0; 
        each.compensate_camera_exposure = false; 
    ) 
)

 

Work with VRayOptionRE

Add VRayOptionRE, set metadata, enable render elements if disabled, set the Raw image output and initiate a render

Note: Replace the "OUTPUT_PATH\OUTPUT_FILE.exr" value to the location and filename where
you want to save the output file.

MAXScript:

re_manager = maxOps.GetCurRenderElementMgr() 
metadata = "MyMetaData=True" 
current_element = VRayOptionRE() 
current_element.elementName = "file_metadata" 
current_element.exr_metadata = metadata 
re_manager.AddRenderElement(current_element) 
if re_manager.GetElementsActive() == false then re_manager.SetElementsActive(true) 
renderers.current.output_saveRawFile = True 
renderers.current.output_rawFileName = @"OUTPUT_PATH\OUTPUT_FILE.exr" 
render vfb:False

 

Export Selected Objects and Their Materials to *.vrmesh and *.mat Files

Note: *.vrmesh and *.mat filenames are taken from object-name.

MAXScript:

function ExportProxyAndMatLib = 
( 
    filesSavePath = getSavePath() 
    for eachObject in selection do 
    ( 
        try 
        ( 
            local matLib = MaterialLibrary() 
            append matLib eachObject.material 
            saveTempMaterialLibrary matLib (filesSavePath + "\\" + eachObject.name + ".mat") 
            vraymeshexport meshfile:(filesSavePath + "\\" + eachObject.name + ".vrmesh") 
        ) 
        catch() 
    ) 
) 
ExportProxyAndMatLib()

 

Select and Delete the Currently Active Camera

MAXScript:

cam = getActiveCamera() 
select cam 
delete cam

 

Replace VRayFastSSS2 Nodes with Default VRayMtl Keeping the Outgoing Connections

MAXScript:

for each in (getclassinstances VRayFastSSS2) do 
    replaceinstances each (VrayMtl())

 

Select All Objects with Specific Value of a Specific Custom User Property

Note: Custom properties are defined from 3ds Max Objects Properties > User Defined rollout

MAXScript:

for each in objects where (getuserprop each "my_property" == 2) do 
( 
        selectmore each 
)

 

Turn Selected Object into VRayClipper in Mesh Mode with Replace Mesh on Pick Option Enabled

MAXScript:

clipMesh = $ 
clipper = VRayClipper() 
clipper.enable_mesh_mode = True 
clipper.mesh_replaceOnPick = True 
clipper.mesh_source = clipMesh 
clipper.pos = clipMesh.pos 
clipper.parent = clipMesh 
clipMesh.renderable = false 
hide clipMesh

 

Export Each Camera to Separate *.vrscene File in Specified Folder

Note: If the camera is animated (position only), the *.vrscene will be exported with
animation from the first to the last keyframe. The script also sets a separate image output 
sub-folder for each animated camera.

MAXScript:

fn ExportCamerasToVRScenes = 
( 
  savePath = getSavePath() 
  for eachCam in Cameras where classof eachCam != Targetobject do 
  ( 
    if savePath == undefined then continue 
    renderers.current.output_saveRawFile = true 
    renderers.current.output_rawFileName = savePath + "\Output\\" + eachCam.name + ".exr" 
    viewport.SetCamera eachCam 
    exportLocation = savePath + "\\" + eachCam.name 
    if eachCam.pos.isAnimated then 
    ( 
      renderers.current.output_rawFileName = savePath + "\Output\\" + eachCam.name + "_Sequence\\" + eachCam.name + ".exr" 
      animRange = getTimeRange eachCam.position.controller #allKeys #children 
      animRangeStartFrame = (integer)animRange.Start 
      animRangeEndFrame = (integer)animRange.End 
      vrayExportVRScene exportLocation startFrame:animRangeStartFrame endFrame:animRangeEndFrame 
    ) 
    else 
    ( 
      vrayExportVRScene exportLocation 
    ) 
  ) 
) 
ExportCamerasToVRScenes()

 

Clean up Leftover Animation Layers and MotionClips Controllers

The benefit of this cleanup is that the scene will save and load faster and the file size will be smaller.

MAXScript:

t=trackviewnodes 
n=t[#Anim_Layer_Control_Manager] 
deleteTrackViewController t n.controller 
gc() 
t=trackviewnodes 
n=t[#Max_MotionClip_Manager] 
deleteTrackViewController t n.controller 
gc()

 

Apply Existing Material to Selection

Note: Non-assigned materials are not listed. Only the ones assigned to geometry are.

MAXScript:

try(destroyDialog AssingExistingMat)catch() 
rollout AssingExistingMat "Assign Existing Material" 
( 
    listbox matListUI "Material List" 
      
    fn PopulateList = 
    ( 
        for each in sceneMaterials do 
        ( 
            appendString = each.name + " (" + (classof(each)as string) + ")" 
            matListUI.items = append matListUI.items appendString 
        ) 
    ) 
      
    on matListUI doubleClicked itm do 
    ( 
        try 
        ( 
            $.material = SceneMaterials[itm] 
            destroyDialog AssingExistingMat 
        )catch() 
    ) 
      
    on AssingExistingMat open do 
    ( 
        try (PopulateList())catch() 
    )   
) 
createDialog AssingExistingMat

 

Print All Property-Value Pairs of the Selected Object’s Material

MAXScript:

for p in getPropNames $.material do 
format "% = %\n" p (getProperty $.material p)

 

Toggle Selected Physical/V-Ray Camera’s Cone On or Off

MAXScript:

for p in getPropNames $.material do 
format "% = %\n" p (getProperty $.material p)

 

Custom V-Ray Raw Image Save File Dialog

MAXScript:

try(destroyDialog saveRollout)catch() 
rollout setRawFile "Save Raw file" 
( 
    edittext pathText 
    button browseButton "Browse" 
    checkbox useHalf "EXR/VRST 32-bit output" 
    checkbox useDeep "Deep EXR" 
    checkbox useDots "Dot-deliminated frame number" 
    checkbox useCorr "Save VFB color corrections to RGB channel" 
    on setRawFile open do 
    ( 
        renderers.current.output_saveRawFile=true 
        useHalf.checked = not renderers.current.output_rawExrUseHalf 
        useDeep.checked = renderers.current.output_rawExrDeep 
        useDots.checked = renderers.current.fileName_addDot 
        useCorr.checked = renderers.current.output_rawSaveColorCorrections 
        pathText.Text = renderers.current.output_rawFileName 
    ) 
    on useHalf changed current_state do renderers.current.output_rawExrUseHalf = not current_state 
    on useDeep changed current_state do renderers.current.output_rawExrDeep = current_state 
    on useDots changed current_state do renderers.current.fileName_addDot = current_state 
    on useCorr changed current_state do renderers.current.output_rawSaveColorCorrections = current_state 
    on browseButton pressed do 
    ( 
        try 
        ( 
        renderers.current.output_rawFileName = getSaveFileName types:"V-Ray image files(*.vrimg)|*.vrimg|OpenEXR image files(*.exr)|*.exr|V-Ray deep image files(*.vrst)|*.vrst|" 
        pathText.Text = renderers.current.output_rawFileName 
        )catch() 
    ) 
) 
CreateDialog setRawFile 500 150

 

Render Custom Frame Range and Output to File Only the effectsResult Channel

Note: The frame range is controlled by the startFrame and endFrame variables. The Output
location is controlled by outputImg variable.

MAXScript:

fn SaveEffectsResultOnly = 
( 
    startFrame = 0 
    endFrame = 50 
    for i = startFrame to endFrame do 
    ( 
        slidertime = i 
        max quick render 
        outputImg = @"D:\" + i as string + ".exr" 
        vfbControl #setchannel (vfbControl #getchannel effectsresult)[1] 
        vfbControl #saveimage outputImg 
    ) 
) 
try(SaveEffectsResultOnly())catch()

 

Replace Part of or the Whole Filename String of All VRayBitmap Nodes in the Scene.

Note: Enter the string you would like to replace in “STRING_TO_REPLACE” and the replacing
string should be added to “STRING_TO_REPLACE_WITH”.

MAXScript

fn ReplaceVRayHDRIFilePath = 
( 
    replaceThis = @"STRING_TO_REPLACE" 
    withThis = @"STRING_TO_REPLACE_WITH" 
    for each in (getclassinstances vrayhdri)  do 
        ( 
            each.hdrimapname = substitutestring each.hdrimapname replaceThis withThis 
        ) 
) 
try (ReplaceVRayHDRIFilePath())catch()

 

Add Path as Prefix to the Filename of the VRayBitmap Node

Note: it works if the said path doesn’t already exist in the string.

Note: enter the string in the vraymatlibpath variable.

MAXScript:

vraymatlibpath = @"D:\Test\" 
for each in (getclassinstances VRayBitmap) do 
( 
if ((findstring each.hdrimapname vraymatlibpath)==undefined) then 
each.hdrimapname = vraymatlibpath + each.hdrimapname 
)

 

Was this article helpful?
0 out of 0 found this helpful