/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	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-2006)

	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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <X11/Xlib.h>
#include <GL/glx.h>

#include <glib.h>

#include "visu_openGL.h"
#include <visu_tools.h>
#include <openGLFunctions/text.h>

static Display *dpy = (Display*)0;
static gboolean Xerror = FALSE;

struct _VisuPixmapContext
{
  GLXContext context;
#ifdef HAVE_PBUFFER
  GLXPbuffer glxPbuffer;
#else
  GLXPixmap glxPixmap;
#endif
  Pixmap pixmap;
  guint width, height;
};

struct _VisuGLXFont
{
  GLuint id;
  GLsizei len;
  XFontStruct *font;
};

static GHashTable *fonts = (GHashTable*)0;

static int handler(Display *dpy _U_, XErrorEvent *error _U_)
{
  DBG_fprintf(stderr, "Visu GLX: ouch one X error.\n");
  Xerror = TRUE;
  return 0;
}

#ifdef HAVE_PBUFFER
static XVisualInfo* _visualInfoFromFB(Display *dpy, int screenId, GLXFBConfig **fb)
{
  XVisualInfo *vinfo;
  GLXFBConfig *fbconfig;
  int nitems;
  int attrib[] = {
    GLX_DOUBLEBUFFER,  False,
    GLX_RED_SIZE,      1,
    GLX_GREEN_SIZE,    1,
    GLX_BLUE_SIZE,     1,
    GLX_DEPTH_SIZE,    1,
    GLX_RENDER_TYPE,   GLX_RGBA_BIT,
    GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
    None
  };

  fbconfig = glXChooseFBConfig(dpy, screenId, attrib, &nitems);
  if (fbconfig == (GLXFBConfig*)0 || nitems == 0)
    {
      g_warning("Can't get FBConfig.");
      return (XVisualInfo*)0;
    }
  *fb = fbconfig;
  vinfo = glXGetVisualFromFBConfig(dpy, fbconfig[0]);
  if (!vinfo)
    {
      g_warning("Can't get RGBA Visual.");
      return (XVisualInfo*)0;
    }  

  return vinfo;
}
#endif
XVisualInfo* visu_gl_getVisualInfo(Display *dpy, int screenId)
{
  XVisualInfo *vinfo;
  int list[] = {
    GLX_RGBA,
    GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
    GLX_DEPTH_SIZE, 1,
    GLX_DOUBLEBUFFER,
    GLX_STEREO,
    None
  };

  if ( (vinfo = glXChooseVisual(dpy, screenId, list)) == NULL )
    {
      list[10] = None; 
      if ( (vinfo = glXChooseVisual(dpy, screenId, list)) == NULL )
	{
	  g_error("Cannot find a visual.\n"
		  "Have you enough right access on the X server?");
	}
      DBG_fprintf(stderr, " | not a stereo buffer.\n");
    }
  else
    DBG_fprintf(stderr, " | stereo buffer.\n");

  return vinfo;
}

/**
 * visu_pixmap_context_new:
 * @width: an integer ;
 * @height: an integer.
 *
 * Create a pixmap storage and a context associated to it. This pixmap
 * can then be used to dump pixel data from an OpenGL area.
 *
 * Returns: (transfer none): a newly allocated #DumpImage object.
 */
