/* -*- mode: C; c-basic-offset: 2 -*- */
/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <epoxy/gl.h>

#include "opengl.h"

#include "visu_extension.h"
#include "visu_tools.h"
#include "visu_configFile.h"
#include "openGLFunctions/interactive.h"
#include "coreTools/toolColor.h"
#include "coreTools/toolGl.h"

/**
 * SECTION:opengl
 * @short_description: This part is responsible for the pseudo3D
 * rendering through OpenGl and gives methods to adapt the view.
 *
 * <para>There is a last parameter which controls when render is
 * done. There are two states : whenever a changing occurs (in fact
 * when the OpenGLAskForReDraw signal is received) or only the
 * OpenGLForceReDraw is received.</para>
 *
 * <para>Except when high performances are required, this module never
 * makes a redraw by itself, even when parameters such as the camera
 * position are changed. The redraw must be asked by the client by
 * emitting the OpenGLAskForReDraw signal or the OpenGLForceReDraw
 * signal. This is to avoid situations when the client makes different
 * changes but want just only one redraw at the end. All set methods
 * return a boolean which informs the client of the opportunity to
 * redraw after the set occurs. For example, if the client call a set
 * change on theta or phi but the server returns FALSE, it means that
 * not emission of OpenGLAskForReDraw is needed (for example because
 * theta or phi had already these values).</para>
 */

/******************************************************************************/

struct _VisuGlPrivate
{
  /* static int stereo; */
  VisuGlLights *currentLights;
  gboolean antialias;
  gboolean trueTransparency, stereoStatus;
  float stereoAngle;
  VisuGlRenderingMode mode;
  gfloat bgRGB[4];
  guint bgProgramId, bgVertexArray, bgId;
  guint hints;

  gboolean fogActive;
  float fogStartEnd[2];
  gboolean fogFollowsBg;
  float fogRGB[4];
};

/* A resource to control the color of the background. */
#define FLAG_RESOURCE_BG_COLOR   "backgroundColor_color"
#define DESC_RESOURCE_BG_COLOR   "Set the background of the background ; four floating point values (0. <= v <= 1.)"
static float bgRGBDefault[4] = {0., 0., 0., 1.};

#define FLAG_RESOURCE_FOG_USED   "fog_is_on"
#define DESC_RESOURCE_FOG_USED   "Control if the fog is used ; boolean (0 or 1)"
static gboolean fogActiveDefault = TRUE;

#define FLAG_RESOURCE_FOG_SPECIFIC   "fog_color_is_specific"
#define DESC_RESOURCE_FOG_SPECIFIC   "Control if the fog uses a specific color ; boolean (0 or 1)"
static gboolean fogSpecificDefault = FALSE;

#define FLAG_RESOURCE_FOG_COLOR   "fog_specific_color"
#define DESC_RESOURCE_FOG_COLOR   "Define the color of the fog ; four floating point values (0. <= v <= 1.)"
static float fogRGBDefault[4] = {0.f, 0.f, 0.f, 1.f};

#define FLAG_RESOURCE_FOG_STARTEND "fog_start_end"
#define DESC_RESOURCE_FOG_STARTEND "Define the position of the fog ; two floating point values (0. <= v <= 1.)"
static float fogStartEndDefault[2] = {0.3f, 0.7f};

#define FLAG_PARAMETER_OPENGL_ANTIALIAS "opengl_antialias"
#define DESC_PARAMETER_OPENGL_ANTIALIAS "If true, lines are drawn smoother ; boolean 0 or 1"
static gboolean antialias = TRUE;

#define FLAG_PARAMETER_OPENGL_FAKEBS "opengl_fakeBackingStore"
#define DESC_PARAMETER_OPENGL_FAKEBS "If true, V_Sim catches the Expose event from the X server and calls a redraw ; boolean 0 or 1"
#define PARAMETER_OPENGL_FAKEBS_DEFAULT 0
static int fakeBackingStore;

#define FLAG_PARAMETER_OPENGL_TRANS "opengl_trueTransparency"
#define DESC_PARAMETER_OPENGL_TRANSS "If true, the transparency rendering is enhanced ; boolean 0 or 1"
static gboolean trueTransparency = FALSE;

#define FLAG_PARAMETER_OPENGL_ANGLE "opengl_stereoAngle"
#define DESC_PARAMETER_OPENGL_ANGLE "Give the angle of the two receivers in stereo output ; float positive"
static float stereoAngle = 5.f;

#define FLAG_PARAMETER_OPENGL_STEREO "opengl_stereo"
#define DESC_PARAMETER_OPENGL_STEREO "If true, try to draw in stereo ; boolean 0 or 1"
static gboolean stereoStatus = FALSE;

#define FLAG_PARAMETER_OPENGL_RENDERING "opengl_render"
#define DESC_PARAMETER_OPENGL_RENDERING "Rules the way OpenGl draws objects in general ; 4 possible strings : VISU_GL_RENDERING_WIREFRAME, VISU_GL_RENDERING_FLAT, VISU_GL_RENDERING_SMOOTH and VISU_GL_RENDERING_SMOOTH_AND_EDGE"
#define FLAG_RESOURCE_OPENGL_RENDERING "gl_render"
#define DESC_RESOURCE_OPENGL_RENDERING "Rules the way OpenGl draws objects in general ; 4 possible strings : VISU_GL_RENDERING_WIREFRAME, VISU_GL_RENDERING_FLAT, VISU_GL_RENDERING_SMOOTH and VISU_GL_RENDERING_SMOOTH_AND_EDGE"
static guint renderingOption = VISU_GL_RENDERING_SMOOTH;

enum {
  DIRTY_SIGNAL,
  LAST_SIGNAL
};
static guint _signals[LAST_SIGNAL] = { 0 };
enum
  {
    PROP_0,
    LIGHTS_PROP,
    ANTIALIAS_PROP,
    TRANS_PROP,
    STEREO_PROP,
    ANGLE_PROP,
    MODE_PROP,
    BG_R_PROP,
    BG_G_PROP,
    BG_B_PROP,
    BG_A_PROP,
    FOG_ACTIVE_PROP,
    FOG_START_PROP,
    FOG_FULL_PROP,
    FOG_FOLLOWS_PROP,
    FOG_R_PROP,
    FOG_G_PROP,
    FOG_B_PROP,
    FOG_A_PROP,
    N_PROP
  };
static GParamSpec* _properties[N_PROP];

static VisuGl *defaultGl = NULL;

static void visu_gl_get_property(GObject* obj, guint property_id,
                                         GValue *value, GParamSpec *pspec);
static void visu_gl_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec);
static gboolean glInitContext(VisuGl *gl, GError **error);
static void glFreeContext(VisuGl *gl);

