©Anton Podvalny

Table of Contents

Introduction


In this chapter we'll cover a peculiar form of lighting - the sun and sky system in V-Ray. The goal of the plugin is to represent precise physical model of the sunlight. It simulates parallel rays. One can achieve soft shadows by modifying the intensity and the dimension of the rays. The color of the simulation is adapted to the physical model of a real sun, depending on the angle on which the rays are falling on the ground.

One can also use Sphere light to simulate sunlight, as this type of light contributes to the IrradianceMap, as opposed to SunLight. Despite, we'll talk only about SunLight in this chapter.

Goal


The ideal goal of a sun-sky system will be to find a function of the form:

  • Sun
(view location, date, time, conditions) → spectral radiance
(sun direction, conditions) → spectral radiance
  • Sky
(view direction, view location, date, time, conditions) → spectral radiance
(view direction, sun direction, conditions) → spectral radiance

 

Sun


The following picture illustrates common terms around the topic of sun:

 

  • Green - altitude
  • Red - azimuth

We'll talk a little bit about sun's physical properties, because they affect its light spectrum:

  • Radius - 695000 km
  • Distance to Earth - 149140000 km
  • Total Solar Irradiance upon Earth - 1366 (1413 – 1321) W/m2
  • Solid Angle - 6x10-5 steradians

Here's a picture of the Solar Spectrum. The blue line represents the light coming to the Earth, the orange is what is left from it after passing through the atmosphere:

 

Atmospheric Phenomena


Scattering

Light may scatter several times on the way to the viewer, although primary scattering typically dominates. Scattering is related to the particle size. Without the scattering in the atmosphere the sky would be black, as on the Moon.

 

Scattering

  • Reyleigh scattering

For particles (atoms and molecules) much smaller than the wavelength of the light (< 0.1λ). Basically the scattering is proportinal to λ−4



Scattering

  • Mie scattering
  • For particles bigger than molecules, but smaller than fog (haze, haze aerosol)
  • Scattering is more uniform with the wave length and causes whitening of the sky.
  • Sources - volcanic eruptions, forest fires, cosmic bombardment, oceans.
  • Parametrization - turbidity. In the following formula tm is the turbidity from the molecules, th is from the humidity.

 

 

  • Spectral Absorbtion

Different gases in the atmosphere have different frequencies of absorption. Here we see the different elements - oxygen, ozone, vapor, carbon dioxide.

 

 

Sky models


  • Use measured sky data directly - International Daylight Measurement Program; has no spectral data
  • Full simulation - One has to work with arbitrarily complex atmospheric conditions and the simulation is very slow
  • Analytic model - Faster to calculate and controlled via small number of parameters

 

Luminance

Here's illustration of the Perez et al. Parameter model for luminance:

 

  • v - input view direction
  • Θ and Θs - the azimuth angles
  • γ - angle between the view and the sun directions With these input parameters our goal is to find the spectrum in a given point.

The model takes into account the following parameters: * Darkening or brightening of the horizont * Luminance gradient near the horizont * Relative intensity of the circumsolar region * Width of the circumsolar region * Relative backscattering light

Chromacity

There are also models for calculating the color of the sun light, which we won't cover in detail

Transmissivity

Final step of the simulation is to determine the amount of direct extraterrestrial light transmitted to the earth surface, taking into account:

  • Reyleigh scattering
  • Aerosol scattering (turbidity)
  • Ozone absorbtion
  • Mixed gases absorbtion
  • Water vapor absorbtion

Aerial perspective model

In V-Ray we also take atmospheric perspective effects into account, but we won't cover them here.

Example



# 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)

