summaryrefslogtreecommitdiff
path: root/triangle.c
blob: 552f05f12f259e79d2921d9a5b5e63953e9d1bc3 (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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
Copyright (c) 2012, Broadcom Europe Ltd
Copyright (c) 2012, OtherCrashOverride
Copyright (C) 2014, Fluendo S.A.
   @author: Josep Torra <josep@fluendo.com>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* A rotating cube rendered with OpenGL|ES with a video on it */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <termios.h>

#include <glib.h>

#include "bcm_host.h"

#include "GLES/gl.h"
#include "EGL/egl.h"
#include "EGL/eglext.h"

#include "cube_texture_and_coords.h"

#include "triangle.h"
#include "egl.h"

#define PATH "./"

#define IMAGE_SIZE_WIDTH 1920
#define IMAGE_SIZE_HEIGHT 1080

#ifndef M_PI
#define M_PI 3.141592654
#endif

typedef struct
{
  DISPMANX_DISPLAY_HANDLE_T dispman_display;
  DISPMANX_ELEMENT_HANDLE_T dispman_element;

  uint32_t screen_width;
  uint32_t screen_height;

  gboolean animate;

  /* OpenGL|ES objects */
  EGLDisplayWrapper *display;
  EGLSurface surface;
  EGLContext context;
  GLuint tex;

  /* model rotation vector and direction */
  GLfloat rot_angle_x_inc;
  GLfloat rot_angle_y_inc;
  GLfloat rot_angle_z_inc;

  /* current model rotation angles */
  GLfloat rot_angle_x;
  GLfloat rot_angle_y;
  GLfloat rot_angle_z;

  /* current distance from camera */
  GLfloat distance;
  GLfloat distance_inc;

  /* GLib mainloop */
  GMainLoop *main_loop;
  /* Rendering thread state */
  gboolean running;

  IPC_T ipc;
} AppState;

static void init_ogl (AppState * state);
static void init_model_proj (AppState * state);
static void reset_model (AppState * state);
static GLfloat inc_and_wrap_angle (GLfloat angle, GLfloat angle_inc);
static GLfloat inc_and_clip_distance (GLfloat distance, GLfloat distance_inc);
static void redraw_scene (AppState * state);
static void update_model (AppState * state);
static void init_textures (AppState * state);
static volatile int terminate;
static AppState _state, *state = &_state;

/***********************************************************
 * Name: init_ogl
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description: Sets the display, OpenGL|ES context and screen stuff
 *
 * Returns: void
 *
 ***********************************************************/
static void
init_ogl (AppState * state)
{
  int32_t success = 0;
  EGLBoolean result;
  EGLint num_config;
  EGLDisplay display;

  static EGL_DISPMANX_WINDOW_T nativewindow;

  DISPMANX_UPDATE_HANDLE_T dispman_update;
  DISPMANX_MODEINFO_T mode_info;
  VC_RECT_T dst_rect;
  VC_RECT_T src_rect;

  static const EGLint attribute_list[] = {
    EGL_RED_SIZE, 8,
    EGL_GREEN_SIZE, 8,
    EGL_BLUE_SIZE, 8,
    EGL_ALPHA_SIZE, 8,
    EGL_DEPTH_SIZE, 16,
    //EGL_SAMPLES, 4,
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
    EGL_NONE
  };

  EGLConfig config;

  /* get an EGL display connection */
  display = eglGetDisplay (EGL_DEFAULT_DISPLAY);
  assert (display != EGL_NO_DISPLAY);
  state->display = egl_display_new (display, display,
      (GDestroyNotify) eglTerminate);

  /* initialize the EGL display connection */
  result = eglInitialize (display, NULL, NULL);
  assert (EGL_FALSE != result);

  /* get an appropriate EGL frame buffer configuration
   * this uses a BRCM extension that gets the closest match, rather
   * than standard which returns anything that matches. */
  result =
      eglSaneChooseConfigBRCM (display, attribute_list, &config, 1,
      &num_config);
  assert (EGL_FALSE != result);

  /* create an EGL rendering context */
  state->context =
      eglCreateContext (display, config, EGL_NO_CONTEXT, NULL);
  assert (state->context != EGL_NO_CONTEXT);

  /* Open display */
  state->dispman_display = vc_dispmanx_display_open (0 /* LCD */ );
  assert (state->dispman_display);

  /* Get display dimensions */
  success = vc_dispmanx_display_get_info(state->dispman_display, &mode_info);
  assert (success >= 0);
  state->screen_width = mode_info.width;
  state->screen_height = mode_info.height;

  /* create an EGL window surface */
  dst_rect.x = 0;
  dst_rect.y = 0;
  dst_rect.width = state->screen_width;
  dst_rect.height = state->screen_height;

  src_rect.x = 0;
  src_rect.y = 0;
  src_rect.width = state->screen_width << 16;
  src_rect.height = state->screen_height << 16;

  dispman_update = vc_dispmanx_update_start (0);

  state->dispman_element =
      vc_dispmanx_element_add (dispman_update, state->dispman_display,
      0 /*layer */ , &dst_rect, 0 /*src */ ,
      &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha */ , 0 /*clamp */ ,
      0 /*transform */ );

  nativewindow.element = state->dispman_element;
  nativewindow.width = state->screen_width;
  nativewindow.height = state->screen_height;
  vc_dispmanx_update_submit_sync (dispman_update);

  state->surface =
      eglCreateWindowSurface (display, config, &nativewindow, NULL);
  assert (state->surface != EGL_NO_SURFACE);

  /* connect the context to the surface */
  result =
      eglMakeCurrent (display, state->surface, state->surface,
      state->context);
  assert (EGL_FALSE != result);

  /* Set background color and clear buffers */
  glClearColor (0.15f, 0.25f, 0.35f, 1.0f);

  /* Enable back face culling. */
  glEnable (GL_CULL_FACE);

  glMatrixMode (GL_MODELVIEW);
}

/***********************************************************
 * Name: init_model_proj
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description: Sets the OpenGL|ES model to default values
 *
 * Returns: void
 *
 ***********************************************************/
static void
init_model_proj (AppState * state)
{
  float nearp = 1.0f;
  float farp = 500.0f;
  float hht;
  float hwd;

  glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

  glViewport (0, 0, (GLsizei) state->screen_width,
      (GLsizei) state->screen_height);

  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();

  hht = nearp * (float) tan (45.0 / 2.0 / 180.0 * M_PI);
  hwd = hht * (float) state->screen_width / (float) state->screen_height;

  glFrustumf (-hwd, hwd, -hht, hht, nearp, farp);

  glEnableClientState (GL_VERTEX_ARRAY);
  glVertexPointer (3, GL_BYTE, 0, quadx);

  reset_model (state);
}

/***********************************************************
 * Name: reset_model
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description: Resets the Model projection and rotation direction
 *
 * Returns: void
 *
 ***********************************************************/
static void
reset_model (AppState * state)
{
  /* reset model position */
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();
  glTranslatef (0.f, 0.f, -50.f);

  /* reset model rotation */
  state->rot_angle_x = 45.f;
  state->rot_angle_y = 30.f;
  state->rot_angle_z = 0.f;
  state->rot_angle_x_inc = 0.5f;
  state->rot_angle_y_inc = 0.5f;
  state->rot_angle_z_inc = 0.f;
  state->distance = 40.f;
}

/***********************************************************
 * Name: update_model
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description: Updates model projection to current position/rotation
 *
 * Returns: void
 *
 ***********************************************************/
static void
update_model (AppState * state)
{
  if (state->animate) {
    /* update position */
    state->rot_angle_x =
        inc_and_wrap_angle (state->rot_angle_x, state->rot_angle_x_inc);
    state->rot_angle_y =
        inc_and_wrap_angle (state->rot_angle_y, state->rot_angle_y_inc);
    state->rot_angle_z =
        inc_and_wrap_angle (state->rot_angle_z, state->rot_angle_z_inc);
    state->distance =
        inc_and_clip_distance (state->distance, state->distance_inc);
  }

  glLoadIdentity ();
  /* move camera back to see the cube */
  glTranslatef (0.f, 0.f, -state->distance);

  /* Rotate model to new position */
  glRotatef (state->rot_angle_x, 1.f, 0.f, 0.f);
  glRotatef (state->rot_angle_y, 0.f, 1.f, 0.f);
  glRotatef (state->rot_angle_z, 0.f, 0.f, 1.f);
}

/***********************************************************
 * Name: inc_and_wrap_angle
 *
 * Arguments:
 *       GLfloat angle     current angle
 *       GLfloat angle_inc angle increment
 *
 * Description:   Increments or decrements angle by angle_inc degrees
 *                Wraps to 0 at 360 deg.
 *
 * Returns: new value of angle
 *
 ***********************************************************/
static GLfloat
inc_and_wrap_angle (GLfloat angle, GLfloat angle_inc)
{
  angle += angle_inc;

  if (angle >= 360.0)
    angle -= 360.f;
  else if (angle <= 0)
    angle += 360.f;

  return angle;
}

/***********************************************************
 * Name: inc_and_clip_distance
 *
 * Arguments:
 *       GLfloat distance     current distance
 *       GLfloat distance_inc distance increment
 *
 * Description:   Increments or decrements distance by distance_inc units
 *                Clips to range
 *
 * Returns: new value of angle
 *
 ***********************************************************/
static GLfloat
inc_and_clip_distance (GLfloat distance, GLfloat distance_inc)
{
  distance += distance_inc;

  if (distance >= 120.0f)
    distance = 120.f;
  else if (distance <= 40.0f)
    distance = 40.0f;

  return distance;
}

/***********************************************************
 * Name: redraw_scene
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description:   Draws the model and calls eglSwapBuffers
 *                to render to screen
 *
 * Returns: void
 *
 ***********************************************************/
static void
redraw_scene (AppState * state)
{
  EGLDisplay display = egl_display_get (state->display);
  /* Start with a clear screen */
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  /* Need to rotate textures - do this by rotating each cube face */
  glRotatef (270.f, 0.f, 0.f, 1.f);     /* front face normal along z axis */

  /* draw first 4 vertices */
  glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);

  /* same pattern for other 5 faces - rotation chosen to make image orientation 'nice' */
  glRotatef (90.f, 0.f, 0.f, 1.f);      /* back face normal along z axis */
  glDrawArrays (GL_TRIANGLE_STRIP, 4, 4);

  glRotatef (90.f, 1.f, 0.f, 0.f);      /* left face normal along x axis */
  glDrawArrays (GL_TRIANGLE_STRIP, 8, 4);

  glRotatef (90.f, 1.f, 0.f, 0.f);      /* right face normal along x axis */
  glDrawArrays (GL_TRIANGLE_STRIP, 12, 4);

  glRotatef (270.f, 0.f, 1.f, 0.f);     /* top face normal along y axis */
  glDrawArrays (GL_TRIANGLE_STRIP, 16, 4);

  glRotatef (90.f, 0.f, 1.f, 0.f);      /* bottom face normal along y axis */
  glDrawArrays (GL_TRIANGLE_STRIP, 20, 4);

  eglSwapBuffers (display, state->surface);
}

