Convert Figma logo to code with AI

SlightlyMad logoVolumetricLights

Volumetric Lights for Unity

2,040
303
2,040
29

Top Related Projects

Lighting effects implemented for the Adam demo: volumetric fog, area lights and tube lights

A light shafts (volumetric shadows) effect for Unity.

1,495

A fully-dynamic voxel-based global illumination system for Unity

Quick Overview

VolumetricLights is a Unity plugin that provides high-quality volumetric lighting effects for Unity projects. It offers a performant solution for creating atmospheric lighting, god rays, and other volumetric effects, enhancing the visual quality of games and interactive applications.

Pros

  • High-quality volumetric lighting effects with minimal performance impact
  • Easy integration with existing Unity projects
  • Customizable settings for fine-tuning the appearance of volumetric lights
  • Compatible with both forward and deferred rendering pipelines

Cons

  • Requires Unity 2019.3 or later, limiting compatibility with older projects
  • May have a learning curve for users unfamiliar with volumetric lighting techniques
  • Some advanced features may require additional setup or scripting

Code Examples

// Adding a volumetric light to a scene
public class VolumetricLightExample : MonoBehaviour
{
    void Start()
    {
        // Create a new GameObject and add the VolumetricLight component
        GameObject lightObject = new GameObject("Volumetric Light");
        VolumetricLight volumetricLight = lightObject.AddComponent<VolumetricLight>();

        // Configure the volumetric light properties
        volumetricLight.intensity = 1.5f;
        volumetricLight.range = 10f;
        volumetricLight.spotAngle = 45f;
    }
}
// Adjusting volumetric light properties at runtime
public class VolumetricLightController : MonoBehaviour
{
    public VolumetricLight targetLight;

    void Update()
    {
        // Pulse the light intensity
        float pulseIntensity = Mathf.PingPong(Time.time, 1f) + 0.5f;
        targetLight.intensity = pulseIntensity;

        // Rotate the light
        targetLight.transform.Rotate(Vector3.up, 30f * Time.deltaTime);
    }
}
// Creating a volumetric fog effect
public class VolumetricFogExample : MonoBehaviour
{
    void Start()
    {
        // Add the VolumetricFog component to the camera
        Camera mainCamera = Camera.main;
        VolumetricFog volumetricFog = mainCamera.gameObject.AddComponent<VolumetricFog>();

        // Configure fog properties
        volumetricFog.density = 0.05f;
        volumetricFog.albedo = Color.white;
        volumetricFog.anisotropy = 0.5f;
    }
}

Getting Started

  1. Import the VolumetricLights package into your Unity project.
  2. Add a VolumetricLight component to a light in your scene:
    • Select a light in the Hierarchy window.
    • Click "Add Component" in the Inspector.
    • Search for and add "Volumetric Light".
  3. Adjust the VolumetricLight component settings in the Inspector to achieve the desired effect.
  4. For global fog effects, add the VolumetricFog component to your main camera.
  5. Fine-tune the volumetric lighting settings in the project's Quality Settings under the "Volumetric Lighting" section.

Competitor Comparisons

Lighting effects implemented for the Adam demo: volumetric fog, area lights and tube lights

Pros of VolumetricLighting

  • Official Unity implementation, ensuring better integration and support
  • More advanced features, including support for multiple light types
  • Optimized for performance in Unity's rendering pipeline

Cons of VolumetricLighting

  • May require more computational resources due to its comprehensive approach
  • Potentially steeper learning curve for beginners due to advanced features

Code Comparison

VolumetricLighting:

[SerializeField] private Light _light;
[SerializeField] private VolumetricLightBeam _volumetricLightBeam;

private void Start()
{
    _volumetricLightBeam.Initialize(_light);
}

VolumetricLights:

public class VolumetricLight : MonoBehaviour
{
    public Light light;
    public Material volumetricMaterial;

    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        // Custom rendering logic
    }
}

