opengl-intro: mouse.c

File mouse.c, 2.0 KB (added by msitar, 15 years ago)

Risanje črt z uporabo miške

Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <GL/glut.h>
4
5#define MAXN 100
6
7GLint n;
8GLfloat *vertex;
9
10void redraw()
11{
12  int i;
13  glClear(GL_COLOR_BUFFER_BIT);
14  glPushMatrix();
15  glColor3f(1,1,1);
16  glBegin(GL_LINE_STRIP);
17  for (i = 0; i < n; i++)
18  {
19    glVertex2fv(&vertex[i*2]);
20  }
21  glEnd();
22 
23  for (i = 0; i < n; i++) //Adding spheres on world coords
24  {
25  glColor3f(1,0,0);
26  glPushMatrix();
27  glTranslatef(vertex[i*2],vertex[i*2+1],0); 
28  glutSolidSphere(0.01,8,8); 
29  glPopMatrix();
30  }
31  glPopMatrix();
32  glutSwapBuffers();
33}
34
35void mouse(int button, int state, int x, int y)
36{
37  GLint viewport[4];
38  GLdouble mvmatrix[16], projmatrix[16];
39  GLdouble wx, wy, wz; //World x, y, z coords
40  GLdouble px, py, pz; //Picked window coordinates
41  int status;
42  if (button == GLUT_LEFT_BUTTON )
43  {
44  if (state == GLUT_DOWN) 
45    {
46      glGetIntegerv (GL_VIEWPORT, viewport);
47      glGetDoublev (GL_MODELVIEW_MATRIX, mvmatrix);
48      glGetDoublev (GL_PROJECTION_MATRIX, projmatrix);
49      //Note viewport[4] is height in pixels
50      px = x;
51      py = viewport[3] - y - 1;
52      pz = 0.0;
53      fprintf (stderr, "Coordinates at cursor are %f, %f\n", px, py);
54      status = gluUnProject (px, py, pz, mvmatrix, projmatrix, viewport, &wx, &wy, &wz);
55      fprintf(stderr, "World coords at z=0.0 are %f, %f, %f\n", wx, wy, wz);
56      if (n < MAXN) 
57      {
58        vertex[n*2] = wx; 
59        vertex[n*2+1] = wy;
60        n=n+1;
61      }       
62      else
63      {
64        fprintf(stderr, "Maximum number of points was recieved!\n");
65      }
66      glutPostRedisplay();
67    }
68  }
69}
70
71/**************************** Glavni program **************************************/
72
73int main(int argc, char *argv[])
74{ 
75  vertex = (GLfloat *) malloc(2 * MAXN * sizeof (GLfloat)); 
76  glutInit(&argc, argv);
77  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
78  glutInitWindowSize (700, 700);
79  glutInitWindowPosition (0, 0);
80  glutCreateWindow("Click in window");
81  glutDisplayFunc(redraw); 
82  glutMouseFunc(mouse);
83  glutMainLoop();
84  return 0;
85}