©Anton Podvalny

Table of Contents

In this chapter we'll cover two effects possible because of the physical camera - Depth of Field (DoF) and Motion Blur (MB).

Depth of field


Depth of field is an effect produced by the lens and refers to the range in which the image is in focus, i.e. appears sharp. It varies due to the following factors:

  • Lens aperture (higher values of the aperture increase the range)
  • Lens size (wide-angle lens increase the range)
  • Focusing distance

It can be applied also as a post-processing effect, but what we're interested in now is the natural effect produced by CameraPhysical. The effect is most strongly seen when the camera is close to some object, like when doing a "macro" photo. For a strong DOF effect, the camera aperture must be open wide (i.e. small f-number value). That may lead to a very burnt and bright image, so to preserve the same luminosity over the whole image, the shutter speed must shortened. And at last but not at least the focus distance determines which part of the scene will be actually on focus. To get the focus near, you would need a small value and reverse - higher value for far focus.


Notice the use_dof parameter in the physicalCamera_camera_depthOfField.vrscene file from the scene bundle.

Motion blur


Motion blur is an effect produced when rapidly moving objects are captured by the camera and appeared slightly blurred. It is dependent on one factor:

  • Shutter speed (exposure) - the lower the shutter speed is, the more blurred is the image.

Motion blur, as well as DoF, can also be either added as a post-processing effect or produced naturally by the physical camera. In order to be able to see Motion blur in a render from V-Ray, we need either a moving object(s) or an animated camera. The amount of the motion blur is determined by the speed of the moving object itself as well as the Shutter speed setting of the camera. Long shutter speeds will produce more motion blur, as the movement of the object is tracked over a longer in time. In reverse, short shutter speeds will produce less motion blur effect. Keep in mind that to preserve the same luminosity over the whole image, the f-number value has to be corrected as well.


Notice the use_moblur parameter in the physicalCamera_camera_motionBlur.vrscene file from the scene bundle.

Note that in the example below the far object is moving quicker than the near one, which cases the difference in the motion blur effects.

Parameters


 If better quality (less noise) is wanted, then those effects can be achieved by raising the max subdivs parameter of the image sampler.

Depth of field

These settings are located in the SettingsCameraDof plugin.

  • on - Turns the Depth-of-Field effect on.
  • aperture - The size of the virtual camera aperture in world units. Small aperture sizes reduce the DOF effect, while larger sizes produce more blur.
  • center_bias - Determines the uniformity of the DOF effect. A value of 0.0 means that light passes uniformly through the aperture. Positive values mean that light is concentrated towards the rim of the aperture, while negative values concentrate light at the center.
  • sides_on - Allows you to simulate the polygonal shape of the aperture of real-world cameras. When this option is off, the shape is assumed to be perfectly circular.
  • sides_num - Sides of the polygon, if sides_on is true.
  • focal_dist - Determines the distance from the camera at which objects will be in perfect focus. Objects closer or further than that distance will be blurred.
  • anisotropy - Allows the stretching of the bokeh effect horizontally or vertically. Positive values stretch the effect in the vertical direction. Negative values stretch it in the horizontal direction.
  • rotation - Specifies the orientation of the aperture shape.
  • subdivs - Determines the number of samples for the DOF effect (has no effect in recent versions of V-Ray).
Depth of field is supported only for the Standard camera type. Other camera types do not produce depth of field effect at this time.

Motion blur