The VolumetricLighting code shows a more integrated approach with Unity's lighting system, while VolumetricLights uses a custom rendering method. VolumetricLighting's implementation suggests better performance and easier setup, but VolumetricLights offers more flexibility for custom rendering techniques.

A light shafts (volumetric shadows) effect for Unity.

Pros of LightShafts

  • More lightweight and focused specifically on light shaft rendering
  • Easier to integrate into existing projects due to its simplicity
  • Potentially better performance for simpler light shaft effects

Cons of LightShafts

  • Less versatile compared to VolumetricLights' broader range of effects
  • May require additional work to achieve more complex volumetric lighting
  • Limited customization options for advanced users

Code Comparison

LightShafts:

public class LightShafts : MonoBehaviour {
    public int radialBlurIterations = 2;
    public float sunShaftBlurRadius = 2.5f;
    public float sunShaftIntensity = 1.15f;
    public float maxRadius = 0.75f;
    public bool useDepthTexture = true;
}

VolumetricLights:

public class VolumetricLight : MonoBehaviour {
    public float Density = 1.0f;
    public float Weight = 1.0f;
    public float Decay = 0.95f;
    public float Exposure = 0.2f;
    public float Illumination = 1.0f;
}

The code snippets show that VolumetricLights offers more parameters for fine-tuning the volumetric effect, while LightShafts focuses on specific light shaft properties. VolumetricLights provides broader control over the overall volumetric lighting, whereas LightShafts emphasizes radial blur and sun shaft characteristics.

1,495

A fully-dynamic voxel-based global illumination system for Unity

Pros of SEGI

  • More advanced global illumination techniques
  • Better performance for complex scenes
  • Supports a wider range of lighting scenarios

Cons of SEGI

  • Steeper learning curve for implementation
  • May require more powerful hardware for optimal performance
  • Less frequent updates and community support

Code Comparison

SEGI:

public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    if (segi == null)
        segi = new SEGI();
    segi.RenderSEGI(source, destination);
}

VolumetricLights:

void OnRenderImage(RenderTexture src, RenderTexture dst)
{
    if (volumetricLight == null)
        volumetricLight = GetComponent<VolumetricLight>();
    volumetricLight.OnRenderImage(src, dst);
}

Both repositories provide solutions for advanced lighting in Unity, but they approach the problem differently. SEGI focuses on global illumination, offering more realistic lighting at the cost of complexity. VolumetricLights, on the other hand, specializes in volumetric lighting effects, which can be easier to implement but may not provide the same level of realism in all scenarios.

The code comparison shows that both systems integrate into Unity's rendering pipeline similarly, but SEGI's implementation suggests a more self-contained approach, while VolumetricLights relies on a component-based system.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Volumetric Lights for Unity 5

IMAGE ALT TEXT HERE IMAGE ALT TEXT HERE

Open source (BSD) extension for built-in Unity lights. It uses ray marching in light's volume to compute volumetric fog. This technique is similar to the one used in Killzone (GPU Pro 5: Volumetric Light Effects in Killzone Shadow Fall by Nathan Vos)

Corresponding thread in Unity Forum can be found here.

Demo Project

I developed this technology for my hobby project. It was never meant for real use and it is therefore little rough around the edges.

You can see the demo on Youtube. Or you can try it for yourself: Binary download

Features

  • Volumetric fog effect for multiple lights. Point, spot and directional lights are fully supported.
  • Volumetric shadows
  • Volumetric light cookies
  • Volumetric noise implemented as animated 3D texture.

Usage

  • Add VolumetricLightRenderer script to your camera and set default cookie texture for spot light.
  • Add VolumetricLight script to every light that you want to have volumetric fog.