/* Local methods. */
static void onEntryAntialias(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryTrans(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryStereo(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryAngle(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryMode(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryBgColor(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogActive(VisuGl *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogSpecific(VisuGl *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogColor(VisuGl *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogStartEnd(VisuGl *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void exportParametersOpenGL(GString *data, VisuData *dataObj);
static void exportOpenGL(GString *data, VisuData *dataObj);
static void glSetAntiAlias(VisuGlPrivate *gl);
static void _openGLMessage(GLenum source, GLenum type, GLuint id, GLenum severity,
                           GLsizei length, const GLchar* message, const void* userParam);

/******************************************************************************/

G_DEFINE_TYPE_WITH_CODE(VisuGl, visu_gl, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuGl))

static void visu_gl_class_init(VisuGlClass *klass)
{
  const float rgColor[2] = {0.f, 1.f};
  const float rgAngle[2] = {-45.f,45.f};
  VisuConfigFileEntry *resourceEntry, *oldEntry;

  g_debug("Visu Gl: creating the class of the object.");
  /* g_debug("                - adding new signals ;"); */

  /* Parameters */
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                   FLAG_PARAMETER_OPENGL_ANTIALIAS,
                                   DESC_PARAMETER_OPENGL_ANTIALIAS,
                                   &antialias, FALSE);
  resourceEntry = visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                                   FLAG_PARAMETER_OPENGL_TRANS,
                                                   DESC_PARAMETER_OPENGL_TRANSS,
                                                   &trueTransparency, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  resourceEntry = visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_PARAMETER,
                                                      FLAG_PARAMETER_OPENGL_ANGLE,
                                                      DESC_PARAMETER_OPENGL_ANGLE,
                                                      1, &stereoAngle, rgAngle, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  resourceEntry = visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                                   FLAG_PARAMETER_OPENGL_STEREO,
                                                   DESC_PARAMETER_OPENGL_STEREO,
                                                   &stereoStatus, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_PARAMETER,
                                     exportParametersOpenGL);

  oldEntry = visu_config_file_addEntry(VISU_CONFIG_FILE_PARAMETER,
                                       FLAG_PARAMETER_OPENGL_RENDERING,
                                       DESC_PARAMETER_OPENGL_RENDERING,
                                       1, NULL);
  resourceEntry = visu_config_file_addEnumEntry(VISU_CONFIG_FILE_RESOURCE,
                                                FLAG_RESOURCE_OPENGL_RENDERING,
                                                DESC_RESOURCE_OPENGL_RENDERING,
                                                &renderingOption,
                                                visu_gl_rendering_getModeFromName, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  visu_config_file_entry_setReplace(resourceEntry, oldEntry);
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_BG_COLOR,
                                      DESC_RESOURCE_BG_COLOR,
                                      4, bgRGBDefault, rgColor, FALSE);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_RESOURCE,
                                   FLAG_RESOURCE_FOG_USED,
                                   DESC_RESOURCE_FOG_USED,
                                   &fogActiveDefault, FALSE);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_RESOURCE,
                                   FLAG_RESOURCE_FOG_SPECIFIC,
                                   DESC_RESOURCE_FOG_SPECIFIC,
                                   &fogSpecificDefault, FALSE);
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_FOG_COLOR,
                                      DESC_RESOURCE_FOG_COLOR,
                                      4, fogRGBDefault, rgColor, FALSE);
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_FOG_STARTEND,
                                      DESC_RESOURCE_FOG_STARTEND,
                                      2, fogStartEndDefault, rgColor, FALSE);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE,
                                     exportOpenGL);
  visu_gl_rendering_init();
  
  fakeBackingStore = PARAMETER_OPENGL_FAKEBS_DEFAULT;

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->set_property = visu_gl_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_gl_get_property;
  VISU_GL_CLASS(klass)->initContext = glInitContext;
  VISU_GL_CLASS(klass)->freeContext = glFreeContext;

  /**
   * VisuGl::lights:
   *
   * Lights environment used for this context.
   *
   * Since: 3.8
   */
  _properties[LIGHTS_PROP] = g_param_spec_boxed("lights", "Lights",
                                                "light environment",
                                                VISU_TYPE_GL_LIGHTS, G_PARAM_READABLE |
                                                G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), LIGHTS_PROP, _properties[LIGHTS_PROP]);
  /**
   * VisuGl::antialias:
   *
   * Antialias line drawing or not.
   *
   * Since: 3.8
   */
  _properties[ANTIALIAS_PROP] = g_param_spec_boolean("antialias", "Antialias",
                                                     "antialias line",
                                                     antialias, G_PARAM_READWRITE |
                                                     G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), ANTIALIAS_PROP, _properties[ANTIALIAS_PROP]);
  /**
   * VisuGl::true-transparency:
   *
   * Draw the scene twice to improve transparency rendering.
   *
   * Since: 3.8
   */
  _properties[TRANS_PROP] = g_param_spec_boolean("true-transparency", "True-Transparency",
                                                 "draw in two passes to improve transparency",
                                                 trueTransparency, G_PARAM_READWRITE |
                                                 G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), TRANS_PROP, _properties[TRANS_PROP]);
  /**
   * VisuGl::stereo:
   *
   * Draw the scene differently in the right and the left buffer to
   * simulate stereo rendering.
   *
   * Since: 3.8
   */
  _properties[STEREO_PROP] = g_param_spec_boolean("stereo", "Stereo",
                                                 "differenciate right and left buffer",
                                                 stereoStatus, G_PARAM_READWRITE |
                                                 G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), STEREO_PROP, _properties[STEREO_PROP]);
  /**
   * VisuGl::stereo-angle:
   *
   * Angle used to separate the left and right buffers (in fact half).
   *
   * Since: 3.8
   */
  _properties[ANGLE_PROP] = g_param_spec_float("stereo-angle", "Stereo-angle",
                                               "angle between left and right buffers",
                                               -45.f, 45.f, stereoAngle,
                                               G_PARAM_READWRITE |
                                               G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), ANGLE_PROP, _properties[ANGLE_PROP]);
  /**
   * VisuGl::mode:
   *
   * Global rendering mode.
   *
   * Since: 3.8
   */
  _properties[MODE_PROP] = g_param_spec_uint("mode", "Mode",
                                             "global rendering mode",
                                             0, VISU_GL_RENDERING_N_MODES - 1,
                                             VISU_GL_RENDERING_SMOOTH,
                                             G_PARAM_READWRITE |
                                             G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), MODE_PROP, _properties[MODE_PROP]);
  /**
   * VisuGl::bg-red:
   *
   * Store the red channel of the background color.
   *
   * Since: 3.8
   */
  _properties[BG_R_PROP] = g_param_spec_float("bg-red", "red channel",
                                             "background red channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_R_PROP,
				  _properties[BG_R_PROP]);
  /**
   * VisuGl::bg-green:
   *
   * Store the green channel of the background color.
   *
   * Since: 3.8
   */
  _properties[BG_G_PROP] = g_param_spec_float("bg-green", "green channel",
                                             "background green channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_G_PROP,
				  _properties[BG_G_PROP]);
  /**
   * VisuGl::bg-blue:
   *
   * Store the blue channel of the background color.
   *
   * Since: 3.8
   */
  _properties[BG_B_PROP] = g_param_spec_float("bg-blue", "blue channel",
                                             "background blue channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_B_PROP,
				  _properties[BG_B_PROP]);
  /**
   * VisuGl::bg-alpha:
   *
   * Store the alpha channel of the background color.
   *
   * Since: 3.8
   */
  _properties[BG_A_PROP] = g_param_spec_float("bg-alpha", "alpha channel",
                                             "background alpha channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_A_PROP,
				  _properties[BG_A_PROP]);

  /**
   * VisuGl::fog-active:
   *
   * Store if the fog is used.
   *
   * Since: 3.8
   */
  _properties[FOG_ACTIVE_PROP] = g_param_spec_boolean("fog-active", "Fog active",
                                                      "Fog is used",
                                                      TRUE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_ACTIVE_PROP,
				  _properties[FOG_ACTIVE_PROP]);
  /**
   * VisuGl::fog-start:
   *
   * Store the starting depth of the fog.
   *
   * Since: 3.8
   */
  _properties[FOG_START_PROP] = g_param_spec_float("fog-start", "Fog start",
                                                   "starting fog depth",
                                                   0., 1., 0.3, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_START_PROP,
				  _properties[FOG_START_PROP]);
  /**
   * VisuGl::fog-full:
   *
   * Store the depth where the fog hides all.
   *
   * Since: 3.8
   */
  _properties[FOG_FULL_PROP] = g_param_spec_float("fog-full", "Fog full",
                                                  "depth where fog hides all",
                                                  0., 1., 0.7, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_FULL_PROP,
				  _properties[FOG_FULL_PROP]);
  /**
   * VisuGl::fog-follows-bg:
   *
   * Store if the fog follows the background color.
   *
   * Since: 3.8
   */
  _properties[FOG_FOLLOWS_PROP] = g_param_spec_boolean("fog-follows-bg", "Fog follows bg",
                                                       "Fog color is the bg color",
                                                       TRUE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_FOLLOWS_PROP,
				  _properties[FOG_FOLLOWS_PROP]);
  /**
   * VisuGl::fog-red:
   *
   * Store the red channel of the specific fog color.
   *
   * Since: 3.8
   */
  _properties[FOG_R_PROP] = g_param_spec_float("fog-red", "red channel",
                                               "specific fog red channel",
                                               0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_R_PROP,
				  _properties[FOG_R_PROP]);
  /**
   * VisuGl::fog-green:
   *
   * Store the green channel of the specific fog color.
   *
   * Since: 3.8
   */
  _properties[FOG_G_PROP] = g_param_spec_float("fog-green", "green channel",
                                               "specific fog green channel",
                                               0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_G_PROP,
				  _properties[FOG_G_PROP]);
  /**
   * VisuGl::fog-blue:
   *
   * Store the blue channel of the specific fog color.
   *
   * Since: 3.8
   */
  _properties[FOG_B_PROP] = g_param_spec_float("fog-blue", "blue channel",
                                               "specific fog blue channel",
                                               0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_B_PROP,
				  _properties[FOG_B_PROP]);
  /**
   * VisuGl::fog-alpha:
   *
   * Store the alpha channel of the specific fog color.
   *
   * Since: 3.8
   */
  _properties[FOG_A_PROP] = g_param_spec_float("fog-alpha", "alpha channel",
                                               "specific fog alpha channel",
                                               0., 1., 1., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_A_PROP,
				  _properties[FOG_A_PROP]);

  /**
   * VisuGl::dirty:
   * @gl: the object which received the signal ;
   *
   * Gets emitted when the OpenGL scene is dirty and requires a redraw.
   *
   * Since: 3.9
   */
  _signals[DIRTY_SIGNAL] =
    g_signal_new("dirty", G_TYPE_FROM_CLASS(klass),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 0, NULL, NULL, g_cclosure_marshal_VOID__VOID,
                 G_TYPE_NONE, 0, NULL);
}

