Displaying LensFlare         The lens flare effect in 3D

Introduction

The tutorial and the code are written by User:Sphinkie.

If you implement this effect in your project, please send me a screenshot, I'll add it here.

A lens-flare effect is an optical effect that appears on the lens of a camera when a strong light is in the field of view.

Lensflare.jpg

The effect is composed with several elements: halos (like a shining circle) or "burst" (like a shining star). You need images with transparency for this (tga or png files usually).

lensflare5.jpg

lensflare6.jpg

On computers, this effect can be rendered with 2D or with 3D.

The 2D way

A plane is created in front of the camera. Halos and bursts will be drawn on this plane.

  • C : The point at the X-Y center of the screen.
  • L : The point at the X-Y position of the light source (projected on the screen).
  • Now, draw a line between C and L with a distance d. The halos are on this line, at d/2 (for instance).


The article that help me for the theory can be found on gamedev.net (Austin Game Conference).

The 3D way

A 3D line is created between a point in front of the camera and the light source. The halos and burst are drawn along this line.

  • L: The Light source Position
  • C: The Camera position
  • R: The Distance between C and L.
  • F: This point is in fromt of the camera, at the same distance thna the light. (Draw a line following the Camera direction, with a distance R).

  • Now you can draw a line between L and F with a distance d. Halos will be drawn on this line, at d/2, d/3, etc.


A good rendering will be obtain by placing the following elements:

Type  Position Scale 
 Main  d        1    
 halo  d/2      1/2    
 burst d/3      1/4    
 halo  d/5      1
 burst -d/2     1/2
 halo  -d/4     1/4
 burst -d/5     1/4

Code



The following code will use the 3D method.

This code is not perfect, because the effect is a little bit far from the camera and some 3D objects can pass between the camera and the effect. (And the effect is supposed to take place, on the camera lens itself (!).

This code is not very difficult, but need a lot of try, and adjustement to have a nice rendering.

Usage

This is the LensFlare class.

You create the lensflare with the createLensFlare function, and then call update in your frameListener, to update the effect according to the camera position, and direction.

LensFlare *lensflare;

 bool frameStarted(const FrameEvent& evt)
 {
  ..
  ..
  lensflare->update();
 }

 CreateScene(void)
 {
   ...
   ...
   lensflare = new LensFlare(Vector3(0,10,0),mCamera, mSceneMgr);
 }

This code will also need a dedicated material file.

Source files

LensFlare.h

LensFlare.cpp

lensflare.material


Alias: Displaying_LensFlare