/***********************************************************
 * Name: init_textures
 *
 * Arguments:
 *       AppState *state - holds OGLES model info
 *
 * Description:   Initialise OGL|ES texture surfaces to use image
 *                buffers
 *
 * Returns: void
 *
 ***********************************************************/
static void
init_textures (AppState * state)
{
  EGLDisplay display = egl_display_get (state->display);
  glGenTextures (1, &state->tex);

  glBindTexture (GL_TEXTURE_2D, state->tex);
  glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, IMAGE_SIZE_WIDTH, IMAGE_SIZE_HEIGHT,
      0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

#if 0
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
#else
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#endif

  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);


  /* Create EGL Image */
  state->ipc.eglImage = eglCreateImageKHR (display,
      state->context, EGL_GL_TEXTURE_2D_KHR, (EGLClientBuffer) state->tex, 0);

  if (state->ipc.eglImage == EGL_NO_IMAGE_KHR) {
    g_print ("eglCreateImageKHR failed.\n");
    exit (1);
  }

  /* setup overall texture environment */
  glTexCoordPointer (2, GL_FLOAT, 0, texCoords);
  glEnableClientState (GL_TEXTURE_COORD_ARRAY);

  glEnable (GL_TEXTURE_2D);

  /* Bind texture surface to current vertices */
  glBindTexture (GL_TEXTURE_2D, state->tex);
}