static void visu_gl_init(VisuGl *self)
{
  g_debug("Visu Gl: initializing a new object (%p).",
	      (gpointer)self);
  self->priv = visu_gl_get_instance_private(self);

  self->priv->currentLights = (VisuGlLights*)0;
  self->priv->antialias     = antialias;
  self->priv->trueTransparency = trueTransparency;
  self->priv->stereoStatus  = stereoStatus;
  self->priv->stereoAngle   = stereoAngle;
  self->priv->mode          = renderingOption;
  self->priv->hints         = 0;
  self->priv->bgRGB[0] = bgRGBDefault[0];
  self->priv->bgRGB[1] = bgRGBDefault[1];
  self->priv->bgRGB[2] = bgRGBDefault[2];
  self->priv->bgRGB[3] = bgRGBDefault[3];
  self->priv->bgProgramId   = 0;
  self->priv->bgVertexArray = 0;
  self->priv->fogActive      = fogActiveDefault;
  self->priv->fogStartEnd[0] = fogStartEndDefault[0];
  self->priv->fogStartEnd[1] = fogStartEndDefault[1];
  self->priv->fogFollowsBg   = !fogSpecificDefault;
  self->priv->fogRGB[0]      = fogRGBDefault[0];
  self->priv->fogRGB[1]      = fogRGBDefault[1];
  self->priv->fogRGB[2]      = fogRGBDefault[2];
  self->priv->fogRGB[3]      = fogRGBDefault[3];

  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_ANTIALIAS,
                          G_CALLBACK(onEntryAntialias), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_TRANS,
                          G_CALLBACK(onEntryTrans), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_STEREO,
                          G_CALLBACK(onEntryStereo), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_ANGLE,
                          G_CALLBACK(onEntryAngle), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_RENDERING,
                          G_CALLBACK(onEntryMode), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_BG_COLOR,
                          G_CALLBACK(onEntryBgColor), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_USED,
                          G_CALLBACK(onEntryFogActive), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_SPECIFIC,
                          G_CALLBACK(onEntryFogSpecific), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_COLOR,
                          G_CALLBACK(onEntryFogColor), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_STARTEND,
                          G_CALLBACK(onEntryFogStartEnd), (gpointer)self, G_CONNECT_SWAPPED);

  if (!defaultGl)
    defaultGl = self;
}

