Dof shader in Mogre        

The "depth of field" (DOF) is the distance between the nearest and farthest objects in a scene that appear acceptably sharp in an image" (Wikipedia). It is a quite impressive technique. It bases on this c++ implementation and the slightly modified version of Polygon9.

Info For questions, bug reports, etc. use this Mogre forum topic or if it's shader related Ogre forum topic.

Showcase and demo

The demo download link (external, c++ version, may not work with dx9)


click for image mode ..... and then ..... click again to switch to the next pictures
click for image mode ..... and then ..... click again to switch to the next pictures
click to enlarge
click to enlarge
click to enlarge
click to enlarge


First copy and paste the code below in two code files (you could create an empty code files in VS). There is a VB.Net and a C# version.
The "DepthOfFieldEffect.vb" or "DepthOfFieldEffect.cs" file:

Option Strict On
Imports Mogre

Public Class DepthOfFieldEffect
    Inherits RenderQueue.RenderableListener

    '   Inherits CompositorInstance.Listener, RenderTargetListener, RenderQueue.RenderableListener

    Private RenderTargetListener As RenderTargetListener
    Private Listener As CompositorInstance.Listener
    Private RenderableListenerBackup As RenderQueue.RenderableListener
    Private mWidth As UInteger
    Private mHeight As UInteger
    Private mViewPort As Viewport
    Private mCamera As Camera
    Private mDepthViewport As Viewport
    Private mDepthTarget As RenderTexture
    Private mDepthTexture As TexturePtr
    Private mDepthMaterial As MaterialPtr
    Private mDepthTechnique As Technique
    Private mCompositor As CompositorInstance
    Private mNearDepth As Single
    Private mFocalDepth As Single
    Private mFarDepth As Single
    Private mFarBlurCutoff As Single

    Private Const BLUR_DIVISOR As Integer = 4

    Public Sub New(ByVal Viewport As Viewport, ByVal Camera As Camera)
        mViewPort = Viewport
        mCamera = Camera
        mNearDepth = 10.0
        mFocalDepth = 100.0
        mFarDepth = 190.0
        mFarBlurCutoff = 1.0
        mWidth = CUInt(Viewport.ActualWidth())
        mHeight = CUInt(Viewport.ActualHeight())

        mCompositor = Nothing
        mDepthTechnique = Nothing
        mDepthTarget = Nothing
        mDepthViewport = Nothing
        mDepthTexture = Nothing
        mDepthMaterial = Nothing

    End Sub
    Public Sub Destroy()
    End Sub

    'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
    'ORIGINAL LINE: Single getNearDepth() const
    Public Function getNearDepth() As Single
        Return mNearDepth
    End Function
    'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
    'ORIGINAL LINE: Single getFocalDepth() const
    Public Function getFocalDepth() As Single
        Return mFocalDepth
    End Function
    'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
    'ORIGINAL LINE: Single getFarDepth() const
    Public Function getFarDepth() As Single
        Return mFarDepth
    End Function
    Public Sub setFocalDepths(ByVal nearDepth As Single, ByVal focalDepth As Single, ByVal farDepth As Single)
        mNearDepth = nearDepth
        mFocalDepth = focalDepth
        mFarDepth = farDepth
    End Sub
    'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
    'ORIGINAL LINE: Single getFarBlurCutoff() const
    Public Function getFarBlurCutoff() As Single
        Return mFarBlurCutoff
    End Function
    Public Sub setFarBlurCutoff(ByVal cutoff As Single)
        mFarBlurCutoff = cutoff
    End Sub
    'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
    'ORIGINAL LINE: Boolean getEnabled() const
    Public Function getEnabled() As Boolean
        Return mCompositor.Enabled()
    End Function
    Public Sub setEnabled(ByVal value As Boolean)
        mCompositor.Enabled = value
    End Sub

    ' Implementation of Ogre::CompositorInstance::Listener
    Private Sub notifyMaterialSetup(ByVal passId As UInt32, ByVal material As MaterialPtr)

        Select Case DirectCast(passId, PassId)
            Case DepthOfFieldEffect.PassId.BlurPass
                'float pixelSize[2] = {
                '	1.0f / (mViewport->getActualWidth() / BLUR_DIVISOR),
                '	1.0f / (mViewport->getActualHeight() / BLUR_DIVISOR)};

                ' Adjust fragment program parameters
                Dim ps As New Vector3(1.0F / (mWidth \ BLUR_DIVISOR), 1.0F / (mHeight \ BLUR_DIVISOR), 1.0F)
                Dim pixelSize() As Single = {ps.x, ps.y, ps.z}
                Dim fragParams As GpuProgramParametersSharedPtr = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()
                If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSize").IsNull) Then
                    fragParams.SetNamedConstant("pixelSize", ps)
                End If

                Exit Select

            Case DepthOfFieldEffect.PassId.OutputPass
                Dim pixelSizeScene() As Single = {1.0F / mWidth, 1.0F / mHeight, 0}
                Dim pixelSizeSceneV As New Vector3(pixelSizeScene(0), pixelSizeScene(1), pixelSizeScene(2))

                Dim pixelSizeBlur() As Single = {1.0F / (mWidth \ BLUR_DIVISOR), 1.0F / (mHeight \ BLUR_DIVISOR), 0}
                Dim pixelSizeBlurV As New Vector3(pixelSizeBlur(0), pixelSizeBlur(1), pixelSizeBlur(2))
                ' Adjust fragment program parameters
                Dim fragParams As GpuProgramParametersSharedPtr = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()
                If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSizeScene").IsNull) Then
                    fragParams.SetNamedConstant("pixelSizeScene", pixelSizeSceneV)
                End If
                If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSizeBlur").IsNull) Then
                    fragParams.SetNamedConstant("pixelSizeBlur", pixelSizeBlurV)
                End If

                Exit Select
        End Select
    End Sub

    ' Implementation of Ogre::RenderTargetListener
    Private Sub preViewportUpdate(ByVal evt As RenderTargetViewportEvent_NativePtr)

        Dim dofParams() As Single = {mNearDepth, mFocalDepth, mFarDepth, mFarBlurCutoff}
        Dim dofParamsM As New Vector4(dofParams(0), dofParams(1), dofParams(2), dofParams(3))
        ' Adjust fragment program parameters for depth pass
        Dim fragParams As GpuProgramParametersSharedPtr = mDepthTechnique.GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()

        If ((Not fragParams Is Nothing)) AndAlso Not (fragParams._findNamedConstantDefinition("dofParams").IsNull) Then
            fragParams.SetNamedConstant("dofParams", dofParamsM)
        End If

        ' Add 'this' as a RenderableListener to replace the technique for all renderables
        Dim queue As RenderQueue = evt.source.Camera().SceneManager().RenderQueue()

    End Sub
    Private Sub postViewportUpdate(ByVal evt As RenderTargetViewportEvent_NativePtr)
        ' Reset the RenderableListener
        Dim queue As RenderQueue = evt.source.Camera.SceneManager().RenderQueue()
    End Sub

    ' Implementation of Ogre::RenderQueue::RenderableListener
    Public Overrides Function RenderableQueued(ByVal rend As Global.Mogre.IRenderable, ByVal groupID As Byte, ByVal priority As UShort, ByRef ppTech As Global.Mogre.Technique, ByVal pQueue As Global.Mogre.RenderQueue) As Boolean
        ' Replace the technique of all renderables
        ppTech = mDepthTechnique
        Return True
    End Function

    Private Enum PassId As UInteger
        BlurPass = 666
        OutputPass = 667
    End Enum

    Private Sub createDepthRenderTexture()
        ' Create the depth render texture
        mDepthTexture = TextureManager.Singleton().CreateManual("DoF_Depth", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, TextureType.TEX_TYPE_2D, mWidth, mHeight, 0, PixelFormat.PF_L8, TextureUsage.TU_RENDERTARGET)

        ' Get its render target and add a viewport to it
        mDepthTarget = mDepthTexture.GetBuffer().GetRenderTarget()
        mDepthViewport = mDepthTarget.AddViewport(mCamera)

        ' Register 'this' as a render target listener

        AddHandler mDepthTarget.PreViewportUpdate, AddressOf preViewportUpdate
        AddHandler mDepthTarget.PostViewportUpdate, AddressOf postViewportUpdate

        ' Get the technique to use when rendering the depth render texture
        mDepthMaterial = MaterialManager.Singleton().GetByName("DoF_Depth")
        mDepthMaterial.Load() ' needs to be loaded manually
        mDepthTechnique = mDepthMaterial.GetBestTechnique()

        ' Create a custom render queue invocation sequence for the depth render texture
        Dim invocationSequence As RenderQueueInvocationSequence = Root.Singleton().CreateRenderQueueInvocationSequence("DoF_Depth")

        ' Add a render queue invocation to the sequence, and disable shadows for it
        Dim invocation As RenderQueueInvocation = invocationSequence.Add(CByte(RenderQueueGroupID.RENDER_QUEUE_MAIN), "main")
        invocation.SuppressShadows = True

        ' Set the render queue invocation sequence for the depth render texture viewport
        mDepthViewport.RenderQueueInvocationSequenceName = "DoF_Depth"

        're-set texture "DoF_Depth"
        Dim p As MaterialPtr = MaterialManager.Singleton().GetByName("DoF_DepthOfField")
    End Sub
    Private Sub destroyDepthRenderTexture()
        mDepthViewport.RenderQueueInvocationSequenceName = ""



    End Sub
    '	void createCompositor();
    '	void destroyCompositor();
    Private Sub addCompositor()
        mCompositor = CompositorManager.Singleton().AddCompositor(mViewPort, "DoF_Compositor_test")

        AddHandler mCompositor.NotifyMaterialSetup, AddressOf Me.notifyMaterialSetup

        mCompositor.Enabled = True
    End Sub
    Private Sub removeCompositor()
        mCompositor.Enabled = False
        RemoveHandler mCompositor.NotifyMaterialSetup, AddressOf Me.notifyMaterialSetup

        CompositorManager.Singleton().RemoveCompositor(mViewPort, "DoF_Compositor_test")
    End Sub