These settings are located in the SettingsMotionBlur plugin.

  • on - Turns Motion Blur on. For more information, see The Motion Blur example below.
  • geom_samples - Determines the number of geometry segments used to approximate motion blur. Objects are assumed to move linearly between geometry samples. For fast rotating objects, you need to increase this value to get correct motion blur. Note that more geometry samples increase memory consumption, since more geometry copies are kept in memory. You can also control the number of geometry samples on a per-object basis from the Object settings dialog. For more information, see the Geometry Samples example below.
  • low_samples - Controls how many samples in time will be computed during irradiance map calculations.
  • duration - Specifies the duration, in frames, during which the camera shutter is open. For more information, see The Duration example below.
  • subdivs - Determines the number of samples for the MB effect (has no effect in recent versions of V-Ray).
  • bias - Controls the bias of the motion blur effect. A value of 0.0 means that the light passes uniformly during the whole motion blur interval. Positive values mean that light is concentrated towards the end of the interval, while negative values concentrate light towards the beginning.
  • shutter_efficiency - In real world cameras, the shutter requires some time to open and close which in turn affects the way motion blur looks. This is especially true for lenses with large apertures. To simulate this effect, the shutter efficiency parameter controls how the motion blur samples are distributed over the time interval of the shot. A value of 1 means that the samples are evenly distributed, as if the change from open to shut (or shut to open) is instant. Lower values place more samples towards the middle of the time interval to correspond to the open or close operation taking a small time interval, as occurs in real life.
  • interval_center - Specifies the middle of the motion blur interval with respect to the 3ds Max frame. A value of 0.5 means that the middle of the motion blur interval is halfway between the frames. A value of 0.0 means that the middle of the interval is at the exact frame position. For more information, see The Interval Center example below.
  • camera_motion_blur - Enables the calculation of motion blur due to camera movement (as opposed to object movement).
  • sampling_type - Type of sampling: 0 - normal, 1 - sample only shutter open, 2 - sample only shutter middle

Examples


Example: Depth Of Field (DOF)


To enable the DoF effect you need to turn on the Depth of field option DoF & Motion blur rollout of the physical camera. The effect is most strongly seen when the camera is close to an object, for example when doing a macro photo. For a strong DoF effect, the camera aperture must be open wide (i.e. small F-Number value). That may lead to a very burnt and bright image, so to preserve the same illuminosity over the whole image, the shutter speed must be shortened. And at last but not least the Focus distance determines which part of the scene will be actually on focus. To get the focus near, you would need a small value and reverse - higher value for far focus.

For the images in this example, the following constant settings were used for some parameters: Exposure is on, F-Number is 1.0, Shutter speed is 4000.0, Film speed (ISO) is 100.0, Vignetting is off.


Depth of field is off

Depth of field is on, Focus distance is 7.30 m

Depth of field is on, Focus distance is 4.34 m



Example: Motion blur


To enable the motion blur effect, you need to enable the Motion blur option in the DoF & Motion blur rollout of the physical camera. The amount of motion blur is determined by the speed of the moving object itself as well as the Shutter speed setting of the camera. Long shutter speeds will produce more motion blur, as the movement of the object is tracked over a longer time. In reverse, short shutter speeds will produce less motion blur. Keep in mind that to preserve the same brightness over the whole image, the F-Number value has to be corrected as well.

In this example, the falling roof tiles are moving faster than the flower pot, which causes the difference in the motion blur effect.

For the images in this example, the following constant settings were used for some parameters: Exposure is on, Film speed (ISO) is 200.0, and Vignetting is on.


Motion blur is off

Motion blur is on, F-Number is 8.0, Shutter speed is 80.0

Motion blur is on, F-number is 16.0, Shutter speed is 20.0


# Compatibility with Python 2.7.
from __future__ import print_function

# The directory containing the vray shared object should be present in the PYTHONPATH environment variable.
# Try to import the vray module from VRAY_SDK/python, if it is not in PYTHONPATH
import sys, os
VRAY_SDK = os.environ.get('VRAY_SDK')
if VRAY_SDK:
    sys.path.append(os.path.join(VRAY_SDK, 'python'))
import vray

SCENE_PATH = os.path.join(os.environ.get('VRAY_SDK'), 'scenes')
# Change process working directory to SCENE_PATH in order to be able to load relative scene resources.
os.chdir(SCENE_PATH)

def onStateChanged(renderer, oldState, newState, instant):
    if newState == vray.RENDERER_STATE_IDLE_FRAME_DONE or newState == vray.RENDERER_STATE_IDLE_DONE:
        print("Image Ready, frame " + str(renderer.frame) + " (sequenceEnd = " + str(renderer.sequenceEnded) + ")")
        if newState == vray.RENDERER_STATE_IDLE_FRAME_DONE:
            # If the sequence has NOT finished - continue with next frame.
            renderer.continueSequence()