static void visu_gl_get_property(GObject* obj, guint property_id,
                                 GValue *value, GParamSpec *pspec)
{
  VisuGl *self = VISU_GL(obj);

  g_debug("Visu Gl: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case LIGHTS_PROP:
      g_debug("%p.", (gpointer)self->priv->currentLights);
      g_value_set_boxed(value, self->priv->currentLights);
      break;
    case ANTIALIAS_PROP:
      g_debug("%d.", self->priv->antialias);
      g_value_set_boolean(value, self->priv->antialias);
      break;
    case TRANS_PROP:
      g_debug("%d.", self->priv->trueTransparency);
      g_value_set_boolean(value, self->priv->trueTransparency);
      break;
    case STEREO_PROP:
      g_debug("%d.", self->priv->stereoStatus);
      g_value_set_boolean(value, self->priv->stereoStatus);
      break;
    case ANGLE_PROP:
      g_debug("%g.", self->priv->stereoAngle);
      g_value_set_float(value, self->priv->stereoAngle);
      break;
    case MODE_PROP:
      g_debug("%d.", self->priv->mode);
      g_value_set_uint(value, self->priv->mode);
      break;
    case BG_R_PROP:
      g_debug("%g.", self->priv->bgRGB[0]);
      g_value_set_float(value, self->priv->bgRGB[0]);
      break;
    case BG_G_PROP:
      g_debug("%g.", self->priv->bgRGB[1]);
      g_value_set_float(value, self->priv->bgRGB[1]);
      break;
    case BG_B_PROP:
      g_debug("%g.", self->priv->bgRGB[2]);
      g_value_set_float(value, self->priv->bgRGB[2]);
      break;
    case BG_A_PROP:
      g_debug("%g.", self->priv->bgRGB[3]);
      g_value_set_float(value, self->priv->bgRGB[3]);
      break;
    case FOG_ACTIVE_PROP:
      g_value_set_boolean(value, self->priv->fogActive);
      g_debug("%d.", self->priv->fogActive);
      break;
    case FOG_START_PROP:
      g_value_set_float(value, self->priv->fogStartEnd[0]);
      g_debug("%g.", self->priv->fogStartEnd[0]);
      break;
    case FOG_FULL_PROP:
      g_value_set_float(value, self->priv->fogStartEnd[1]);
      g_debug("%g.", self->priv->fogStartEnd[1]);
      break;
    case FOG_FOLLOWS_PROP:
      g_value_set_boolean(value, self->priv->fogFollowsBg);
      g_debug("%d.", self->priv->fogFollowsBg);
      break;
    case FOG_R_PROP:
      g_value_set_float(value, self->priv->fogRGB[0]);
      g_debug("%g.", self->priv->fogRGB[0]);
      break;
    case FOG_G_PROP:
      g_value_set_float(value, self->priv->fogRGB[1]);
      g_debug("%g.", self->priv->fogRGB[1]);
      break;
    case FOG_B_PROP:
      g_value_set_float(value, self->priv->fogRGB[2]);
      g_debug("%g.", self->priv->fogRGB[2]);
      break;
    case FOG_A_PROP:
      g_value_set_float(value, self->priv->fogRGB[3]);
      g_debug("%g.", self->priv->fogRGB[3]);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_gl_set_property(GObject* obj, guint property_id,
                                 const GValue *value, GParamSpec *pspec)
{
  VisuGl *self = VISU_GL(obj);
  float rgba[4], startEnd[2];

  g_debug("Visu Gl: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ANTIALIAS_PROP:
      g_debug("%d.", g_value_get_boolean(value));
      visu_gl_setAntialias(self, g_value_get_boolean(value));
      break;
    case TRANS_PROP:
      g_debug("%d.", g_value_get_boolean(value));
      visu_gl_setTrueTransparency(self, g_value_get_boolean(value));
      break;
    case STEREO_PROP:
      g_debug("%d.", g_value_get_boolean(value));
      visu_gl_setStereo(self, g_value_get_boolean(value));
      break;
    case ANGLE_PROP:
      g_debug("%g.", g_value_get_float(value));
      visu_gl_setStereoAngle(self, g_value_get_float(value));
      break;
    case MODE_PROP:
      g_debug("%d.", g_value_get_uint(value));
      visu_gl_setMode(self, g_value_get_uint(value));
      break;
    case BG_R_PROP:
      rgba[0] = g_value_get_float(value);
      g_debug("%g.", rgba[0]);
      visu_gl_setBgColor(self, rgba, TOOL_COLOR_MASK_R);
      break;
    case BG_G_PROP:
      rgba[1] = g_value_get_float(value);
      g_debug("%g.", rgba[1]);
      visu_gl_setBgColor(self, rgba, TOOL_COLOR_MASK_G);
      break;
    case BG_B_PROP:
      rgba[2] = g_value_get_float(value);
      g_debug("%g.", rgba[2]);
      visu_gl_setBgColor(self, rgba, TOOL_COLOR_MASK_B);
      break;
    case BG_A_PROP:
      rgba[3] = g_value_get_float(value);
      g_debug("%g.", rgba[3]);
      visu_gl_setBgColor(self, rgba, TOOL_COLOR_MASK_A);
      break;
    case FOG_ACTIVE_PROP:
      visu_gl_setFogActive(self, g_value_get_boolean(value));
      g_debug("%d.", self->priv->fogActive);
      break;
    case FOG_START_PROP:
      startEnd[0] = g_value_get_float(value);
      visu_gl_setFogStartFull(self, startEnd, VISU_GL_FOG_MASK_START);
      g_debug("%g.", self->priv->fogStartEnd[0]);
      break;
    case FOG_FULL_PROP:
      startEnd[1] = g_value_get_float(value);
      visu_gl_setFogStartFull(self, startEnd, VISU_GL_FOG_MASK_FULL);
      g_debug("%g.", self->priv->fogStartEnd[1]);
      break;
    case FOG_FOLLOWS_PROP:
      visu_gl_setFogFollowsBg(self, g_value_get_boolean(value));
      g_debug("%d.", self->priv->fogFollowsBg);
      break;
    case FOG_R_PROP:
      rgba[0] = g_value_get_float(value);
      visu_gl_setFogColor(self, rgba, TOOL_COLOR_MASK_R);
      g_debug("%g.", self->priv->fogRGB[0]);
      break;
    case FOG_G_PROP:
      rgba[1] = g_value_get_float(value);
      visu_gl_setFogColor(self, rgba, TOOL_COLOR_MASK_G);
      g_debug("%g.", self->priv->fogRGB[1]);
      break;
    case FOG_B_PROP:
      rgba[2] = g_value_get_float(value);
      visu_gl_setFogColor(self, rgba, TOOL_COLOR_MASK_B);
      g_debug("%g.", self->priv->fogRGB[2]);
      break;
    case FOG_A_PROP:
      rgba[3] = g_value_get_float(value);
      visu_gl_setFogColor(self, rgba, TOOL_COLOR_MASK_A);
      g_debug("%g.", self->priv->fogRGB[3]);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

/**
 * visu_gl_getLights:
 * @gl: a #VisuGl object.
 *
 * V_Sim proposes a wrapper around the OpenGL light definitions.
 *
 * Returns: the set of current lights.
 */
VisuGlLights* visu_gl_getLights(VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), (VisuGlLights*)0);

  g_debug("OpenGL: getting lights %p", (gpointer)gl->priv->currentLights);
  if (!gl->priv->currentLights)
    {
      /* Deals with lights. */
      gl->priv->currentLights = visu_gl_lights_new();
      visu_gl_lights_add(gl->priv->currentLights, visu_gl_light_newDefault());
    }

  return gl->priv->currentLights;
}

/**
 * visu_gl_applyLights:
 * @gl: a #VisuGl object.
 *
 * If @gl has some defined lights, it setup the OpenGL context with
 * them and notify the "lights" parameter.
 *
 * Since: 3.8
 **/
void visu_gl_applyLights(VisuGl *gl)
{
  g_return_if_fail(VISU_IS_GL(gl));

  if (gl->priv->currentLights)
    g_object_notify_by_pspec(G_OBJECT(gl), _properties[LIGHTS_PROP]);
}

/******************************************************************************/

static gboolean _initChess(VisuGl *gl, GError **error)
{
  guint buffer, id;
  gfloat coords[4][2];
  const char *vertexSource =
    "#version 130\n"
    "in vec2 position;\n"
    "\n"
    "void main() {\n"
    "  gl_Position = vec4(position, 0., 1.0);\n"
    "}";
  const char *fragmentSource =
    "#version 130\n"
    "\n"
    "out vec4 outputColor;\n"
    "uniform vec4 bgColor;\n"
    "\n"
    "void main() {\n"
    "  int intensityX = int(mod(gl_FragCoord.x - 0.5, 32) / 16);\n"
    "  int intensityY = int(mod(gl_FragCoord.y - 0.5, 32) / 16);\n"
    "  float intensity = 0.5 + 0.25 * mod(intensityX + intensityY, 2);\n"
    "  outputColor = vec4(bgColor.x * bgColor.w + (1. - bgColor.w) * intensity, bgColor.y * bgColor.w + (1. - bgColor.w) * intensity, bgColor.z * bgColor.w + (1. - bgColor.w) * intensity, 1.);\n"
    "}";

  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (!tool_gl_createShader(&gl->priv->bgProgramId, vertexSource, fragmentSource, error))
    return FALSE;

  glGenVertexArrays(1, &gl->priv->bgVertexArray);
  glGenBuffers(1, &buffer);

  coords[0][0] = -1.f;
  coords[0][1] = -1.f;
  coords[1][0] = +1.f;
  coords[1][1] = -1.f;
  coords[2][0] = +1.f;
  coords[2][1] = +1.f;
  coords[3][0] = -1.f;
  coords[3][1] = +1.f;
  glBindVertexArray(gl->priv->bgVertexArray);
  glBindBuffer(GL_ARRAY_BUFFER, buffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(coords), coords, GL_STATIC_DRAW);
  id = glGetAttribLocation(gl->priv->bgProgramId, "position");
  gl->priv->bgId = glGetUniformLocation(gl->priv->bgProgramId, "bgColor");
  glEnableVertexAttribArray(id);
  glVertexAttribPointer(id, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), 0);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);

  return TRUE;
}

