aboutsummaryrefslogtreecommitdiffstats
path: root/progs/xdemos/corender.c
blob: f2b8145e52b4ac297e32d1f41bf9d50ed8f282bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
 * Example of cooperative rendering into one window by two processes.
 * The first instance of the program creates the GLX window.
 * The second instance of the program gets the window ID from the first
 * and draws into it.
 * Socket IPC is used for synchronization.
 *
 * Usage:
 * 1. run 'corender &'
 * 2. run 'corender 2'  (any arg will do)
 *
 * Brian Paul
 * 11 Oct 2007
 */


#include <GL/gl.h>
#include <GL/glx.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/keysym.h>
#include <unistd.h>
#include "ipc.h"


#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

static int MyID = 0;  /* 0 or 1 */
static int WindowID = 0;
static GLXContext Context = 0;
static int Width = 700, Height = 350;
static int Rot = 0;
static int Sock = 0;

static GLfloat Red[4] = {1.0, 0.2, 0.2, 1.0};
static GLfloat Blue[4] = {0.2, 0.2, 1.0, 1.0};

static int Sync = 1;  /** synchronized rendering? */


static void
setup_ipc(void)
{
   int k, port = 10001;

   if (MyID == 0) {
      /* I'm the first one, wait for connection from second */
      k = CreatePort(&port);
      assert(k != -1);

      printf("Waiting for connection from another 'corender'\n");
      Sock = AcceptConnection(k);

      printf("Got connection, sending windowID\n");

      /* send windowID */
      SendData(Sock, &WindowID, sizeof(WindowID));
   }
   else {
      /* I'm the second one, connect to first */
      char hostname[1000];

      MyHostName(hostname, 1000);
      Sock = Connect(hostname, port);
      assert(Sock != -1);

      /* get windowID */
      ReceiveData(Sock, &WindowID, sizeof(WindowID));
      printf("Contacted first 'corender', getting WindowID\n");
   }
}



/** from GLUT */
static void
doughnut(GLfloat r, GLfloat R, GLint nsides, GLint rings)
{
  int i, j;
  GLfloat theta, phi, theta1;
  GLfloat cosTheta, sinTheta;
  GLfloat cosTheta1, sinTheta1;
  GLfloat ringDelta, sideDelta;

  ringDelta = 2.0 * M_PI / rings;
  sideDelta = 2.0 * M_PI / nsides;

  theta = 0.0;
  cosTheta = 1.0;
  sinTheta = 0.0;
  for (i = rings - 1; i >= 0; i--) {
    theta1 = theta + ringDelta;
    cosTheta1 = cos(theta1);
    sinTheta1 = sin(theta1);
    glBegin(GL_QUAD_STRIP);
    phi = 0.0;
    for (j = nsides; j >= 0; j--) {
      GLfloat cosPhi, sinPhi, dist;

      phi += sideDelta;
      cosPhi = cos(phi);
      sinPhi = sin(phi);
      dist = R + r * cosPhi;

      glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi);
      glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi);
      glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi);
      glVertex3f(cosTheta * dist, -sinTheta * dist,  r * sinPhi);
    }
    glEnd();
    theta = theta1;
    cosTheta = cosTheta1;
    sinTheta = sinTheta1;
  }
}


static void
redraw(Display *dpy)
{
   int dbg = 0;

   glXMakeCurrent(dpy, WindowID, Context);
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_DEPTH_TEST);
   glClearColor(0.5, 0.5, 0.5, 0.0);

   if (MyID == 0) {
      /* First process */

      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

      glPushMatrix();
      glTranslatef(-1, 0, 0);
      glRotatef(Rot, 1, 0, 0);
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Red);
      doughnut(0.5, 2.0, 20, 30);
      glPopMatrix();

      glFinish();
      if (!Sync) {
         usleep(1000*10);
      }

      /* signal second process to render */
      if (Sync) {
         int code = 1;
         if (dbg) printf("0: send signal\n");
         SendData(Sock, &code, sizeof(code));
         SendData(Sock, &Rot, sizeof(Rot));
      }

      /* wait for second process to finish rendering */
      if (Sync) {
         int code = 0;
         if (dbg) printf("0: wait signal\n");
         ReceiveData(Sock, &code, sizeof(code));
         if (dbg) printf("0: got signal\n");
         assert(code == 2);
      }

   }
   else {
      /* Second process */

      /* wait for first process's signal for me to render */
      if (Sync) {
         int code = 0;
         if (dbg) printf("1: wait signal\n");
         ReceiveData(Sock, &code, sizeof(code));
         ReceiveData(Sock, &Rot, sizeof(Rot));

         if (dbg) printf("1: got signal\n");
         assert(code == 1);
      }

      /* XXX this clear should not be here, but for some reason, it
       * makes things _mostly_ work correctly w/ NVIDIA's driver.
       * There's only occasional glitches.
       * Without this glClear(), depth buffer for the second process
       * is pretty much broken.
       */
      //glClear(GL_DEPTH_BUFFER_BIT);

      glPushMatrix();
      glTranslatef(1, 0, 0);
      glRotatef(Rot + 90 , 1, 0, 0);
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Blue);
      doughnut(0.5, 2.0, 20, 30);
      glPopMatrix();
      glFinish();

      glXSwapBuffers(dpy, WindowID);
      usleep(1000*10);

      /* signal first process that I'm done rendering */
      if (Sync) {
         int code = 2;
         if (dbg) printf("1: send signal\n");
         SendData(Sock, &code, sizeof(code));
      }
   }
}