# Create an instance of VRayRenderer with default options.
# The renderer is automatically closed after the `with` block.
with vray.VRayRenderer() as renderer:
    # Register a simple log callback. Always useful for debugging.
    def dumpMsg(renderer, message, level, instant):
        if level == vray.LOGLEVEL_ERROR:
            print("[ERROR]", message)
        elif level == vray.LOGLEVEL_WARNING:
            print("[Warning]", message)
        elif level == vray.LOGLEVEL_INFO:
            print("[info]", message)
        # Uncomment for testing, but you might want to ignore these in real code
        #else: print("[debug]", message)
    renderer.setOnLogMessage(dumpMsg)

    # Add a listener for the renderer state change event.
    # We will use it to detect when a frame is completed and allow the next one to start.
    renderer.setOnStateChanged(onStateChanged)
    # Load scene from a file.
    renderer.load(os.path.join(SCENE_PATH, 'animation.vrscene'))
    # Maximum paths per pixel for interactive mode. Set a low sample level to complete rendering faster.
    # The default value is unlimited. We have to call this *after* loading the scene.
    renderer.setInteractiveSampleLevel(1)
    # Enable depth of field and apply parameters
    settingsDof = renderer.classes.SettingsCameraDof.getInstanceOrCreate()
    settingsDof.on = True
    settingsDof.aperture = 6       # f/6
    settingsDof.focal_dist = 100   # focus distance in scene units
    # The default V-Ray camera is a simple pinhole camera. To enable advanced effects like 
    # depth of field, motion blur, shaped bokeh, vignetting etc. you need to add this plugin.
    camera = renderer.classes.CameraPhysical.getInstanceOrCreate()
    # Specify the focal length of the camera lens.
    camera.focal_length = 55
    # Specify the width of the camera aperture.
    # If "exposure = True" - changing the 'f_number' will affect the image brightness.
    camera.f_number = 12
    # Specify the shutter speed, in inverse seconds, for the still photographic camera ("type = 0").
    # For example, shutter speed of 1/30 s corresponds to "shutter_speed=30".
    camera.shutter_speed = 40
    # Specify the film sensitivity.
    # If "exposure = True", changing the "ISO" will affect the image brightness.
    # Smaller values make the image darker, while larger values make it brighter.
    camera.ISO = 800
    # The distance between the camera and the current target position
    # If "specify_focus=0" this value will be used as focus distance.
    camera.target_distance = 23.72558
    # Enables motion blur effect controlled by the camera parameters.
    # This setting could also be toggled using the 'on' property of the 'SettingsMotionBlur' plugin.
    camera.use_moblur = True
    # Start rendering a sequence of frames (animation).
    renderer.renderSequence()
    # Wait until the entire sequence has finished rendering.
    renderer.waitForSequenceEnd()
#define VRAY_RUNTIME_LOAD_PRIMARY

#include "vraysdk.hpp"
#include "vrayplugins.hpp"
#include "utils.h"

using namespace VRay;
using namespace VRay::Plugins;
using namespace std;

const char *BASE_PATH = getenv("VRAY_SDK");
string SCENE_PATH = (BASE_PATH ? string(BASE_PATH) : string(".")) + PATH_DELIMITER + "scenes";

void onStateChanged(VRayRenderer &renderer, RendererState oldState, RendererState newState, double instant, void* userData) {
	if (newState == IDLE_FRAME_DONE || newState == IDLE_DONE) {
		printf("Image Ready, frame %d (sequenceEnded = %d)\n", renderer.getCurrentFrame(), renderer.isSequenceEnded());
		if (newState == IDLE_FRAME_DONE) {
			// If the sequence has NOT finished - continue with next frame.
			renderer.continueSequence();
		}
	}
}