static gboolean glInitContext(VisuGl *gl, GError **error)
{
  static gboolean done = FALSE;
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (!done) {
    glEnable(GL_DEBUG_OUTPUT);
    glDebugMessageCallback(_openGLMessage, 0);
    done = TRUE;
  }

  /* Set the openGL flags. */
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glDepthRange(0.0, 1.0);
  glClearDepth(1.0);

  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  visu_gl_rendering_applyMode(gl->priv->mode);

  glSetAntiAlias(gl->priv);

  if (!_initChess(gl, error))
    return FALSE;

  return TRUE;
}

static void glFreeContext(VisuGl *gl)
{
  g_return_if_fail(VISU_IS_GL(gl));

  if (gl->priv->bgProgramId)
    glDeleteProgram(gl->priv->bgProgramId);
  gl->priv->bgProgramId = 0;
  glDeleteVertexArrays(1, &gl->priv->bgVertexArray);
}

/**
 * visu_gl_setBgColor:
 * @gl: a #VisuGl object.
 * @rgba: (in) (array fixed-size=4): a three floats array with values
 * (0 <= values <= 1) for the red, the green and the blue color. Only
 * values specified by the mask are really relevant.
 * @mask: use #TOOL_COLOR_MASK_R, #TOOL_COLOR_MASK_G,
 * #TOOL_COLOR_MASK_B, #TOOL_COLOR_MASK_RGBA or a combinaison to
 * indicate what values in the rgb array must be taken into account.
 *
 * Method used to change the value of the parameter background_color.
 *
 * Since: 3.8
 *
 * Returns: TRUE if changed.
 */
gboolean visu_gl_setBgColor(VisuGl *gl, const float rgba[4], int mask)
{
  gboolean changed = FALSE;

  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  g_object_freeze_notify(G_OBJECT(gl));
  if (mask & TOOL_COLOR_MASK_R && gl->priv->bgRGB[0] != rgba[0])
    {
      gl->priv->bgRGB[0] = CLAMP(rgba[0], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(gl), _properties[BG_R_PROP]);
      changed = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_G && gl->priv->bgRGB[1] != rgba[1])
    {
      gl->priv->bgRGB[1] = CLAMP(rgba[1], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(gl), _properties[BG_G_PROP]);
      changed = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_B && gl->priv->bgRGB[2] != rgba[2])
    {
      gl->priv->bgRGB[2] = CLAMP(rgba[2], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(gl), _properties[BG_B_PROP]);
      changed = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_A && gl->priv->bgRGB[3] != rgba[3])
    {
      gl->priv->bgRGB[3] = CLAMP(rgba[3], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(gl), _properties[BG_A_PROP]);
      changed = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(gl));
  if (changed)
    g_signal_emit(gl, _signals[DIRTY_SIGNAL], 0, NULL);
  return changed;
}

/**
 * visu_gl_getBgColor:
 * @gl: a #VisuGl object.
 * @rgba: (array fixed-size=4) (out): a storage for four values.
 *
 * Read the RGBA value of the specific background colour (in [0;1]).
 *
 * Since: 3.8
 */
void visu_gl_getBgColor(const VisuGl *gl, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL(gl));

  memcpy(rgba, gl->priv->bgRGB, sizeof(float) * 4);
}