# 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)
    # Load scene from a file.
    renderer.load(os.path.join(SCENE_PATH, 'lighting.vrscene'))
    # Remove original light source from the scene.
    del renderer.plugins["VRayLightDomeShape1"]
    # Add a physical camera and allowed it to affect exposure.
    # Otherwise the Sun produces overbright values if not using a physical
    # setup and without changing its intensity.
    camera = renderer.classes.CameraPhysical.getInstanceOrCreate()
    camera.exposure = 1
    # The V-Ray Sun light together with the Sky texture plugin provides a
    # realistic outdoor illumination system that can be tuned to a specific
    # time of day and athmospheric contents (without clouds). The Sun is
    # represented as a light source at "infinity" similar to a directional
    # light, but with a real radius causing soft shadows.
    sun = renderer.classes.SunLight()
    # Specify the sun rotation.
    # The rotation matrix defines the direction vector of the light. Even
    # though it should be an omni light very far away, it's set as a directional light.
    # Note: The translation vector does NOT affect position as the Sun light
    # source is positioned at "infinity". It is only used by some 3D
    # applications to represent the Sun within the scene with an OpenGL gizmo.
    sun.transform = vray.Transform(
        vray.Matrix(
            vray.Vector(0.9563327, 0, 0.2922803),
            vray.Vector(0.2010161, 0.7259465, -0.6577188),
            vray.Vector(-0.2121799, 0.6877511, 0.6942464)),
        vray.Vector(-94.70224040070444, 306.9639183671097, 309.8629632135933))
    # Initialize the target position.
    # It is used only for caustic effects. Only the translation vector matters.
    sun.target_transform = vray.Transform(
        vray.Matrix(
            vray.Vector(1, 0, 0),
            vray.Vector(0, 1, 0),
            vray.Vector(0, 0, 1)),
        vray.Vector(0, 0, 0))
    # Specify the amount of dust in the air.
    # This property affects the color of the sun and the sky. Smaller values
    # produce a clear and blue sky and sun as you get in the country, while
    # larger values make them yellow and orange as, for example, in a big city.
    sun.turbidity = 2.5
    # Specify the reflective property of the "ground".
    # This property affects sky-dome brightness and color.
    sun.ground_albedo = vray.Color(0.5, 0.5, 0.5)
    # Specify the rotation of the sky texture based on a up vector.
    sun.up_vector = vray.Vector(0, 1, 0)
    # Specify the procedural model that will be used to generate the V-Ray Sky texture.
    # Possible values are:
    #   0 (Preethem)
    #   1 (CIE Clear)
    #   2 (CIE Overcast)
    #   3 (Hosek)
    sun.sky_model = 3
    # Specify shadow offset from the surface. Helps to prevent polygonal shadow artifacts on low-poly surfaces.
    sun.shadowBias = 0.02
    # Specify a color texture for shadows. Overrides the 'shadowColor' parameter.
    sun.shadow_color_tex = vray.AColor(0, 0, 0, 1)
    # The Sky texture emits blue (or warm around dusk and dawn) light from all
    # directions and it is used as an environment texture.
    texture = renderer.classes.TexSky()
    # The Sky texture takes its parameters from a SunLight through this connection.
    # If you don't want a Sun you can set the same parameters on this plugin.
    texture.sun = sun
    # Environment plugin with the V-Ray Sky texture used as an input.
    # It is recommended to use the 'getInstanceOrCreate' method when a settings
    # plugin is needed because there should be at most one instance of its type in the scene.
    environment = renderer.classes.SettingsEnvironment.getInstanceOrCreate()
    environment.bg_tex = texture
    environment.gi_tex = texture
    environment.reflect_tex = texture
    environment.refract_tex = texture
    # Start rendering.
    renderer.startSync()
    # Wait for rendering to end.
    renderer.waitForRenderEnd()