//------------------------------------------------------------------------------

static void
close_ogl (void)
{
  DISPMANX_UPDATE_HANDLE_T dispman_update;
  EGLDisplay display = egl_display_get (state->display);
  
  if (state->ipc.eglImage != 0) {
    if (!eglDestroyImageKHR (display, (EGLImageKHR) state->ipc.eglImage))
      g_print ("eglDestroyImageKHR failed.");
  }

  /* clear screen */
  glClear (GL_COLOR_BUFFER_BIT);
  eglSwapBuffers (display, state->surface);

  /* Release OpenGL resources */
  eglMakeCurrent (display, EGL_NO_SURFACE, EGL_NO_SURFACE,
      EGL_NO_CONTEXT);
  eglDestroySurface (display, state->surface);
  eglDestroyContext (display, state->context);
  egl_display_unref (state->display);

  dispman_update = vc_dispmanx_update_start (0);
  vc_dispmanx_element_remove (dispman_update, state->dispman_element);
  vc_dispmanx_update_submit_sync (dispman_update);
  vc_dispmanx_display_close (state->dispman_display);
}

//==============================================================================

static void
open_ogl (void)
{

  bcm_host_init ();

  /* Start OpenGLES */
  init_ogl (state);

  /* Setup the model world */
  init_model_proj (state);

  /* initialize the OGLES texture(s) */
  init_textures (state);
}