/**
 * visu_gl_setFogColor:
 * @set: a #VisuGl object.
 * @rgba: (array fixed-size=4): four [0;1] float values.
 * @mask: a mask, see %TOOL_COLOR_MASK_R for instance.
 *
 * Change the fog specific colour. Activate it with
 * visu_gl_setFogFollowsBg().
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_setFogColor(VisuGl *set, const float rgba[4], int mask)
{
  gboolean diff;

  g_return_val_if_fail(VISU_IS_GL(set), FALSE);

  diff = FALSE;
  g_object_freeze_notify(G_OBJECT(set));
  if (mask & TOOL_COLOR_MASK_R && set->priv->fogRGB[0] != rgba[0])
    {
      set->priv->fogRGB[0] = CLAMP(rgba[0], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_R_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_G && set->priv->fogRGB[1] != rgba[1])
    {
      set->priv->fogRGB[1] = CLAMP(rgba[1], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_G_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_B && set->priv->fogRGB[2] != rgba[2])
    {
      set->priv->fogRGB[2] = CLAMP(rgba[2], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_B_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_A && set->priv->fogRGB[3] != rgba[3])
    {
      set->priv->fogRGB[3] = CLAMP(rgba[3], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_A_PROP]);
      diff = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(set));
  if (diff && set->priv->fogActive)
    g_signal_emit(set, _signals[DIRTY_SIGNAL], 0, NULL);
  return diff;
}
/**
 * visu_gl_setFogActive:
 * @set: a #VisuGl object.
 * @value: a boolean.
 *
 * Activates the fog rendering, or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_setFogActive(VisuGl *set, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL(set), FALSE);

  if (set->priv->fogActive == value)
    return FALSE;

  set->priv->fogActive = value;
  g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_ACTIVE_PROP]);
  g_signal_emit(set, _signals[DIRTY_SIGNAL], 0, NULL);
  return TRUE;
}
/**
 * visu_gl_setFogFollowsBg:
 * @set: a #VisuGl object.
 * @value: a boolean.
 *
 * Specifies if the fog is coloured with the background colour or with
 * its own colour, see visu_gl_setFogColor().
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_setFogFollowsBg(VisuGl *set, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL(set), FALSE);

  if (set->priv->fogFollowsBg == value)
    return FALSE;

  set->priv->fogFollowsBg = value;
  g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_FOLLOWS_PROP]);
  if (set->priv->fogActive)
    g_signal_emit(set, _signals[DIRTY_SIGNAL], 0, NULL);
  return TRUE;
}
/**
 * visu_gl_setFogStartFull:
 * @set: a #VisuGl object.
 * @startEnd: (array fixed-size=2): two [0;1] floating point values.
 * @mask: a mask, see %VISU_GL_FOG_MASK_START and
 * %VISU_GL_FOG_MASK_FULL.
 *
 * Change the starting and ending point of fog.
 *
 * Since: 3.8
 *
 * Returns: TRUE if values are actually changed.
 **/
gboolean visu_gl_setFogStartFull(VisuGl *set, const float startEnd[2], int mask)
{
  gboolean diff;

  g_return_val_if_fail(VISU_IS_GL(set), FALSE);

  diff = FALSE;
  g_object_freeze_notify(G_OBJECT(set));
  if (mask & VISU_GL_FOG_MASK_START && set->priv->fogStartEnd[0] != startEnd[0])
    {
      set->priv->fogStartEnd[0] = CLAMP(startEnd[0], 0.f, 1.f);
      if (mask & VISU_GL_FOG_MASK_FULL)
	{
	  if (set->priv->fogStartEnd[0] >= startEnd[1])
	    set->priv->fogStartEnd[0] = startEnd[1] - 0.001;
	}
      else
	if (set->priv->fogStartEnd[0] >= set->priv->fogStartEnd[1])
	  set->priv->fogStartEnd[0] = set->priv->fogStartEnd[1] - 0.001;
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_START_PROP]);
      diff = TRUE;
    }
  if (mask & VISU_GL_FOG_MASK_FULL && set->priv->fogStartEnd[1] != startEnd[1])
    {
      set->priv->fogStartEnd[1] = CLAMP(startEnd[1], 0.f, 1.f);
      if (set->priv->fogStartEnd[1] <= set->priv->fogStartEnd[0])
	set->priv->fogStartEnd[1] = set->priv->fogStartEnd[0] + 0.001;
      g_object_notify_by_pspec(G_OBJECT(set), _properties[FOG_FULL_PROP]);
      diff = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(set));
  if (diff && set->priv->fogActive)
    g_signal_emit(set, _signals[DIRTY_SIGNAL], 0, NULL);
  return diff;
}

/**
 * visu_gl_getFogColor:
 * @set: a #VisuGl object.
 * @rgba: (out) (array fixed-size=4): a storage for three values.
 *
 * Gives the actual fog color, for the specific color, use
 * visu_gl_getFogSpecificColor().
 *
 * Since: 3.8
 */
void visu_gl_getFogColor(const VisuGl *set, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL(set));
  if (set->priv->fogFollowsBg)
    visu_gl_getBgColor(VISU_GL(set), rgba);
  else
    {
      memcpy(rgba, set->priv->fogRGB, sizeof(float) * 3);
      rgba[3] = set->priv->bgRGB[3];
    }
}
/**
 * visu_gl_getFogSpecificColor:
 * @set: a #VisuGl object.
 * @rgba: (out) (array fixed-size=4): a storage for three values.
 *
 * Gives the specific fog color, for the actual color, use
 * visu_gl_getFogColor().
 *
 * Since: 3.8
 */
void visu_gl_getFogSpecificColor(const VisuGl *set, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL(set));
  memcpy(rgba, set->priv->fogRGB, sizeof(float) * 4);
}
/**
 * visu_gl_getFogActive:
 * @set: a #VisuGl object.
 *
 * Read if fog is used or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the fog is rendered, FALSE otherwise.
 */
gboolean visu_gl_getFogActive(const VisuGl *set)
{
  g_return_val_if_fail(VISU_IS_GL(set), FALSE);
  return set->priv->fogActive;
}
/**
 * visu_gl_getFogFollowsBg:
 * @set: a #VisuGl object.
 *
 * Read if fog uses a specific colour or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the fog uses its own color or FALSE if it uses
 * the color of the background.
 */
gboolean visu_gl_getFogFollowsBg(const VisuGl *set)
{
  g_return_val_if_fail(VISU_IS_GL(set), FALSE);
  return set->priv->fogFollowsBg;
}
/**
 * visu_gl_getFogStartFull:
 * @set: a #VisuGl object.
 * @startFull: (out caller-allocates) (array fixed-size=2): two float
 * location.
 *
 * Retrieves the starting and ending value (reduced) of fog extension.
 *
 * Since: 3.8
 **/