int main() {
	// Change process working directory to SCENE_PATH in order to be able to load relative scene resources.
	changeCurrentDir(SCENE_PATH.c_str());
	// Load V-Ray SDK library.
	VRayInit init(NULL, true);
	// Create an instance of VRayRenderer with default options.
	// The renderer is automatically closed at the end of the current scope.
	VRayRenderer renderer;
	// It's recommended to always have a console log
	renderer.setOnLogMessage(logMessage);
	// Add a listener for the renderer state change event.
	// We will use it to detect when a frame is completed and allow the next one to start.
	renderer.setOnStateChanged(onStateChanged);
	// Load scene from a file.
	renderer.load("animation.vrscene");
	// Maximum paths per pixel for interactive mode. Set a low sample level to complete rendering faster.
	// The default value is unlimited. We have to call this *after* loading the scene.
	renderer.setInteractiveSampleLevel(1);
	// Enable depth of field and apply parameters
	SettingsCameraDof settingsDof = renderer.getInstanceOrCreate<SettingsCameraDof>();
	settingsDof.set_on(true);
	settingsDof.set_aperture(6);        // f/6
	settingsDof.set_focal_dist(100);    // focus distance in scene units
	// The default V-Ray camera is a simple pinhole camera. To enable advanced effects like 
	// depth of field, motion blur, shaped bokeh, vignetting etc. you need to add this plugin.
	CameraPhysical camera = renderer.getInstanceOrCreate<CameraPhysical>();
	// Specify the focal length of the camera lens.
	camera.set_focal_length(55);
	// Specify the width of the camera aperture.
	// If "exposure = true" - changing the 'f_number' will affect the image brightness.
	camera.set_f_number(12);
	// Specify the shutter speed, in inverse seconds, for the still photographic camera("type = 0").
	// For example, shutter speed of 1 / 30 s corresponds to "shutter_speed=30".
	camera.set_shutter_speed(40);
	// Specify the film sensitivity. If "exposure = True", changing the "ISO" will affect the image brightness.
	// Smaller values make the image darker, while larger values make it brighter.
	camera.set_ISO(800);
	// The distance between the camera and the current target position.
	// If "specify_focus=0" this value will be used as focus distance.
	camera.set_target_distance(23.72558f);
	// Enables motion blur effect controlled by the camera parameters.
	// This setting could also be toggled using the 'on' property of the 'SettingsMotionBlur' plugin.
	camera.set_use_moblur(true);
	// Start rendering a sequence of frames (animation).
	renderer.renderSequence();
	// Wait until the entire sequence has finished rendering.
	renderer.waitForSequenceEnd();

	return 0;
}
using System;
using System.IO;
using VRay;
using VRay.Plugins;