static void
resize(Display *dpy, int width, int height)
{
   float ar = (float) width / height;

   glXMakeCurrent(dpy, WindowID, Context);

   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glFrustum(-ar, ar, 1.0, -1.0, 5.0, 200.0);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glTranslatef(0, 0, -15);

   Width = width;
   Height = height;
}



static void
set_window_title(Display *dpy, Window win, const char *title)
{
   XSizeHints sizehints;
   sizehints.flags = 0;
   XSetStandardProperties(dpy, win, title, title,
                          None, (char **)NULL, 0, &sizehints);
}


static Window
make_gl_window(Display *dpy, XVisualInfo *visinfo, int width, int height)
{
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   int x = 0, y = 0;
   char *name = NULL;

   scrnum = DefaultScreen( dpy );
   root = RootWindow( dpy, scrnum );

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow( dpy, root, x, y, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr );

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(dpy, win, &sizehints);
      XSetStandardProperties(dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

   return win;
}


static void
set_event_mask(Display *dpy, Window win)
{
   XSetWindowAttributes attr;
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   XChangeWindowAttributes(dpy, win, CWEventMask, &attr);
}


static void
event_loop(Display *dpy)
{
   while (1) {
      while (XPending(dpy) > 0) {
         XEvent event;
         XNextEvent(dpy, &event);

         switch (event.type) {
         case Expose:
            redraw(dpy);
            break;
         case ConfigureNotify:
            resize(dpy, event.xconfigure.width, event.xconfigure.height);
            break;
         case KeyPress:
            {
               char buffer[10];
               int r, code;
               code = XLookupKeysym(&event.xkey, 0);
               if (code == XK_Left) {
               }
               else {
                  r = XLookupString(&event.xkey, buffer, sizeof(buffer),
                                    NULL, NULL);
                  if (buffer[0] == 27) {
                     exit(0);
                  }
               }
            }
         default:
            /* nothing */
            ;
         }
      }

      if (MyID == 0 || !Sync)
         Rot += 1;
      redraw(dpy);
   }
}


static XVisualInfo *
choose_visual(Display *dpy)
{
   int attribs[] = { GLX_RGBA,
                     GLX_RED_SIZE, 1,
                     GLX_GREEN_SIZE, 1,
                     GLX_BLUE_SIZE, 1,
                     GLX_DOUBLEBUFFER,
                     GLX_DEPTH_SIZE, 1,
                     None };
   int scrnum = DefaultScreen( dpy );
   return glXChooseVisual(dpy, scrnum, attribs);
}


static void
parse_opts(int argc, char *argv[])
{
   if (argc > 1) {
      MyID = 1;
   }
}


int
main( int argc, char *argv[] )
{
   Display *dpy;
   XVisualInfo *visinfo;

   parse_opts(argc, argv);

   dpy = XOpenDisplay(NULL);

   visinfo = choose_visual(dpy);

   Context = glXCreateContext( dpy, visinfo, NULL, True );
   if (!Context) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   if (MyID == 0) {
      WindowID = make_gl_window(dpy, visinfo, Width, Height);
      set_window_title(dpy, WindowID, "corender");
      XMapWindow(dpy, WindowID);
      /*printf("WindowID 0x%x\n", (int) WindowID);*/
   }

   /* do ipc hand-shake here */
   setup_ipc();
   assert(Sock);
   assert(WindowID);

   if (MyID == 1) {
      set_event_mask(dpy, WindowID);
   }

   resize(dpy, Width, Height);

   event_loop(dpy);

   return 0;
}