void visu_gl_getFogStartFull(const VisuGl *set, float startFull[2])
{
  g_return_if_fail(VISU_IS_GL(set));
  memcpy(startFull, set->priv->fogStartEnd, sizeof(float) * 2);
}

/**
 * visu_gl_initContext:
 * @gl: a #VisuGl object.
 * @error: an error location.
 *
 * This method is called when an OpenGL surface is created for the first time.
 * It sets basic OpenGL options and calls other OpenGLFunctions used
 * in V_Sim.
 *
 * Returns: FALSE on error.
 */
gboolean visu_gl_initContext(VisuGl *gl, GError **error)
{
  VisuGlClass *klass = VISU_GL_GET_CLASS(gl);
  g_return_val_if_fail(klass && klass->initContext, FALSE);
  
  return klass->initContext(gl, error);
}
/**
 * visu_gl_freeContext:
 * @gl: a #VisuGl object.
 *
 * This method is called when an OpenGL surface is destroyed to free
 * OpenGL resources.
 *
 * Since: 3.9
 */
void visu_gl_freeContext(VisuGl *gl)
{
  VisuGlClass *klass = VISU_GL_GET_CLASS(gl);
  g_return_if_fail(klass && klass->freeContext);
  
  klass->freeContext(gl);
}
/**
 * visu_gl_paint:
 * @gl: a #VisuGl object.
 *
 * This method is called when it's necessary to redraw.
 */
void visu_gl_paint(VisuGl *gl)
{
  VisuGlClass *klass = VISU_GL_GET_CLASS(gl);
  
  g_return_if_fail(VISU_IS_GL(gl));

  if (klass->draw)
    klass->draw(gl);

  glClearColor(gl->priv->bgRGB[0], gl->priv->bgRGB[1],
               gl->priv->bgRGB[2], gl->priv->bgRGB[3]);
  glClear(GL_COLOR_BUFFER_BIT);
  if (gl->priv->bgRGB[3] < 1.f && !(visu_gl_getHint(gl) & VISU_GL_OFFSCREEN))
    {
      glUseProgram(gl->priv->bgProgramId);
      glUniform4fv(gl->priv->bgId, 1, gl->priv->bgRGB);
      glBindVertexArray(gl->priv->bgVertexArray);
      glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
      glBindVertexArray(0);
      glUseProgram(0);
    }

  visu_gl_rendering_applyMode(gl->priv->mode);
  if (klass->render)
    klass->render(gl);

  glFlush();
}

/******************************************************************************/

/* To set the antialiasing on lines. */
static void glSetAntiAlias(VisuGlPrivate *gl)
{
  if (gl->antialias)
    {
      /* Set blend if not present */
      glEnable(GL_BLEND);
      glBlendEquation(GL_FUNC_ADD);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/*       glBlendFunc(GL_SRC_ALPHA_SATURATE,GL_ONE); */

      /* Antialias */
      glEnable(GL_LINE_SMOOTH);
      glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    }
  else
    {
      glDisable(GL_LINE_SMOOTH);
/*       glDisable(GL_BLEND); */
    }
}
/**
 * visu_gl_setAntialias:
 * @gl: a #VisuGl object.
 * @value: a boolean to activate or not the lines antialias.
 *
 * To set the antialiasing on lines.
 *
 * Returns: TRUE if value is actually changed.
 */
gboolean visu_gl_setAntialias(VisuGl *gl, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (value == gl->priv->antialias)
    return FALSE;
  gl->priv->antialias = value;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[ANTIALIAS_PROP]);

  glSetAntiAlias(gl->priv);
  
  return TRUE;
}
/**
 * visu_gl_getAntialias:
 * @gl: a #VisuGl object.
 *
 * Get the value of the antialiasing parameter.
 *
 * Returns: wether or not the antialising for lines is activated.
 */
gboolean visu_gl_getAntialias(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->antialias;
}

/**
 * visu_gl_getStereoCapability:
 * @gl: a #VisuGl object.
 *
 * Retrieve if the OpenGL window can render in stereo or not.
 *
 * Returns: TRUE if the OpenGL surface can draw in stereo.
 */
gboolean visu_gl_getStereoCapability(const VisuGl *gl _U_)
{
  GLboolean glStereo;

  glGetBooleanv(GL_STEREO, &glStereo);

  return (gboolean)glStereo;
}
/**
 * visu_gl_setTrueTransparency:
 * @gl: a #VisuGl object.
 * @status: a boolean.
 *
 * If true the rendering is done twice to respect the transparency.
 *
 * Returns: TRUE if redraw should be done.
 */
gboolean visu_gl_setTrueTransparency(VisuGl *gl, gboolean status)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (status == gl->priv->trueTransparency)
    return FALSE;
  gl->priv->trueTransparency = status;  
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[TRANS_PROP]);

  return TRUE;
}
/**
 * visu_gl_getTrueTransparency:
 * @gl: a #VisuGl object.
 *
 * The drawing can be done in one pass or two to respect transparency.
 *
 * Returns: TRUE if the drawing is done twice.
 */
gboolean visu_gl_getTrueTransparency(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->trueTransparency;
}
/**
 * visu_gl_setStereoAngle:
 * @gl: a #VisuGl object.
 * @angle: a positive floating point value.
 *
 * Change the angle of the eyes in the stereo output.
 *
 * Returns: TRUE if redraw should be done.
 */
gboolean visu_gl_setStereoAngle(VisuGl *gl, float angle)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  g_return_val_if_fail(angle > 0.f, FALSE);

  if (gl->priv->stereoAngle == angle)
    return FALSE;
  gl->priv->stereoAngle = angle;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[ANGLE_PROP]);

  return TRUE;
}
/**
 * visu_gl_getStereoAngle:
 * @gl: a #VisuGl object.
 *
 * Retrieve the angle of the eyes in the stereo output.
 *
 * Returns: the angle.
 */
float visu_gl_getStereoAngle(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0.f);
  return gl->priv->stereoAngle;
}
/**
 * visu_gl_setStereo:
 * @gl: a #VisuGl object.
 * @status: a boolean.
 *
 * Change the type of rendering. The surface can be switch to stereo,
 * only if the OpenGL has stereo capabilities (see
 * visu_gl_getStereoCapability()).
 */
gboolean visu_gl_setStereo(VisuGl *gl, gboolean status)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (gl->priv->stereoStatus == status)
    return FALSE;
  gl->priv->stereoStatus = status;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[STEREO_PROP]);

  return TRUE;
}
/**
 * visu_gl_getStereo:
 * @gl: a #VisuGl object.
 *
 * Retrieve the status of the OpenGL surface.
 *
 * Returns: TRUE if the surface try to draw in stereo (may be TRUE,
 *          even if visu_gl_getStereoCapability() returns FALSE, in
 *          that case the stereo capability is not used).
 */