End Class

Public Class DOFManager

    Private mCamera As Camera
    Private mWindow As RenderWindow
    Private mSceneManager As SceneManager
    Private cooldown As Single = 0.25
    Public Delegate Function RequestFocalDistance() As Single
    Public Property DelegateRequestFocalDistance As RequestFocalDistance

    Public Sub New(ByVal Viewport As Viewport, ByVal Camera As Camera, ByVal RenderWindow As RenderWindow, ByVal SceneManager As SceneManager)
        mCamera = Camera
        mWindow = RenderWindow
        mSceneManager = SceneManager
        mFocusMode = FocusMode.Auto
        mAutoSpeed = 999
        mAutoTime = cooldown
        targetFocalDistance = 5

        mDepthOfFieldEffect = New DepthOfFieldEffect(Viewport, Camera)
        mLens = New Lens(Camera.FOVy, 1)
        '	mDepthOfFieldEffect->setEnabled(false);

        AddHandler Root.Singleton.FrameStarted, AddressOf frameStarted
        '	MaterialPtr material = MaterialManager::getSingleton().getByName("DoF_DepthDebug");
        '	material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("DoF_Depth");
        '	Overlay* overlay = OverlayManager::getSingleton().getByName("DoF_DepthDebugOverlay");
        '	overlay->show();
    End Sub
    Public Sub Dispose()
    End Sub

    Public Sub setEnabled(ByVal enabled As Boolean)
        '	// crashes for some reason
        '	if(enabled && !mDepthOfFieldEffect->getEnabled())
        '	{
        '		// turn on
        '		mDepthOfFieldEffect->setEnabled(true);
        '		mRoot->addFrameListener(this);
        '	} else if(!enabled && mDepthOfFieldEffect->getEnabled())
        '	{
        '		// turn off
        '		mDepthOfFieldEffect->setEnabled(false);
        '		mRoot->removeFrameListener(this);
        '	}
    End Sub
    Public Function getEnabled() As Boolean
        Return mDepthOfFieldEffect.getEnabled()
    End Function

    ' controls
    Public Sub setFocusMode(ByVal mode As FocusMode)
        mFocusMode = CType(mode, FocusMode)
    End Sub
    Public Sub setAutoSpeed(ByVal f As Single)
        mAutoSpeed = f
    End Sub
    Public Sub zoomView(ByVal delta As Single)
        Dim fieldOfView As Single = mLens.getFieldOfView().ValueRadians()
        fieldOfView += delta
        fieldOfView = CSng(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)))
        mLens.setFieldOfView(New Radian(fieldOfView))
        mCamera.FOVy = (New Radian(fieldOfView))
    End Sub
    Public Sub Aperture(ByVal delta As Single)
        If mFocusMode = FocusMode.Pinhole Then
        End If
        Dim fStop As Single = mLens.getFStop()
        fStop += delta
        fStop = CSng(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)))
    End Sub
    Public Sub moveFocus(ByVal delta As Single)
        mLens.setFocalDistance(mLens.getFocalDistance() + delta)
    End Sub
    Public Sub setZoom(ByVal f As Single)
        Dim fieldOfView As Single = New Degree(f).ValueRadians()
        fieldOfView = CSng(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)))
        mLens.setFieldOfView(New Radian(fieldOfView))
        mCamera.FOVy = New Radian(fieldOfView)
    End Sub
    Public Sub setAperture(ByVal f As Single)
        If mFocusMode = FocusMode.Pinhole Then
        End If
        Dim fStop As Single = f
        fStop = CSng(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)))
    End Sub
    Public Sub setFocus(ByVal f As Single)
    End Sub

    'C++ TO VB CONVERTER TODO TASK: The implementation of the following method could not be found:
    '	virtual Function frameStarted(ByVal evt As Ogre::FrameEvent) As Boolean

    Protected Sub cleanup()
        RemoveHandler Root.Singleton.FrameStarted, AddressOf frameStarted

        mLens = Nothing

        mDepthOfFieldEffect = Nothing
    End Sub
    Protected mDepthOfFieldEffect As DepthOfFieldEffect
    Protected mLens As Lens
    Public Enum FocusMode
    End Enum
    Protected mFocusMode As FocusMode
    Protected mAutoSpeed As Single
    Protected mAutoTime As Single
    Protected targetFocalDistance As New Single()
    Private Class Result
        Public Property Position As Vector3
        Public Property Entity As Entity
        Public Property Distance As Single
    End Class
    Private Function RaycastFromCamera(ByVal window As RenderWindow, ByVal camera As Camera, ByVal point As Vector2, ByVal SceneManager As SceneManager, ByVal queryMask As UInt32) As Result
        Dim tx As Single = (point.x / CSng(window.Width))
        Dim ty As Single = (point.y / CSng(window.Height))
        Dim ray As Ray = camera.GetCameraToViewportRay(tx, ty)

        Dim raySceneQuery As RaySceneQuery = SceneManager.CreateRayQuery(ray, queryMask)
        Dim Results = raySceneQuery.GetLastResults
        If Results Is Nothing OrElse Results.IsEmpty Then
            Return Nothing
            For i As Integer = 0 To Results.Count - 1
                Dim obj = Results.Item(i)
                If obj.movable IsNot Nothing AndAlso TypeOf obj.movable Is Entity Then
                    RaycastFromCamera = New Result With {.Distance = obj.distance, .Entity = DirectCast(obj.movable, Entity), .Position = ray.GetPoint(obj.distance)}
                    Return RaycastFromCamera
                End If
            Return Nothing
        End If
    End Function
    Public Function frameStarted(ByVal evt As FrameEvent) As Boolean
        Dim camera As Camera = mCamera
        ' Focusing
        If Me.getEnabled = False Then Return True
        Select Case mFocusMode
            Case FocusMode.Auto
                ' TODO: Replace with accurate ray/triangle collision detection
                Dim currentFocalDistance As Single = mLens.getFocalDistance()

                ' TODO: Continous AF / triggered
                mAutoTime -= evt.timeSinceLastFrame
                If mAutoTime <= 0.0F Then
                    mAutoTime = cooldown

                    targetFocalDistance = currentFocalDistance

                    '' Ryan Booker's (eyevee99) ray scene query auto focus
                    'Dim focusRay As New Ray()
                    'focusRay.Origin = (camera.DerivedPosition())
                    'focusRay.Direction = (camera.DerivedDirection())
                    'Dim v As New Vector3()
                    'Dim vn As New Vector3()
                    'Dim e As Entity
                    'Dim d As Single

                    If DelegateRequestFocalDistance IsNot Nothing Then
                        targetFocalDistance = DelegateRequestFocalDistance.Invoke
                        Dim r = RaycastFromCamera(mWindow, mCamera, New Vector2(CSng(mWindow.Width / 2), CSng(mWindow.Height / 2)), mSceneManager, 1 << 2)
                        If r IsNot Nothing Then

                            targetFocalDistance = r.Distance
                        End If
                    End If

                End If

                ' Slowly adjust the focal distance (emulate auto focus motor)
                If currentFocalDistance < targetFocalDistance Then
                    mLens.setFocalDistance(System.Math.Min(currentFocalDistance + mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance))
                ElseIf currentFocalDistance > targetFocalDistance Then
                    mLens.setFocalDistance(System.Math.Max(currentFocalDistance - mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance))
                End If

            Case FocusMode.Manual
                'we set the values elsewhere
        End Select

        ' Update Depth of Field effect
        If mFocusMode <> FocusMode.Pinhole Then

            ' Calculate and set depth of field using lens
            Dim nearDepth As Single
            Dim focalDepth As Single
            Dim farDepth As Single
            mLens.recalculateDepthOfField(nearDepth, focalDepth, farDepth)
            mDepthOfFieldEffect.setFocalDepths(nearDepth, focalDepth, farDepth)
        End If

        Return True
    End Function