VisuPixmapContext* visu_pixmap_context_new(guint width, guint height)
{
  VisuPixmapContext *image;
  int screenId, res;
  Bool direct;
  XVisualInfo *visualInfo;
#ifdef HAVE_PBUFFER
  GLXFBConfig *fbconfig;
  int pbufAttrib[] = {
    GLX_PBUFFER_WIDTH,   0,
    GLX_PBUFFER_HEIGHT,  0,
    GLX_LARGEST_PBUFFER, False,
    None
  };
#endif

  DBG_fprintf(stderr, "Visu GLX: creating a off-screen buffer (%dx%d).\n", width, height);
  image = g_malloc(sizeof(VisuPixmapContext));
  image->pixmap = (Pixmap)0;
#ifdef HAVE_PBUFFER
  image->glxPbuffer = (GLXPbuffer)0;
#else
  image->glxPixmap = (GLXPixmap)0;
#endif
  image->context = (GLXContext)0;

  if (!dpy)
    dpy = XOpenDisplay(0);

  if (!dpy)
    {
      g_warning("Cannot connect to the X server.");
      g_free(image);
      return (VisuPixmapContext*)0;
    }
  DBG_fprintf(stderr, "Visu GLX: display opened.\n");

  screenId = DefaultScreen(dpy);
#ifdef HAVE_PBUFFER
  visualInfo = _visualInfoFromFB(dpy, screenId, &fbconfig);
#else
  visualInfo = visu_gl_getVisualInfo(dpy, screenId);
#endif
  if (!visualInfo)
    {
      g_free(image);
      return (VisuPixmapContext*)0;
    }

  image->width = width;
  image->height = height;
  image->pixmap = XCreatePixmap(dpy, RootWindow(dpy, screenId),
				width, height, visualInfo->depth);
  if (!image->pixmap)
    {
      g_warning("Cannot allocate a XPixmap for the indirect rendering.");
      g_free(image);
      XFree(visualInfo);
      return (VisuPixmapContext*)0;
    }
  DBG_fprintf(stderr, "Visu GLX: X pixmap created.\n");

#ifdef HAVE_PBUFFER
  pbufAttrib[1] = width;
  pbufAttrib[3] = height;
  image->glxPbuffer = glXCreatePbuffer(dpy, fbconfig[0], pbufAttrib);
  DBG_fprintf(stderr, "Visu GLX: use pBuffer.\n");
  if (!image->glxPbuffer)
    {
      g_warning("Cannot allocate a GLXPbuffer for the indirect rendering.");
      XFreePixmap(dpy, image->pixmap);
      g_free(image);
      XFree(visualInfo);
      return (VisuPixmapContext*)0;
    }
  direct = GL_TRUE;
#else
  image->glxPixmap = glXCreateGLXPixmap(dpy, visualInfo, image->pixmap);
  DBG_fprintf(stderr, "Visu GLX: use GLXPixmap.\n");
  if (!image->glxPixmap)
    {
      g_warning("Cannot allocate a GLXPixmap for the indirect rendering.");
      XFreePixmap(dpy, image->pixmap);
      g_free(image);
      XFree(visualInfo);
      return (VisuPixmapContext*)0;
    }
  direct = GL_FALSE;
#endif
  DBG_fprintf(stderr, "Visu GLX: GLX off-creen surface created.\n");

  image->context = glXCreateContext(dpy, visualInfo, 0, direct);
  if (!image->context)
    {
      g_warning("Cannot create indirect GLX context.");
      XFreePixmap(dpy, image->pixmap);
#ifdef HAVE_PBUFFER
      glXDestroyPbuffer(dpy, image->glxPbuffer);
#else
      glXDestroyGLXPixmap(dpy, image->glxPixmap);
#endif
      g_free(image);
      XFree(visualInfo);
      return (VisuPixmapContext*)0;
    }
  DBG_fprintf(stderr, "Visu GLX: new OpenGL context created.\n");

  Xerror = FALSE;
  XSetErrorHandler(handler);
#ifdef HAVE_PBUFFER
  res = glXMakeCurrent(dpy, image->glxPbuffer, image->context);
#else
  res = glXMakeCurrent(dpy, image->glxPixmap, image->context);
#endif
  XSetErrorHandler(NULL);
  if (!res || Xerror)
    {
      g_warning("Cannot make current the pixmap context.");
      XFreePixmap(dpy, image->pixmap);
#ifdef HAVE_PBUFFER
      glXDestroyPbuffer(dpy, image->glxPbuffer);
#else
      glXDestroyGLXPixmap(dpy, image->glxPixmap);
#endif
      g_free(image);
      XFree(visualInfo);
      return (VisuPixmapContext*)0;
    }
  DBG_fprintf(stderr, "Visu GLX: pixmap context is now current.\n");

  /* Changing context, update fonts. */
  visu_gl_text_onNewContext();

  XFree(visualInfo);

  glXWaitX();

  return image;
}

/**
 * visu_pixmap_context_free:
 * @dumpData: an allocated #DumpImage object.
 *
 * Free an allocated #DumpImage.
 */