gboolean visu_gl_getStereo(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->stereoStatus;
}
/**
 * visu_gl_setMode:
 * @gl: a #VisuGl object.
 * @value: an integer to represent the method of rendering.
 *
 * This function change the value of the parameter renderingOption.
 * It controls how V_Sim renders objects, in wireframe for example.
 *
 * Returns: TRUE if value is actually changed.
 */
gboolean visu_gl_setMode(VisuGl *gl, VisuGlRenderingMode value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  g_return_val_if_fail(value < VISU_GL_RENDERING_N_MODES, FALSE);
  
  if (value == gl->priv->mode)
    return FALSE;

  gl->priv->mode = value;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[MODE_PROP]);
  visu_gl_rendering_applyMode(value);

  return TRUE;
}
/**
 * visu_gl_getMode:
 * @gl: a #VisuGl object.
 *
 * This function retrieve the value of the parameter renderingOption.
 *
 * Returns: the identifier of the current rendering option.
 */
VisuGlRenderingMode visu_gl_getMode(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), renderingOption);
  return gl->priv->mode;
}
/**
 * visu_gl_addHint:
 * @gl: a #VisuGl object.
 * @value: a mask of hints.
 *
 * Set some additional hints to @gl.
 *
 * Since: 3.8
 *
 * Returns: the mask of current hints.
 **/
guint visu_gl_addHint(VisuGl *gl, guint value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0);
  
  return (gl->priv->hints |= value);
}
/**
 * visu_gl_removeHint:
 * @gl: a #VisuGl object.
 * @value: a mask of hints.
 *
 * Remove an additional hints from @gl.
 *
 * Since: 3.9
 *
 * Returns: the mask of current hints.
 **/
guint visu_gl_removeHint(VisuGl *gl, guint value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0);
  
  return (gl->priv->hints ^= value);
}
/**
 * visu_gl_getHint:
 * @gl: a #VisuGl object.
 *
 * Retrieve hints of @gl.
 *
 * Since: 3.8
 *
 * Returns: the mask of current hints.
 **/
guint visu_gl_getHint(VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0);
  
  return gl->priv->hints;
}

static void _openGLMessage(GLenum source _U_, GLenum type, GLuint id, GLenum severity,
                           GLsizei length _U_, const GLchar* message,
                           const void* userParam _U_)
{
  gboolean warn = TRUE;
  const char *ctype, *cseverity;
  switch (severity)
    {
    case GL_DEBUG_SEVERITY_LOW:
      cseverity = "LOW";
      break;
    case GL_DEBUG_SEVERITY_MEDIUM:
      cseverity = "MEDIUM";
      break;
    case GL_DEBUG_SEVERITY_HIGH:
      cseverity = "HIGH";
      break;
    default:
      cseverity = "UNKNOWN";
    }
  switch (type)
    {
    case GL_DEBUG_TYPE_ERROR:
      ctype = "ERROR";
      break;
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
      ctype = "DEPRECATION";
      break;
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
      ctype = "UNDEFINED";
      break;
    case GL_DEBUG_TYPE_PORTABILITY:
      ctype = "PORTABILITY";
      break;
    default:
      ctype = "OTHER";
      warn = FALSE;
    }
  if (warn)
    g_warning("GL CALLBACK: type = %s, severity = %s, id = %d, message = %s",
              ctype, cseverity, id, message);
  else
    g_debug("Visu OpenGL: type = %s, severity = %s, id = %d, message = %s",
            ctype, cseverity, id, message);
}

/***************************/
/* Dealing with parameters */
/***************************/
static void onEntryAntialias(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setAntialias(self, antialias);
}
static void onEntryTrans(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setTrueTransparency(self, trueTransparency);
}
static void onEntryStereo(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setStereo(self, stereoStatus);
}
static void onEntryAngle(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setStereoAngle(self, stereoAngle);
}
static void onEntryMode(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setMode(self, renderingOption);
}
static void exportParametersOpenGL(GString *data,
                                   VisuData *dataObj _U_)
{
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_ANTIALIAS);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_ANTIALIAS,
	  defaultGl->priv->antialias);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_TRANSS);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_TRANS,
	  defaultGl->priv->trueTransparency);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_STEREO);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_STEREO,
	  defaultGl->priv->stereoStatus);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_ANGLE);
  g_string_append_printf(data, "%s: %f\n\n", FLAG_PARAMETER_OPENGL_ANGLE,
	  defaultGl->priv->stereoAngle);
}
static void onEntryBgColor(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setBgColor(self, bgRGBDefault, TOOL_COLOR_MASK_RGBA);
}
static void onEntryFogActive(VisuGl *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setFogActive(set, fogActiveDefault);
}
static void onEntryFogSpecific(VisuGl *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setFogFollowsBg(set, !fogSpecificDefault);
}
static void onEntryFogColor(VisuGl *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setFogColor(set, fogRGBDefault, TOOL_COLOR_MASK_RGBA);
}
static void onEntryFogStartEnd(VisuGl *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setFogStartFull(set, fogStartEndDefault, VISU_GL_FOG_MASK_START | VISU_GL_FOG_MASK_FULL);
}
static void exportOpenGL(GString *data, VisuData *dataObj _U_)
{
  visu_config_file_exportComment(data, DESC_RESOURCE_OPENGL_RENDERING);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_OPENGL_RENDERING, NULL,
                               "%s", visu_gl_rendering_getAllModes()[defaultGl->priv->mode]);
  visu_config_file_exportComment(data, "");
  visu_config_file_exportComment(data, DESC_RESOURCE_BG_COLOR);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_BG_COLOR, NULL,
                               "%4.3f %4.3f %4.3f %4.3f",
                               defaultGl->priv->bgRGB[0], defaultGl->priv->bgRGB[1],
                               defaultGl->priv->bgRGB[2], defaultGl->priv->bgRGB[3]);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_USED);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_USED, NULL,
                               "%d", defaultGl->priv->fogActive);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_SPECIFIC);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_SPECIFIC, NULL,
                               "%d", !defaultGl->priv->fogFollowsBg);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_COLOR);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_COLOR, NULL,
                               "%4.3f %4.3f %4.3f %4.3f",
                               defaultGl->priv->fogRGB[0], defaultGl->priv->fogRGB[1],
                               defaultGl->priv->fogRGB[2], defaultGl->priv->fogRGB[3]);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_STARTEND);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_STARTEND, NULL,
                               "%4.3f %4.3f", defaultGl->priv->fogStartEnd[0],
                               defaultGl->priv->fogStartEnd[1]);
}