End Class

The "Lens.vb" or "Lens.cs" file:

Option Strict On
Imports Mogre

Public Class Lens
  ' NOTE: All units must be the same, eg mm, cm or m etc
  ' Primary attributes
  Protected mFrameSize As New single() ' Film stock/sensor size, arbitrarily selected to help mimic the properties of film, eg 35mm, 3.5cm, 0.035m etc
  Protected mCircleOfConfusion As New single() ' The area within which the depth of field is clear, it's tied to frame size, eg 0.03mm, 0.003cm, 0.0003m etc
  Protected mFocalDistance As New single() ' The distance to the object we are focusing on
  Protected mFocalLength As New single() ' Focal length of the lens, this directly effects field of view, we can do anything from wide angle to telephoto as we don't have the limitations of physical lenses.  Focal length is the distance from the optical centre of the lens to the film stock/sensor etc
  Protected mFStop As New single() ' FStop number, ie aperture, changing the aperture of a lens has an effect of depth of field, the narrower the aperture/higher the fstop number, the greater the depth of field/clearer the picture is.

  ' Secondary attributes
  Protected mHyperfocalLength As New single() ' The hyperfocal length is the point at which far depth of field is infinite, ie if mFocalDistance is >= to this value everythig will be clear to infinity
  Protected mFieldOfView As New Radian() ' Field of view of the lens, directly related to focal length

  Public Sub Dispose()
  End Sub

  Public Function getFrameSize() As single
	  Return mFrameSize
  End Function
  Public Function getFocalDistance() As single
	  Return mFocalDistance
  End Function
  Public Function getFocalLength() As single
	  Return mFocalLength
  End Function
  Public Function getFieldOfView() As Radian
	  Return mFieldOfView
  End Function
  Public Function getFStop() As single
	  Return mFStop
  End Function
  Public Function getHyperfocalLength() As single
	  Return mHyperfocalLength
  End Function

    Public Sub recalculateDepthOfField(ByRef _nearDepth As Single, ByRef _focalDepth As Single, ByRef _farDepth As Single)
        ' Set focalDepth to the current focalDistance
        _focalDepth = mFocalDistance

        ' Recalculate the Hyperfocal length

        ' Calculate the numerator of the optics equations
        Dim numerator As Single = (mFocalDistance * (mHyperfocalLength - mFocalLength))

        Dim nearClear As Single = CSng(numerator / (mHyperfocalLength + mFocalDistance - (2.0 * mFocalLength)))

        ' Adjust the nearDepth relative to the aperture. This is an approximation.
        _nearDepth = System.Math.Min(nearClear - nearClear * mFStop, CType(0, Single))

        If mFocalDistance < mHyperfocalLength Then
            ' Calculate the far clear plane
            Dim farClear As Single = numerator / (mHyperfocalLength - mFocalDistance)

            ' Adjust the farDepth relative to the aperture. This is an approximation.
            _farDepth = farClear + farClear * mFStop

            ' Far depth of field should be infinite
            _farDepth = Math.POS_INFINITY
        End If
    End Sub

    Public Sub New(ByVal _focalLength As Single, ByVal _fStop As Single, Optional ByVal _frameSize As Single = 3.5, Optional ByVal _circleOfConfusion As Single = 0.003)
        init(_focalLength, _fStop, _frameSize, _circleOfConfusion)
    End Sub
    Public Sub New(ByVal _fieldOfView As Radian, ByVal _fStop As Single, Optional ByVal _frameSize As Single = 3.5, Optional ByVal _circleOfConfusion As Single = 0.003)
        init(_fieldOfView, _fStop, _frameSize, _circleOfConfusion)
    End Sub
    Public Sub init(ByVal _focalLength As Single, ByVal _fStop As Single, ByVal _frameSize As Single, ByVal _circleOfConfusion As Single)
        mFocalLength = _focalLength
        mFStop = _fStop
        mFrameSize = _frameSize
        mCircleOfConfusion = _circleOfConfusion
    End Sub
    Public Sub init(ByVal _fieldOfView As Radian, ByVal _fStop As Single, ByVal _frameSize As Single, ByVal _circleOfConfusion As Single)
        mFieldOfView = _fieldOfView
        mFStop = _fStop
        mFrameSize = _frameSize
        mCircleOfConfusion = _circleOfConfusion
    End Sub
    Public Sub setFrameSize(ByVal _frameSize As Single)
        mFrameSize = _frameSize
    End Sub
    Public Sub setFocalDistance(ByVal _focalDistance As Single)
        mFocalDistance = System.Math.Max(_focalDistance, 0.0F)
    End Sub
    Public Sub setFocalLength(ByVal _focalLength As Single)
        mFocalLength = System.Math.Max(_focalLength, 0.3F)
    End Sub
    Public Sub setFieldOfView(ByVal _fieldOfView As Radian)
        Dim n As New Radian(2.8)
        If n < _fieldOfView Then
            mFieldOfView = n
            mFieldOfView = _fieldOfView
        End If
    End Sub
    Public Sub setFStop(ByVal _fStop As Single)
        mFStop = System.Math.Max(_fStop, 0.0F)
    End Sub

  Private Sub recalculateHyperfocalLength()
	mHyperfocalLength = (mFocalLength * mFocalLength) / (mFStop * mCircleOfConfusion) + mFocalLength
  End Sub
  Private Sub recalculateFieldOfView()
        mFieldOfView = 2.0 * Math.ATan(CSng(mFrameSize / (2.0 * mFocalLength)))
  End Sub
  Private Sub recalculateFocalLength()
        mFocalLength = CSng((mFrameSize / System.Math.Tan(mFieldOfView.ValueRadians / 2.0)) / 2.0)
  End Sub