namespace _05_motion_blur
{
	class Program
	{
		static void Main(string[] args)
		{
			string SCENE_PATH = Path.Combine(Environment.GetEnvironmentVariable("VRAY_SDK"), "scenes");
			// Change process working directory to SCENE_PATH in order to be able to load relative scene resources.
			Directory.SetCurrentDirectory(SCENE_PATH);			
			// Create an instance of VRayRenderer with default options.
			// The renderer is automatically closed after the `using` block.
			using (VRayRenderer renderer = new VRayRenderer())
			{
				// Add a listener for any type of log message.
				renderer.LogMessage += new EventHandler<MessageEventArgs>((source, e) =>
				{
					// You can remove the if for testing, but you might want to ignore Debug in real code
					if (e.LogLevel != LogLevelType.Debug)
					{
						Console.WriteLine(String.Format("[{0}] {1}", e.LogLevel.ToString(), e.Message));
					}
				});

				// Add a listener for state changes. It is invoked when the renderer prepares for rendering, renders, finishes or fails.
				renderer.StateChanged += new EventHandler<StateChangedEventArgs>((source, e) =>
				{
					if (e.NewState == VRayRenderer.RendererState.IDLE_FRAME_DONE)
					{
						Console.WriteLine("Image Ready, frame " + renderer.Frame +
							" (sequenceEnded = " + renderer.IsSequenceEnded + ")");

						// If the sequence has NOT finished - continue with next frame.
						renderer.ContinueSequence();
					}
				});
				// Load scene from a file.
				renderer.Load("animation.vrscene");
				// Maximum paths per pixel for interactive mode. Set a low sample level to complete rendering faster.
				// The default value is unlimited. We have to call this *after* loading the scene.
				renderer.SetInteractiveSampleLevel(1);
				// Enable depth of field and apply parameters
				SettingsCameraDof settingsDof = renderer.GetInstanceOrCreate<SettingsCameraDof>();
				settingsDof.On = true;
				settingsDof.Aperture = 6;      // f/6
				settingsDof.FocalDist = 100;   // focus distance in scene units
				// The default V-Ray camera is a simple pinhole camera. To enable advanced effects like 
				// depth of field, motion blur, shaped bokeh, vignetting etc. you need to add this plugin.
				CameraPhysical camera = renderer.GetInstanceOrCreate<CameraPhysical>();
				// Specify the focal length of the camera lens.
				camera.FocalLength = 55;
				// Specify the width of the camera aperture.
				// If "Exposure = true" - changing the 'FNumber' will affect the image brightness.
				camera.FNumber = 12;
				// Specify the shutter speed, in inverse seconds, for the still photographic camera ("type = 0").
				// For example, shutter speed of 1/30 s corresponds to "shutter_speed=30".
				camera.ShutterSpeed = 40;
				// Specify the film sensitivity.
				// If "Exposure = true", changing the "ISO" will affect the image brightness.
				// Smaller values make the image darker, while larger values make it brighter.
				camera.ISO = 800;
				// The distance between the camera and the current target position
				// If "SpecifyFocus = 0" this value will be used as focus distance.
				camera.TargetDistance = 23.72558F;
				// Enables motion blur effect controlled by the camera parameters.
				// This setting could also be toggled using the 'on' property of the 'SettingsMotionBlur' plugin.
				camera.UseMoblur = true;
				// Start rendering a sequence of frames (animation).
				renderer.RenderSequence();
				// Wait until the entire sequence has finished rendering.
				renderer.WaitForSequenceEnd();
			}
		}
	}
}
var path = require('path');
var vray = require(path.join(process.env.VRAY_SDK, 'node', 'vray'));
var SCENE_PATH = path.join(process.env.VRAY_SDK, 'scenes');

// Change process working directory to SCENE_PATH in order to be able to load relative scene resources.
process.chdir(SCENE_PATH);
// Create an instance of VRayRenderer with default options.
var renderer = vray.VRayRenderer();

// It's recommended to always have a console log callback
renderer.on("logMessage", function(message, level, instant) {
	if (level == vray.LOGLEVEL_ERROR)
		console.log("[ERROR] ", message);
	else if (level == vray.LOGLEVEL_WARNING)
		console.log("[Warning] ", message);
	else if (level == vray.LOGLEVEL_INFO)
		console.log("[info] ", message);
	// Uncomment for testing, but you might want to ignore these in real code
	//else console.log("[debug] ", message);
});

// Add a listener for the renderer state change event.
// We will use it to detect when a frame is completed and allow the next one to start.
renderer.on("stateChanged", function(oldState, newState, instant) {
	if (newState == "idleFrameDone" || newState == "idleDone") {
		console.log("Image Ready, frame " + renderer.frame + " (sequenceEnd = " + renderer.sequenceEnded + ")");
		// Check if the sequence has finished rendering.
		if (newState == "idleDone") {
			renderer.close();
		} else {
			// If the sequence has NOT finished - continue with next frame.
			renderer.continueSequence();
		}
	} else if (newState.startsWith("idle")) {
		console.log("Unexpected end of render sequence: ", newState);
		renderer.close();
	}
});