static gpointer
render_func (gpointer data)
{
  open_ogl ();
  state->running = TRUE;

  do {
    update_model (state);
    redraw_scene (state);

    g_usleep (0);
  } while (state->running == TRUE);

  close_ogl ();
  return NULL;
}

/* Process keyboard input */
static gboolean
handle_keyboard (GIOChannel * source, GIOCondition cond, AppState * state)
{
  gsize bytesread;
  gchar op;

  if (g_io_channel_read_chars (source, &op, 1, &bytesread,
          NULL) == G_IO_STATUS_NORMAL) {
    switch (op) {
      case 'a':
        if (state->animate) {
          state->animate = FALSE;
          g_print ("Animation disabled\n");
        } else {
          state->animate = TRUE;
          g_print ("Animation enabled\n");
        }
        break;
      case 'q':
        video_decode_stop ();
        g_main_loop_quit (state->main_loop);
        break;
      default:
        /* g_print ("%02x ", op); */
        break;
    }
  }
  return TRUE;
}

int
main ()
{
  GThread *rthread = NULL, *mthread = NULL;
  GIOChannel *io_stdin;
  struct termios cooked, raw;

  /* must initialise the threading system before using any other GLib funtion */
  if (!g_thread_supported ())
    g_thread_init (NULL);

  /* Clear application state */
  memset (state, 0, sizeof (*state));
  state->animate = TRUE;

  /* Create a GLib Main Loop and set it to run */
  state->main_loop = g_main_loop_new (NULL, FALSE);

  /* Get the state of the tty */
  tcgetattr (0, &cooked);
  /* Make a copy we can mess with */
  memcpy (&raw, &cooked, sizeof (struct termios));
  /* Turn off linebuffering, and special-character processing,
   * but not the SIGINT or SIGQUIT keys. */
  raw.c_lflag &= ~(ICANON | ECHO);
  /* Ship the raw control blts */
  tcsetattr (0, TCSANOW, &raw);
  /* Add a keyboard watch so we get notified of keystrokes */
  io_stdin = g_io_channel_unix_new (fileno (stdin));
  g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc) handle_keyboard, state);
  g_io_channel_unref (io_stdin);

  /* *INDENT-OFF* */
  g_print ("Available commands: \n"
      "  a - Toggle animation \n"
      "  q - Quit \n");
  /* *INDENT-ON* */

  if (!(rthread = g_thread_new ("render", (GThreadFunc) render_func, NULL))) {
    g_print ("Render thread creation failed\n");
    goto done;
  }

  g_usleep(50000);
  if (!(mthread = g_thread_new ("media", (GThreadFunc) video_decode_test, &state->ipc))) {
    g_print ("Media thread creation failed\n");
    goto done;
  }

  /* Start the mainloop */
  g_main_loop_run (state->main_loop);

done:

  /* Unref the mainloop */
  if (state->main_loop) {
    g_main_loop_unref (state->main_loop);
  }

  /* Stop media thread */
  if (mthread)
    g_thread_join (mthread);

  /* Stop rendering thread */
  state->running = FALSE;
  if (rthread)
    g_thread_join (rthread);

  tcsetattr (0, TCSANOW, &cooked);
  g_print ("test finished\n");
  return 0;
}