#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";

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);
	// Load scene from a file.
	renderer.load("lighting.vrscene");
	// Remove original light source from the scene.
	renderer.deletePlugin("VRayLightDomeShape1");
	// Add a physical camera and allowed it to affect exposure.
	// Otherwise the Sun produces overbright values if not using a physical
	// setup and without changing its intensity.
	CameraPhysical camera = renderer.getInstanceOrCreate<CameraPhysical>();
	camera.set_exposure(1);
	// The V-Ray Sun light together with the Sky texture plugin provides a
	// realistic outdoor illumination system that can be tuned to a specific
	// time of day and athmospheric contents (without clouds). The Sun is
	// represented as a light source at "infinity" similar to a directional
	// light, but with a real radius causing soft shadows.
	SunLight sun = renderer.newPlugin<SunLight>();
	// Specify the light rotation.
	// The rotation matrix defines the direction vector of the light. Even
	// though it should be an omni light very far away, it's set as a directional light.
	// Note: The translation vector does NOT affect position as the Sun light
	// source is positioned at "infinity". It is only used by some 3D
	// applications to represent the Sun within the scene with an OpenGL gizmo.
	sun.set_transform(Transform(
		Matrix(
			Vector(0.9563327, 0.0, 0.2922803),
			Vector(0.2010161, 0.7259465, -0.6577188),
			Vector(-0.2121799, 0.6877511, 0.6942464)),
		Vector(-94.70224040070444, 306.9639183671097, 309.8629632135933)));
	// Initialize the target position.
	// It is used only for caustic effects.Only the translation vector matters.
	sun.set_target_transform(Transform(
		Matrix(
			Vector(1.0, 0.0, 0.0),
			Vector(0.0, 1.0, 0.0),
			Vector(0.0, 0.0, 1.0)),
		Vector(0.0, 0.0, 0.0)));
	// Specify the amount of dust in the air.
	// This property affects the color of the sun and the sky. Smaller values
	// produce a clear and blue sky and sun as you get in the country, while
	// larger values make them yellow and orange as, for example, in a big city.
	sun.set_turbidity(2.5);
	// Specify the reflective property of the "ground".
	// This property affects sky-dome brightness and color.
	sun.set_ground_albedo(Color(0.5, 0.5, 0.5));
	// Specify the rotation of the sky texture based on a up vector.
	sun.set_up_vector(Vector(0.0, 1.0, 0.0));
	// Specify the procedural model that will be used to generate the V-Ray Sky texture.
	// Possible values are:
	//   0 (Preethem) - default
	//   1 (CIE Clear)
	//   2 (CIE Overcast)
	//   3 (Hosek)
	sun.set_sky_model(3);
	// Specify shadow offset from the surface. Helps to prevent polygonal shadow artifacts on low-poly surfaces.
	sun.set_shadowBias(0.02f);
	// Specify a color texture for shadows. Overrides the 'shadowColor' parameter.
	sun.set_shadow_color_tex(AColor(0.0, 0.0, 0.0, 1.0));
	// The Sky texture emits blue(or warm around dusk and dawn) light from all
	// directions and it is used as an environment texture.
	TexSky texture = renderer.newPlugin<TexSky>();
	// The Sky texture takes its parameters from a SunLight through this connection.
	// If you don't want a Sun you can set the same parameters on this plugin.
	texture.set_sun(sun);
	// Environment plugin with the V-Ray Sky texture used as an input.
	// It is recommended to use the 'getInstanceOrCreate' method when a settings
	// plugin is needed because there should be at most one instance of its type in the scene.
	SettingsEnvironment environment = renderer.getInstanceOrCreate<SettingsEnvironment>();
	environment.set_bg_tex(texture);
	environment.set_gi_tex(texture);
	environment.set_reflect_tex(texture);
	environment.set_refract_tex(texture);
	// Start rendering.
	renderer.startSync();
	// Wait for rendering to end.
	renderer.waitForRenderEnd();
	return 0;
}
using System;
using System.IO;
using VRay;
using VRay.Plugins;