// Load scene from a file asynchronously.
renderer.load("animation.vrscene", function(err) {
	if (err) throw err;
	// Maximum paths per pixel for interactive mode. Set a low sample level to complete rendering faster.
	// The default value is unlimited. We have to call this *after* loading the scene.
	renderer.setInteractiveSampleLevel(1);
	// Enable depth of field and apply parameters
	settingsDof = renderer.classes.SettingsCameraDof.getInstanceOrCreate();
	settingsDof.on = true;
	settingsDof.aperture = 6;       // f/6
	settingsDof.focal_dist = 100;   // focus distance in scene units
	// The default V-Ray camera is a simple pinhole camera. To enable advanced effects like 
	// depth of field, motion blur, shaped bokeh, vignetting etc. you need to add this plugin.
	var camera = renderer.classes.CameraPhysical.getInstanceOrCreate();
	// Specify the focal length of the camera lens.
	camera.focal_length = 55;
	// Specify the width of the camera aperture.
	// If "exposure = true" - changing the 'f_number' will affect the image brightness.
	camera.f_number = 12;
	// Specify the shutter speed, in inverse seconds, for the still photographic camera ("type = 0").
	// For example, shutter speed of 1/30 s corresponds to "shutter_speed=30".
	camera.shutter_speed = 40;
	// Specify the film sensitivity.
	// If "exposure = true", changing the "ISO" will affect the image brightness.
	// Smaller values make the image darker, while larger values make it brighter.
	camera.ISO = 800;
	// The distance between the camera and the current target position.
	// If "specify_focus=0" this value will be used as focus distance.
	camera.target_distance = 23.72558;
	// Enables motion blur effect controlled by the camera parameters.
	// This setting could also be toggled using the 'on' property of the 'SettingsMotionBlur' plugin.
	camera.use_moblur = true;
	// Start rendering a sequence of frames (animation).
	renderer.renderSequence();
});

Motion Blur with objects moving on a curved trajectory

Objects moving on a curved path, rotating or deforming objects usually require more geometry samples for correct motion blur. This is controlled with SettingsMotionBlur::geom_samples. For example, with the default value of 2, a sphere moving along a curved path will appear to be moving in a straight line when motion blurred. (In general more geometry samples lead to a slight performance hit which is why the default value is 2.)


The motion blur duration is increased to exaggerate the effect.

Geometry samples = 2

The motion blur duration is increased to exaggerate the effect.

Geometry samples = 4

Move the slider to see the example renders.


Increasing the geometry samples even slightly will produce correct motion blur. The perfect value is scene dependent and may require some experimentation.

Motion Blur with small and/or fast moving objects

Small, fast moving or small and fast moving objects may additionally require the min subdivs of the Image Sampler to be increased slightly above the default 1. This is the case with small particles or thin hair, which can require adjusting some additional settings even if motion blur is not used. V-Ray’s adaptive sampler may miss such objects with the first sample in a pixel, which will prevent it from continuing sampling the pixel. Usually, this requires raising the Image Sampler’s min subdivs to 2 or 3. (The choice of the default value is motivated by this relation: the more initial samples, the slower the rendering. In most cases the value 1 gives good results, but sometimes manual adjustments may be needed.)

Here’s an example to consider. A simple particle emitter that shoots particles in one direction. Compare the images without motion blur and with motion blur to see the effect of raising the Image Sampler’s min subdivs from 1 to 2.


Small, fast-moving particles without motion blur.

Bucket sampler, min subdivs = 1

Small, fast-moving particles with motion blur.

Bucket sampler, min subdivs = 1

Small, fast-moving particles with motion blur.

Bucket sampler, min subdivs = 2

Move the slider to see the example renders.


It’s clear that some particles are not rendered at all when motion blur is enabled. Raising the Image Sampler’s min subdivs to 2 allows V-Ray to shoot more initial samples in each pixel before any adaptivity is applied. This helps intersecting all particles.

Motion Blur Notes

These examples omit SettingsMotionBlur::low_samples on purpose. This is a parameter that controls the motion blur samples when using the Irradiance Map engine for GI and the Irradiance Map is not a recommended GI solution anymore, as it’s not compatible with features like the Adaptive Lights.

  • No labels