End Class

There are three classes:
DepthOfField - This is the class which controls the dof shader and the underlying compositor script.
Lens - This is a class which makes it easier to control the DeathOfField class (makes it more natural)
Dofmanager - This class combines both other classes to an automatic dof shader: create a new instance and set mode=automatic and everything runs out of the box

And now you have to download the material file and the other shader files.

Tip Subfolder
Copy the material file in a new folder called "dof". It improves clarity and makes it easier to find.

note Warning
Make sure that the material file is in the media folder or in one of it's subfolders and a reference is added to the "resources.cfg" file.

How to use - The simplest way

Create a dofmanager instance (and set the values you need)

Dim dof as DofManager = new DOFManager(MyViewport, MyCamera, MyRenderWindow, MySceneManager)

How to use - The other way

Create instances of Lens and DepthOfField.

Dim mDepthOfFieldEffect as DepthOfFieldEffect = new DepthOfFieldEffect(Viewport, Camera);
Dim mLens as Lens = new Lens(Camera.FOVy, 1);

But now you have to adjust the values on your own. Look into the DofManager to get an overview.

Don't forget to call "Dispose" if you stop rendering.

How does the DofManager works

The DofManager hooks into the renderloop (the FrameStarted event) and raycasts each frame from the screen center (You may need to change the query flags). The "DelegateRequestFocalDistance" is delegate which can be used to inect custom focal distances into the manager. If it's null/nothing it will be ignored.

You can stop/resume the manager with getenabled and setenabled.

Combability issues
The dofshader somehow prevents other compositors to work. (Note from Tublii: One example: this happens with the SSAA compositor)

Thanks to