#include <stdio.h>
#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include "Bitmap.h"
#include "Espace3UC.h"

/* ************************************************************************ */
/*               Module de gestion d'un espaceDessin bitmap                 */
/* ************************************************************************ */

void affichageGLBitmap(struct espace *e)
  { int t = e->dx*e->dy*3 ;
    GLubyte *im =(GLubyte *) calloc(t,sizeof(GLubyte));
    struct c24bits *l =(struct c24bits *) calloc(e->dx,sizeof(struct c24bits)) ;
    for ( int i = 0 ; i < e->dy ; i++ ) {
      cherche_ligne(i,(unsigned char *) l,e) ;
      for ( int j = 0 ; j < e->dx ; j++ ) {
        int ind = (i*e->dx+j)*3 ;
        im[ind] = l[j].r ;
        im[ind+1] = l[j].v ;
        im[ind+2] = l[j].b ; } }
    glRasterPos2f(0.0F,0.0F) ;
    glDrawPixels(e->dx,e->dy,GL_RGB,GL_UNSIGNED_BYTE,im) ;
    free(im) ;
    free(l) ;
}

void affichageGLBitmap(struct espace *e,int px,int py)
  { int t = e->dx*e->dy*3 ;
    GLubyte *im =(GLubyte *) calloc(t,sizeof(GLubyte));
    struct c24bits *l =(struct c24bits *) calloc(e->dx,sizeof(struct c24bits)) ;
    for ( int i = 0 ; i < e->dy ; i++ ) {
      cherche_ligne(i,(unsigned char *) l,e) ;
      for ( int j = 0 ; j < e->dx ; j++ ) {
        int ind = (i*e->dx+j)*3 ;
        im[ind] = l[j].r ;
        im[ind+1] = l[j].v ;
        im[ind+2] = l[j].b ; } }
    glRasterPos2f(px,py) ;
    glDrawPixels(e->dx,e->dy,GL_RGB,GL_UNSIGNED_BYTE,im) ;
    free(im) ;
    free(l) ;
}

void extractionGLBitmap(struct espace *e)
  { int dx = glutGet(GLUT_WINDOW_WIDTH);
    int dy = glutGet(GLUT_WINDOW_HEIGHT);
    int t = dx*dy*3 ;
    GLubyte *im =(GLubyte *) calloc(t,sizeof(GLubyte));
    new_espace(e,dx,dy,24) ;
    glReadPixels(0,0,e->dx,e->dy,GL_RGB,GL_UNSIGNED_BYTE,im) ;
    for ( int i = 0 ; i < e->dy ; i++ ) {
      sauve_ligne(i,(unsigned char *) &im[i*3*e->dx],e) ; }
    free(im) ;
}

Espace3UC *extractionGLBitmap(void)
  { int dx = glutGet(GLUT_WINDOW_WIDTH);
    int dy = glutGet(GLUT_WINDOW_HEIGHT);
    Espace3UC *espace = new Espace3UC(dx,dy);
    for ( int i = 0 ; i < dy ; i++ ) {
      glReadPixels(0,i,dx,1,GL_RGB,GL_UNSIGNED_BYTE,espace->p[i]); }
    return(espace) ;
}

Espace3UC *extractionGLBitmap(int dx,int dy)
  { Espace3UC *espace = new Espace3UC(dx,dy);
    if ( espace->alloue() ) {
      for ( int i = 0 ; i < dy ; i++ ) {
         glReadPixels(0,i,dx,1,GL_RGB,GL_UNSIGNED_BYTE,espace->p[i]); } }
    return(espace) ;
}

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