#include "gloutils.h"
#include <GL/glu.h>
#include "types.h"
#include "vecmath.h"

void glouAbsoluteRasterPos3f (float x, float y, float z)
{
  GLdouble modelview[16], projection[16] ;
  GLdouble rx,ry,rz ;
  GLint viewport[4] ;
  
  glGetDoublev (GL_PROJECTION_MATRIX, projection) ;
  glGetDoublev (GL_MODELVIEW_MATRIX, modelview) ;
  glGetIntegerv (GL_VIEWPORT, viewport) ;

  if (x<0) x=viewport[2]+x ;
  if (y<0) y=viewport[3]+y ; 

  gluUnProject (0.5+x, 0.5+y, z, 
		modelview, projection, viewport,
		&rx, &ry, &rz) ;
  glRasterPos3d (rx,ry,rz) ;
}

void glouGetMatrix (GLenum data, matrix* m) 
{
  GLdouble tab[16] ;
  int i,j ;
  glGetDoublev (data, tab) ;
  for (i=0; i<4; i++)
    for (j=0; j<4; j++)
      (*m)[j][i] = tab[j+i*4];
}

void glouGet (opengldata_t* gldata) {
  int i,j ;
  glGetIntegerv (GL_VIEWPORT, gldata->viewport) ;
  glGetDoublev (GL_MODELVIEW_MATRIX, gldata->modelview) ;
  glGetDoublev (GL_PROJECTION_MATRIX, gldata->projection) ;
  for (i=0; i<4; i++)
    for (j=0; j<4; j++) {
      gldata->projectionmatrix[j][i] = gldata->projection[j+i*4];
      gldata->modelviewmatrix[j][i] = gldata->modelview[j+i*4];
    }
  matrix_inverse (&gldata->modelviewinverse, gldata->modelviewmatrix) ;
  matrix_inverse (&gldata->projectioninverse, gldata->projectionmatrix) ;
}
