#####################################
Background Setup: A CAD Style Example
#####################################


This very simple tutorial focuses on how to use background images. A background image is set on a VRL thanks to ``RED::IViewpointRenderList::SetBackgroundImages``. The rendering sequence in a VRL (see :doc:`/book/subjects/bk_ba/bk_ba_viewpoint_render_lists` under the section **Contents of a VRL**) uses a back to front order. Before starting rendering cameras, the VRL renders the background that may be set in it (see :doc:`/book/subjects/bk_ba/bk_ba_vrl/bk_ba_adding_a_background`).

We'll see how a simple 2D image can be created and used as a background here, in a "CAD style" way.


*************************
Creating a Gradient Image
*************************

The gradient image is easy to create here:

.. code:: cpp

    RC_TEST( iresmgr->CreateImage2D( gradient, iresmgr->GetState() ) );

    RED::IImage* igradient = gradient->As< RED::IImage >();
    RED::IImage2D* igradient2D = gradient->As< RED::IImage2D >();

    RC_TEST( igradient2D->SetLocalPixels( NULL, RED::FMT_RGB, 1, gheight ) );
    unsigned char* lpix = igradient2D->GetLocalPixels();

    for( i = 0; i < gheight; i++ )
    {
        lpix[ 3 * i ]     = (unsigned char)( 255.0f * (float)i / (float)gheight + 120.0f * ( 1.0f - (float)i / (float)gheight ) );
        lpix[ 3 * i + 1 ] = (unsigned char)( 255.0f * (float)i / (float)gheight + 120.0f * ( 1.0f - (float)i / (float)gheight ) );
        lpix[ 3 * i + 2 ] = (unsigned char)( 255.0f * (float)i / (float)gheight + 220.0f * ( 1.0f - (float)i / (float)gheight ) );
    }

    RC_TEST( igradient2D->SetPixels( RED::TGT_TEX_RECT, iresmgr->GetState() ) );
    RC_TEST( igradient->SetWrapModes( RED::WM_CLAMP_TO_EDGE, RED::WM_CLAMP_TO_EDGE, iresmgr->GetState() ) );


It's a simple column of pixels, written to the wished gradient colors. The image uses A ``RED::WM_CLAMP_TO_EDGE`` wrapping mode, to ensure that our gradient colors will be used across the entire window width.

Then, our gradient is set on the VRL as its 2D background image:

.. code:: cpp

    RED::Matrix grad_matx;
    grad_matx.Scale( RED::Vector3( 1.0f, (float)gheight / (float)height, 1.0f ) );

    RC_TEST( ivrl->SetBackgroundImages( NULL, RED::Matrix::IDENTITY, gradient, grad_matx, true, 1.0, 1.0, iresmgr->GetState() ) );


Please note that the 'grad_matx' transformation matrix that adjusts the gradient height to match the window height needs to be updated on a resize event, otherwise, the exact window coverage of the gradient will not be maintained.

.. figure:: wf_BackgroundSetupACadStyleExample01.jpg
    :align: center
    
    **A torus in front of our CAD background**
