/examples/cookbook/openglapp.pl

http://github.com/PerlGameDev/SDL · Perl · 115 lines · 95 code · 20 blank · 0 comment · 14 complexity · 80d02e2538b383ba615041cd35b2a138 MD5 · raw file

  1. use strict;
  2. use warnings;
  3. use SDL;
  4. use SDLx::App;
  5. use SDL::Mouse;
  6. use SDL::Video;
  7. use SDL::Events;
  8. use SDL::Event;
  9. use OpenGL qw(:all);
  10. my ( $SDLAPP, $WIDTH, $HEIGHT, $SDLEVENT );
  11. $| = 1;
  12. $WIDTH = 1024;
  13. $HEIGHT = 768;
  14. $SDLAPP = SDLx::App->new(
  15. title => "Opengl App",
  16. width => $WIDTH,
  17. height => $HEIGHT,
  18. gl => 1
  19. );
  20. $SDLEVENT = SDL::Event->new;
  21. glEnable(GL_DEPTH_TEST);
  22. glMatrixMode(GL_PROJECTION);
  23. glLoadIdentity;
  24. gluPerspective( 60, $WIDTH / $HEIGHT, 1, 1000 );
  25. glTranslatef( 0, 0, -20 );
  26. while (1) {
  27. &handlepolls;
  28. glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
  29. glRotatef( .1, 1, 1, 1 );
  30. &drawscene;
  31. $SDLAPP->sync;
  32. }
  33. sub drawscene {
  34. my ( $color, $x, $y, $z );
  35. for ( -2 .. 2 ) {
  36. glPushMatrix;
  37. glTranslatef( $_ * 3, 0, 0 );
  38. glColor3d( 1, 0, 0 );
  39. &draw_cube;
  40. glPopMatrix;
  41. }
  42. return "";
  43. }
  44. sub draw_cube {
  45. my ( @indices, @vertices, $face, $vertex, $index, $coords );
  46. @indices = qw(4 5 6 7 1 2 6 5 0 1 5 4
  47. 0 3 2 1 0 4 7 3 2 3 7 6);
  48. @vertices = (
  49. [ -1, -1, -1 ],
  50. [ 1, -1, -1 ],
  51. [ 1, 1, -1 ],
  52. [ -1, 1, -1 ],
  53. [ -1, -1, 1 ],
  54. [ 1, -1, 1 ],
  55. [ 1, 1, 1 ],
  56. [ -1, 1, 1 ]
  57. );
  58. glBegin(GL_QUADS);
  59. foreach my $face ( 0 .. 5 ) {
  60. foreach my $vertex ( 0 .. 3 ) {
  61. $index = $indices[ 4 * $face + $vertex ];
  62. $coords = $vertices[$index];
  63. glVertex3d(@$coords);
  64. }
  65. }
  66. glEnd;
  67. return "";
  68. }
  69. sub handlepolls {
  70. my ( $type, $key );
  71. SDL::Events::pump_events();
  72. while ( SDL::Events::poll_event($SDLEVENT) ) {
  73. $type = $SDLEVENT->type();
  74. $key = ( $type == 2 or $type == 3 ) ? $SDLEVENT->key_sym : "";
  75. if ( $type == 4 ) {
  76. printf(
  77. "You moved the mouse! x=%s y=%s xrel=%s yrel=%s\n",
  78. $SDLEVENT->motion_x, $SDLEVENT->motion_y,
  79. $SDLEVENT->motion_xrel, $SDLEVENT->motion_yrel
  80. );
  81. } elsif ( $type == 2 ) {
  82. print "You are pressing $key\n";
  83. } elsif ( $type == 3 ) {
  84. print "You released $key\n";
  85. } elsif ( $type == 12 ) {
  86. exit;
  87. } else {
  88. print "TYPE $type UNKNOWN!\n";
  89. }
  90. if ( $type == 2 ) {
  91. if ( $key eq "q" or $key eq "escape" ) {exit}
  92. }
  93. }
  94. return "";
  95. }