namespace _11_sun
{
    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));
                    }
                });
                // Load scene from a file.
                renderer.Load("lighting.vrscene");
                // Remove original light source from the scene.
                renderer.DeletePlugin("VRayLightDomeShape1");
                // Add a physical camera and allowed it to affect exposure.
                // Otherwise the Sun produces overbright values if not using a physical
                // setup and without changing its intensity.
                CameraPhysical camera = renderer.GetInstanceOrCreate<CameraPhysical>();
                camera.Exposure = 1;
                // The V-Ray Sun light together with the Sky texture plugin provides a
                // realistic outdoor illumination system that can be tuned to a specific
                // time of day and athmospheric contents (without clouds). The Sun is
                // represented as a light source at "infinity" similar to a directional
                // light, but with a real radius causing soft shadows.
                SunLight sun = renderer.NewPlugin<SunLight>();
                // Specify the sun rotation.
                // The rotation matrix defines the direction vector of the light. Even
                // though it should be an omni light very far away, it's set as a directional light.
                // Note: The translation vector does NOT affect position as the Sun light
                // source is positioned at "infinity". It is only used by some 3D
                // applications to represent the Sun within the scene with an OpenGL gizmo.
                sun.Transform = new Transform(
                    new Matrix(
                        new Vector(0.9563327, 0, 0.2922803),
                        new Vector(0.2010161, 0.7259465, -0.6577188),
                        new Vector(-0.2121799, 0.6877511, 0.6942464)),
                    new Vector(-94.70224040070444, 306.9639183671097, 309.8629632135933));
                // Initialize the target position.
                // It is used only for caustic effects. Only the translation vector matters.
                sun.TargetTransform = new Transform(
                    new Matrix(
                        new Vector(1, 0, 0),
                        new Vector(0, 1, 0),
                        new Vector(0, 0, 1)),
                    new Vector(0, 0, 0));
                // Specify the amount of dust in the air.
                // This property affects the color of the sun and the sky. Smaller values
                // produce a clear and blue sky and sun as you get in the country, while
                // larger values make them yellow and orange as, for example, in a big city.
                sun.Turbidity = 2.5F;
                // Specify the reflective property of the "ground".
                // This property affects sky-dome brightness and color.
                sun.GroundAlbedo = new Color(0.5, 0.5, 0.5);
                // Specify the rotation of the sky texture based on a up vector.
                sun.UpVector = new Vector(0, 1, 0);
                // Specify the procedural model that will be used to generate the V-Ray Sky texture.
                // Possible values are:
                //   0 (Preethem)
                //   1 (CIE Clear)
                //   2 (CIE Overcast)
                //   3 (Hosek)
                sun.SkyModel = 3;
                // Specify shadow offset from the surface. Helps to prevent polygonal shadow artifacts on low-poly surfaces.
                sun.ShadowBias = 0.02F;
                // Specify a color texture for shadows. Overrides the 'shadowColor' parameter.
                sun.ShadowColorTex = new AColor(0, 0, 0, 1);
                // The Sky texture emits blue (or warm around dusk and dawn) light from all
                // directions and it is used as an environment texture.
                TexSky texture = renderer.NewPlugin<TexSky>();
                // The Sky texture takes its parameters from a SunLight through this connection.
                // If you don't want a Sun you can set the same parameters on this plugin.
                texture.Sun = sun;
                // Environment plugin with the V-Ray Sky texture used as an input.
                // It is recommended to use the 'GetInstanceOrCreate' method when a settings
                // plugin is needed because there should be at most one instance of its type in the scene.
                SettingsEnvironment environment = renderer.GetInstanceOrCreate<SettingsEnvironment>();
                environment.BgTex = texture;
                environment.GiTex = texture;
                environment.ReflectTex = texture;
                environment.RefractTex = texture;
                // Start rendering.
                renderer.StartSync();
                // Wait for rendering to end.
                renderer.WaitForRenderEnd();
            }
        }
    }
}
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);
});
// Load scene from a file asynchronously.
renderer.load("lighting.vrscene", function(err) {
    if (err) throw err;
    // Remove original light source from the scene.
    delete renderer.plugins["VRayLightDomeShape1"];
    // Add a physical camera and allowed it to affect exposure.
    // Otherwise the Sun produces overbright values if not using a physical
    // setup and without changing its intensity.
    var camera = renderer.classes.CameraPhysical.getInstanceOrCreate();
    camera.exposure = 1;
    // The V-Ray Sun light together with the Sky texture plugin provides a
    // realistic outdoor illumination system that can be tuned to a specific
    // time of day and athmospheric contents (without clouds). The Sun is
    // represented as a light source at "infinity" similar to a directional
    // light, but with a real radius causing soft shadows.
    var sun = renderer.classes.SunLight();
    // Specify the sun rotation.
    // The rotation matrix defines the direction vector of the light. Even
    // though it should be an omni light very far away, it's set as a directional light.
    // Note: The translation vector does NOT affect position as the Sun light
    // source is positioned at "infinity". It is only used by some 3D
	// applications to represent the Sun within the scene with an OpenGL gizmo.
    sun.transform = vray.Transform(
        vray.Matrix(
            vray.Vector(0.9563327, 0, 0.2922803),
            vray.Vector(0.2010161, 0.7259465, -0.6577188),
            vray.Vector(-0.2121799, 0.6877511, 0.6942464)),
        vray.Vector(-94.70224040070444, 306.9639183671097, 309.8629632135933));
    // Initialize the target position.
    // It is used only for caustic effects. Only the translation vector matters.
    sun.target_transform = vray.Transform(
        vray.Matrix(
            vray.Vector(1, 0, 0),
            vray.Vector(0, 1, 0),
            vray.Vector(0, 0, 1)),
        vray.Vector(0, 0, 0));
    // Specify the amount of dust in the air.
    // This property affects the color of the sun and the sky. Smaller values
    // produce a clear and blue sky and sun as you get in the country, while
    // larger values make them yellow and orange as, for example, in a big city.
    sun.turbidity = 2.5;
    // Specify the reflective property of the "ground".
    // This property affects sky-dome brightness and color.
    sun.ground_albedo = vray.Color(0.5, 0.5, 0.5);
    // Specify the rotation of the sky texture based on a up vector.
    sun.up_vector = vray.Vector(0, 1, 0);
    // Specify the procedural model that will be used to generate the V-Ray Sky texture.
    // Possible values are:
    //   0 (Preethem)
    //   1 (CIE Clear)
    //   2 (CIE Overcast)
    //   3 (Hosek)
    sun.sky_model = 3;
    // Specify shadow offset from the surface. Helps to prevent polygonal shadow artifacts on low-poly surfaces.
    sun.shadowBias = 0.02;
    // Specify a color texture for shadows. Overrides the 'shadowColor' parameter.
    sun.shadow_color_tex = vray.AColor(0, 0, 0, 1);
    // The Sky texture emits blue (or warm around dusk and dawn) light from all
    // directions and it is used as an environment texture.
    var texture = renderer.classes.TexSky();
    // The Sky texture takes its parameters from a SunLight through this connection.
    // If you don't want a Sun you can set the same parameters on this plugin.
    texture.sun = sun;
    // Environment plugin with the V-Ray Sky texture used as an input.
    // It is recommended to use the 'getInstanceOrCreate' method when a settings
    // plugin is needed because there should be at most one instance of its type in the scene.
    var environment = renderer.classes.SettingsEnvironment.getInstanceOrCreate();
    environment.bg_tex = texture;
    environment.gi_tex = texture;
    environment.reflect_tex = texture;
    environment.refract_tex = texture;
    // Start rendering.
    renderer.start(function(err) {
        if (err) throw err;
        // Wait for rendering to end.
        renderer.waitForRenderEnd(function() {
            renderer.close();
        });
    });
});

Result


The scene used for this render is called "Lighting_Sun.vrscene" and can be found in the scene bundle (comments to the different parameters available inside).

  • No labels