void visu_pixmap_context_free(VisuPixmapContext *dumpData)
{
  g_return_if_fail(dumpData);

  if (dpy)
    {
#ifdef HAVE_PBUFFER
      DBG_fprintf(stderr, "Visu GLX: free the GLX pbuffer 0x%x.\n",
		  (int)dumpData->glxPbuffer);
      if (dumpData->glxPbuffer)
        glXDestroyPbuffer(dpy, dumpData->glxPbuffer);
#else
      DBG_fprintf(stderr, "Visu GLX: free the GLX pixmap 0x%x.\n",
		  (int)dumpData->glxPixmap);
      if (dumpData->glxPixmap)
        glXDestroyGLXPixmap(dpy, dumpData->glxPixmap);
#endif

      DBG_fprintf(stderr, "Visu GLX: free the X pixmap 0x%x.\n",
		  (int)dumpData->pixmap);
      if (dumpData->pixmap)
	XFreePixmap(dpy, dumpData->pixmap);

      DBG_fprintf(stderr, "Visu GLX: free the context.\n");
      if (dumpData->context)
	glXDestroyContext(dpy, dumpData->context);

      /* We do NOT close the display since it is shared
	 by all the application and thus dpy structure
	 is unique and will be closed by the main program when quiting. */
      /*   XCloseDisplay(dumpData->dpy); */
      glXWaitX();
    }
  g_free(dumpData);
}

static void freeFont(gpointer data)
{
  struct _VisuGLXFont *font = (struct _VisuGLXFont*)data;

  if (!dpy)
    dpy = XOpenDisplay(0);

  DBG_fprintf(stderr, "Visu GLX: delete font %d.\n", font->id);
  glDeleteLists(font->id, font->len);
  XFreeFont(dpy, font->font);
  g_free(data);
}

GLuint visu_gl_initFontList(guint size)
{
  XFontStruct *fontInfo = (XFontStruct*)0;
  guint first, last; 
  gchar *name;
  struct _VisuGLXFont *font;

  name = g_strdup_printf("-misc-fixed-bold-r-normal-*-%d-*-*-*-*-*-iso8859-1", size);
  DBG_fprintf(stderr, "Visu GLX: initialise fonts (%s).\n", name);
        
  if (!dpy)
    dpy = XOpenDisplay(0);
  if (!fonts)
    fonts = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, freeFont);

  /* Delete previous lists for this size. */
  DBG_fprintf(stderr, " | remove previous entry %p if any from %p (%d).\n",
              GINT_TO_POINTER(size), (gpointer)fonts, g_hash_table_size(fonts));
  g_hash_table_remove(fonts, name);

  DBG_fprintf(stderr, " | get the X font description.\n");
  Xerror = FALSE;
  XSetErrorHandler(handler);
  if ((fontInfo = XLoadQueryFont(dpy, name)) == NULL) 
    {
      g_message("Specified font not available in gl_font_init\n" 
                "Trying to use fixed font\n"); 
      if ((fontInfo = XLoadQueryFont(dpy, "fixed")) == NULL) 
        {
          g_error("Fixed font not available.\n"); 
        }
    }
  XSetErrorHandler(NULL);
  if (Xerror)
    {
      g_warning("No font for this surface.");
      return 0;
    }
  DBG_fprintf(stderr, " | Found XFontStruct.\n");

  first = fontInfo->min_char_or_byte2; 
  last = fontInfo->max_char_or_byte2; 
  DBG_fprintf(stderr, " | XFontStruct OK (%d %d).\n", first, last);
 
  /* this creates display lists 1 to 256 (not checked) */ 
  font = g_malloc(sizeof(struct _VisuGLXFont));
  font->font = fontInfo;
  font->len = last + 1;
  font->id = glGenLists(font->len);
  if (!font->id)
    {
      g_free(font);
      g_free(name);
      return 0;
    }
  g_hash_table_insert(fonts, name, (gpointer)font);
    
  Xerror = FALSE;
  XSetErrorHandler(handler);
  glXUseXFont(fontInfo->fid, first, last-first+1, font->id+first);
  XSetErrorHandler(NULL);
  if (Xerror)
    {
      g_warning("No font generation for this surface.");
      font->id = 0;
    }
  DBG_fprintf(stderr, " | list id %d\n", font->id);

  return font->id; 
}