Volumetric lights will respect standard light's parameters like color, intensity, range, shadows and cookie. There are also additional parameters specific for volumetric lights. For example:

  • Sample count - number of raymarching samples (trade quality for performance)
  • Scattering Coef - scattering coefficient controls amount of light that is reflected towards camera. Makes the effect stronger.
  • Extinction Coef - controls amount of light absorbed or out-scattered with distance. Makes the effect weaker with increasing distance. It also attenuates existing scene color when used with directional lights.
  • Skybox Extinction Coef - Only affects directional light. It controls how much skybox is affected by Extinction coefficient. This technique ignores small air particles and decreasing particle density with altitude. That often makes skybox too "foggy". Skybox extinction coefficient can help with it.
  • MieG - controls mie scattering (controls how light is reflected with respect to light's direction)
  • Height Fog - toggle exponential height fog
  • Height Fog Scale - scale height fog
  • Noise - enable volumetric noise
  • Noise Scale - noise scale
  • Noise Speed - noise animation speed

Several sample scenes are part of this project.

Building a standalone player

IMPORTANT - Standalone player will work only if all shaders are included in build! All shaders must be added into "Always Included Shaders" in ProjectSettings/Graphics.

Example scene with different parameters

  • Low/High Scattering and Extinction parameters
  • Low/High Mie G parameter
  • High/Low Shadow Strength. This technique uses single scattering model. That makes areas in shadow unnaturally dark. Use Shadow Strength to "simulate" multiple scattering.
  • Height fog with different scale
  • High/Low Skybox Extinction parameter

Rendering resolution

Volumetric fog can be rendered in smaller resolution as an optimization. Set rendering resolution in VolumetricLightRenderer script.

  • Full resolution - best quality, poor performance. Serves as a "ground truth".
  • Half resolution - best quality/performance ratio.
  • Quarter resolution - experimental. Worse quality, best performance.

Requirements

  • Unity 5 (tested on 5.3.4, 5.4 and 5.5)
  • DirectX 10/11 or OpenGL 4.1 and above
  • Tested on Windows and Mac but it should work on other platforms as well
  • VR isn't supported
  • Mobile devices aren't supported

Known Limitations

  • Currently requires HDR camera and deferred renderer
  • Currently requires DirectX 11
  • Doesn't handle transparent geometry correctly (cutout is ok)
  • 3d noise texture is hard coded. VolumetricLightRenderer has custom dds file loader that loads one specific 3d texture (Unity doesn't support 3d textures loaded from file). File "NoiseVolume.bytes" has to be in Resources folder.
  • Shadow fading is not implemented
  • Parameters and thresholds for bilateral blur and upscale are hard-coded in shaders. Different projects may need different constants. Look into BilateralBlur.shader. There are several constants at the beginning that control downsampling, blur and upsampling.

Technique overview

  • Create render target for volumetric light (volume light buffer)
  • Use CameraEvent.BeforeLighting to clear volume light buffer
  • For every volumetric light render light's volume geometry (sphere, cone, full-screen quad)
    • Use LightEvent.AfterShadowMap for shadow casting lights​
    • Use CameraEvent.BeforeLighting for non-shadow casting lights​
    • Perform raymarching in light's volume​
      • Dithering is used to offset ray origin for neighbouring pixels​
  • Use CameraEvent.AfterLighting to perform depth aware gaussian blur on volume light buffer
  • Add volume light buffer to Unity's built-in light buffer

Possible improvements

  • Light's volume geometry is unnecessarily high poly
  • Ray marching is performed in view space and every sample is then transformed to shadow space. It would be better to perform ray marching in both spaces simultaneously.
  • Add temporal filter to improve image quality and stability in motion. Change sampling pattern every frame to get more ray marching steps at no additional cost (works only with temporal filter)
  • Bilateral blur and upscale can be improved
  • I didn't try to optimize the shaders, there is likely room for improvement.

Donations

I've been asked about donation button several times now. I don't feel very comfortable about it. I don't need the money. I have a well paid job. It could also give the impression that I would use the money for further development. But that is certainly not the case.

But if you really like it and you want to brighten my day then you can always buy me a little gift. Send me Amazon or Steam gift card and I'll buy myself something shiny. You can find my email in my profile.