blib/lib/PDL/Graphics2D.pm untested

filter: Statementstmt 0.0% 0 / 402 Branchbran 0.0% 0 / 202 Conditioncond 0.0% 0 / 85 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 723 CC 102 SCAR 55.3
CC
102
Cov
0%
imag2d
600.0
key_ops
420.0
display_image
272.0
CRAP 251.5
1 package PDL::Graphics2D;
2  
3 use Exporter 'import'; # gives you Exporter's import() method directly
4 @EXPORT = qw(imag2d imag2d_update twiddle); # symbols to export on request
5 @EXPORT_OK = qw(imag2d imag2d_update twiddle); # symbols to export on request
6  
7 =head1 NAME
8  
9 PDL::Graphics2D - An object oriented interface to PDL graphics
10  
11 =head1 SYNOPSIS
12  
13 use PDL::Graphics2D;
14 $win = PDL::Graphics2D->new(<Interface>, <Options>);
15  
16 $w = imag2d( $image, 'Title Here', ... );
17  
18 =head1 DESCRIPTION
19  
20 This is an umbrella class allowing for a simple interface to all plotting
21 routines in PDL. On its own it does not do any work it merely passes
22 information to the appropriate class. Ideally this should probably offer
23 a uniform interface to a variety of packages.
24  
25 This requires a lot more work before it is useful I feel, but it can be
26 used already.
27  
28 =head1 CONSTRUCTORS
29  
30 =head2 new
31  
32 =for ref
33  
34 Create a 2-D graphics object with the requested interface type
35  
36 =cut
37  
38  
39 {
40 my %lookup=(
41 'PGPLOT' => 'PDL::Graphics::PGPLOT::Window'
42 );
43 sub new {
44  
45 my $type=shift;
46 my $interface=shift;
47  
48 #
49 # Translate the interface name to the appropriate class name.
50 #
51 $interface=uc($interface);
52 die "Interface $interface is not known!\n" if !exists($lookup{$interface});
53 my $class = $lookup{$interface};
54 eval "require $class;";
55 return $class->new(@_);
56 }
57 }
58  
59 use strict;
60  
61 my $debug = 0;
62  
63 use PDL::Lite;
64 use PDL::NiceSlice;
65  
66 #------------------------------------------------------------------------
67 # PDL constants used by imag2d
68 #------------------------------------------------------------------------
69 #
70 # PDL_B
71 # PDL_D
72 # PDL_F
73 # PDL_L
74 # PDL_S
75 # PDL_US
76 #
77 #------------------------------------------------------------------------
78  
79 #------------------------------------------------------------------------
80 # PDL methods used by imag2d
81 #------------------------------------------------------------------------
82 #
83 # .=
84 # dim
85 # float
86 # get_dataref
87 # ndims
88 # sever
89 # type->symbol
90 #
91 #------------------------------------------------------------------------
92  
93 use OpenGL qw( :all );
94  
95 #------------------------------------------------------------------------
96 # opengl/glut constants used by imag2d
97 #------------------------------------------------------------------------
98 #
99 # GLUT_ACTION_CONTINUE_EXECUTION
100 # GLUT_ACTION_ON_WINDOW_CLOSE
101 # GLUT_DOUBLE
102 # GLUT_RGBA
103 # GLUT_WINDOW_HEIGHT
104 # GLUT_WINDOW_WIDTH
105 #
106 # GL_COLOR_BUFFER_BIT
107 # GL_FLOAT
108 # GL_INT
109 # GL_LUMINANCE
110 # GL_LUMINANCE_ALPHA
111 # GL_MODELVIEW
112 # GL_PROJECTION
113 # GL_RGB
114 # GL_RGBA
115 # GL_SHORT
116 # GL_UNPACK_ALIGNMENT
117 # GL_UNSIGNED_BYTE
118 # GL_UNSIGNED_INT_8_8_8_8
119 # GL_UNSIGNED_SHORT
120 #
121 #------------------------------------------------------------------------
122  
123  
124 #------------------------------------------------------------------------
125 # opengl/glu/glut routines used by imag2d
126 #------------------------------------------------------------------------
127 #
128 # OpenGL::done_glutInit
129 #
130 # glutAddMenuEntry
131 # glutAttachMenu
132 # glutCreateMenu
133 # glutCreateWindow
134 # glutDestroyWindow
135 # glutDisplayFunc
136 # glutGet
137 # glutGetWindow
138 # glutInit
139 # glutInitDisplayMode
140 # glutInitWindowPosition
141 # glutInitWindowSize
142 # glutKeyboardFunc
143 # glutLeaveMainLoop
144 # glutMouseFunc
145 # glutPostRedisplay
146 # glutReshapeFunc
147 # glutReshapeWindow
148 # glutSetOption
149 # glutSwapBuffers
150 #
151 # glClear
152 # glClearColor
153 # glDrawPixels_s
154 # glFlush
155 # glLoadIdentity
156 # glMatrixMode
157 # glPixelStorei
158 # glPixelZoom
159 # glRasterPos2i
160 # glViewport
161 #
162 # gluOrtho2D
163 #
164 #------------------------------------------------------------------------
165  
166  
167 our $draw_overlay;
168  
169 my $finished_glutInit = 0;
170 my $cur_fig_num = 0;
171 my $imag2d_keep_twiddling;
172 my $imag2d_is_twiddling;
173  
174 my $show_overlay = 1;
175 our $is_paused = 0;
176 our $do_step = 0;
177 our $step_count = 1;
178 our $go_forward = 1;
179 our $go_backward = 0;
180  
181 our @imag2d_list = ();
182  
183 #------------------------------------------------------------------------
184 # glutMouseFunc callback
185 #------------------------------------------------------------------------
186 sub mouse_click {
187 my ($button, $state, $x, $y) = @_;
188  
189 my $window_id = glutGetWindow();
190 my $width = glutGet(GLUT_WINDOW_WIDTH);
191 my $height = glutGet(GLUT_WINDOW_HEIGHT);
192 my $img;
193  
194 # search for image corresponding to window
195 foreach my $entry ( @imag2d_list ) {
196 if ( $entry->{window_id} == $window_id ) {
197 $img = $entry->{img}; # 2D piddle for now
198 last;
199 }
200 }
201  
202 die "mouse_click: callback could not find image window\n" unless defined $img;
203  
204 # calculate zoom/aspect ratio factors
205 my $glds = 0; $glds = 1 if $img->dim(0) < 5; # hack, need verify consistency
206  
207 my $zoom_x = $width / $img->dim($glds+0);
208 my $zoom_y = $height / $img->dim($glds+1);
209 my $zoom = ($zoom_x < $zoom_y) ? $zoom_x : $zoom_y;
210  
211 # calculate the offset to the image use for centering
212 my ($hshift, $vshift) = (0,0);
213  
214 if ( $zoom == $zoom_x ) {
215 # shift down
216 $vshift = ($height - $zoom * $img->dim($glds+1)) / 2.0;
217 } else {
218 # shift right
219 $hshift = ($width - $zoom * $img->dim($glds+0)) / 2.0;
220 }
221  
222 my ($im_x, $im_y);
223 $im_x = sprintf "%.1f", ($x - $hshift) / $zoom;
224 $im_y = sprintf "%.1f", ($y - $vshift) / $zoom;
225  
226 if ( $state
227 and (-1 < $im_x)
228 and (-1 < $im_y)
229 and ($im_x < $img->dim($glds+0)+1)
230 and ($im_y < $img->dim($glds+1)+1) ) {
231 printf STDERR "b_%01d: pixel=(%d,%d), im pt=(%.1f,%.1f),", $button, $x, $y, $im_x, $im_y;
232 printf STDERR " im val=%s, glds=$glds, winID=$window_id\n", $glds ? $img->(:,(int($im_x)),(int($im_y))) : $img->((int($im_x)),(int($im_y)));
233 }
234 };
235  
236 #------------------------------------------------------------------------
237 # glutReshapeFunc callback
238 #------------------------------------------------------------------------
239 sub resize_window {
240 my ($width, $height) = @_;
241  
242 print STDERR "resize_window: call with new dims ($width, $height)\n" if $debug;
243  
244 my $window_id = glutGetWindow();
245 my $img;
246  
247 return unless scalar(@imag2d_list);
248  
249 # search for image corresponding to window
250 foreach my $entry ( @imag2d_list ) {
251 if ( $entry->{window_id} == $window_id ) {
252 $img = $entry->{img}; # 2D piddle for now
253 last;
254 }
255 }
256  
257 die "resize_window: callback could not find image window\n" unless defined $img;
258  
259 # calculate zoom/aspect ratio factors
260 my $glds = 0; $glds = 1 if $img->dim(0) < 5; # hack, need verify consistency
261  
262 my $zoom_x = $width / $img->dim($glds+0);
263 my $zoom_y = $height / $img->dim($glds+1);
264 my $zoom = ($zoom_x < $zoom_y) ? $zoom_x : $zoom_y;
265  
266 glViewport( 0, 0, $width, $height );
267  
268 # set coordinate frame for graphics in window
269 glMatrixMode( GL_PROJECTION );
270 glLoadIdentity();
271  
272 gluOrtho2D( 0, $width, $height, 0 );
273  
274 glMatrixMode( GL_MODELVIEW );
275 glLoadIdentity();
276  
277 # set zoom factors for image display
278 glPixelZoom( $zoom, -$zoom );
279  
280 ## glutReshapeWindow($zoom*$img->dim($glds+0), $zoom*$img->dim($glds+1));
281  
282 # offset the image in the window to keep centered
283 my ($hshift, $vshift) = (0,0);
284  
285 if ( $zoom == $zoom_x ) {
286 # shift down
287 $vshift = ($height - $zoom * $img->dim($glds+1)) / 2.0;
288 } else {
289 # shift right
290 $hshift = ($width - $zoom * $img->dim($glds+0)) / 2.0;
291 }
292  
293 glRasterPos2i( int($hshift), int($vshift) );
294  
295 my ($do_reshape) = 0;
296 my ($new_width, $new_height) = ($zoom*$img->dim($glds+0), $zoom*$img->dim($glds+1));
297  
298 # handle integer rounding problems in resize
299 if (abs($new_width - $width ) <= 2) {
300 $new_width = $width;
301 } else {
302 $do_reshape++;
303 }
304 if (abs($new_height - $height ) <= 2) {
305 $new_height = $height;
306 } else {
307 $do_reshape++;
308 }
309  
310 glutReshapeWindow($new_width, $new_height) if $do_reshape;
311 };
312  
313 #------------------------------------------------------------------------
314 # glutDisplayFunc callback
315 #------------------------------------------------------------------------
316 sub display_image {
317 my $window_id = glutGetWindow();
318 my $img;
319 my ($gldrawformat, $gldrawtype, $glds);
320  
321 return unless scalar(@imag2d_list);
322  
323 # search for image corresponding to window
324 foreach my $entry ( @imag2d_list ) {
325 if ( $entry->{window_id} == $window_id ) {
326 $img = $entry->{img}; # 2D piddle for now
327 last;
328 }
329 }
330  
331 die "display_window: callback could not find image window\n" unless defined $img;
332  
333 # determine display pixel format to use
334 if ($img->ndims > 2 && $img->dim(0) == 4) {
335 $gldrawformat = GL_RGBA;
336 $glds = 1;
337 } elsif ($img->ndims > 2 && $img->dim(0) == 3) {
338 $gldrawformat = GL_RGB;
339 $glds = 1;
340 } elsif ($img->ndims > 2 && $img->dim(0) == 2) {
341 $gldrawformat = GL_LUMINANCE_ALPHA;
342 $glds = 1;
343 } elsif ($img->ndims > 2 && $img->dim(0) == 1) {
344 $gldrawformat = GL_LUMINANCE;
345 $glds = 1;
346 } else {
347 $gldrawformat = GL_LUMINANCE;
348 $glds = 0;
349 };
350  
351 # convert to float if double for display
352 if ($img->type->symbol eq 'PDL_D') { # clean up code
353 $img = $img->float;
354 }
355  
356 # determine display pixel type to use
357 if ($img->type->symbol eq 'PDL_F') {
358 $gldrawtype = GL_FLOAT;
359 } elsif ($img->type->symbol eq 'PDL_B') {
360 $gldrawtype = GL_UNSIGNED_BYTE;
361 } elsif ($img->type->symbol eq 'PDL_S') {
362 $gldrawtype = GL_SHORT;
363 } elsif ($img->type->symbol eq 'PDL_US') {
364 $gldrawtype = GL_UNSIGNED_SHORT;
365 } elsif ($img->type->symbol eq 'PDL_L') {
366 $gldrawtype = ( $gldrawformat == GL_RGBA ) ? GL_UNSIGNED_INT_8_8_8_8 : GL_INT;
367 } else {
368 die "display_image: unsupported data type '", $img->type->symbol, "' for image display\n";
369 }
370  
371 my ($sizeX, $sizeY) = ($img->dim($glds+0), $img->dim($glds+1));
372 # print STDERR "... calculated image size is ($sizeX, $sizeY)\n";
373  
374 # display image
375 glClear(GL_COLOR_BUFFER_BIT);
376 # glRasterPos2i( 0, 0 );
377 glDrawPixels_s( $sizeX, $sizeY, $gldrawformat, $gldrawtype, $img->get_dataref );
378  
379 &{$draw_overlay}($img, $sizeX, $sizeY) if $show_overlay and defined($draw_overlay);
380  
381 #draw_hough_lines($img, $sizeX, $sizeY);
382  
383 glutSwapBuffers();
384 glFlush();
385 }
386  
387 my $RELEASE=99;
388  
389 #------------------------------------------------------------------------
390 # glutCreateMenu callback
391 #------------------------------------------------------------------------
392 sub ModeMenu {
393 my $entry = shift;
394 my $img;
395  
396 if ($entry == $RELEASE) {
397 my ($window_id) = glutGetWindow();
398  
399 # search for image corresponding to window
400 foreach my $listentry ( @imag2d_list ) {
401 if ( $listentry->{window_id} == $window_id ) {
402 $img = $listentry->{img}; # 2D piddle for now
403 last;
404 }
405 }
406  
407 die "ModeMenu: callback could not find image window\n" unless defined $img;
408  
409 glutLeaveMainLoop();
410 # glutDestroyWindow($window_id);
411  
412 } else {
413 die "ModeMenu: illegal menu entry '$entry'\n";
414 }
415 }
416  
417 #------------------------------------------------------------------------
418 # glutKeyboardFunc callback
419 #------------------------------------------------------------------------
420 sub key_ops {
421 my ($key, $x, $y) = @_;
422 my $win_id = glutGetWindow();
423  
424 # handle keypress events (defaults first)
425 # print STDERR "Got keypress for keypress=$key\n";
426  
427 # stop twiddling
428 if ($key == ord('Q') or $key == ord('q')) {
429 $imag2d_is_twiddling = 0;
430 warn "Stop twiddling command, key '" . chr($key) . "', detected.\n";
431 return;
432 }
433  
434 # exit program
435 if ($key == 27 or $key == 3) { # ESC or Ctrl-C
436 warn "Exit program command, key '" . (($key == 27) ? 'ESC' : 'Ctrl-C') . "', detected.\n";
437 if (defined $PERLDL::TERM) { # don't exit if in the perldl or pdl2 shell
438 $imag2d_is_twiddling = 0;
439 warn "PDL shell in use, stop twiddling instead of exit...\n";
440 return;
441 } else {
442 exit;
443 }
444 }
445  
446 # toggle overlay
447 if ($key == ord('O') or $key == ord('o')) {
448 $show_overlay = (($show_overlay) ? 0 : 1);
449 warn "Toggle overlay command, key '" . chr($key) . "', detected.\n";
450 return;
451 }
452  
453 # lock windows sizes together
454 if ($key == ord('L') or $key == ord('l')) {
455 ## $lock_sizes = (($lock_sizes) ? 0 : 1);
456 ## warn "Setting \$lock_sizes to $lock_sizes, (window=$win_id)\n";
457 warn "Lock window sizes command, key '" . chr($key) . "', not implemented.\n";
458 return;
459 }
460  
461 # toggle image histogram equalization
462 if ($key == ord('H') or $key == ord('h')) {
463 ## $hist_equalize = (($hist_equalize) ? 0 : 1);
464 ## warn "Setting \$hist_equalize to $hist_equalize\n";
465 warn "Toggle image histogram equalization command, key '" . chr($key) . "', not implemented.\n";
466 return;
467 }
468  
469 # resize current window (last clicked?) to 1:1
470 if ($key == ord('1')) {
471 ## resize_window(-1,-1); # Special (w,h) args mean set zoom to 1
472 ## glutPostRedisplay();
473 warn "Resize current window to 1:1 scale command, key '" . chr($key) . "', not implemented.\n";
474 return;
475 }
476
477 # resize other image windows to this one
478 if ($key == ord('=')) {
479 ## warn "Resize other images to this one not yet implemented, (window=$win_id)\n";
480 warn "Resize other windows to this one command, key '" . chr($key) . "', not implemented.\n";
481 return;
482 }
483  
484 # pause/run with space bar
485 if ($key == 32) { # SPACE
486 if ($is_paused) {
487 $is_paused = 0;
488 } else {
489 $is_paused = 1;
490 $step_count = 1;
491 $do_step = 1;
492 }
493 # warn "Pause/Run command, key 'SPACE', detected\n";
494 return;
495 }
496  
497 # toggle verbose output
498 if ($key == ord('v') or $key == ord('V')) {
499 ## $be_verbose = (($be_verbose) ? 0 : 1);
500 warn "Toggle verbose output command, key '" . chr($key) . "', not implemented.\n";
501 return;
502 }
503  
504 # change direction or step in direction
505 if ($key == 46 or $key == 62) { # . or >
506 $go_forward = 1;
507 $go_backward = 0;
508 if ($is_paused) {
509 $do_step = 1;
510 $step_count = 1;
511 } else {
512 $step_count++;
513 $step_count = 1 if $step_count == 0;
514 }
515 # warn "Change Direction/Step forward command, key '" . (($key == 46) ? '.' : '>') . "', detected.\n";
516 return;
517 };
518  
519 if ($key == 44 or $key == 60) { ; # , or <
520 $go_forward = 0;
521 $go_backward = 1;
522 if ($is_paused) {
523 $do_step = 1;
524 $step_count = -1;
525 } else {
526 $step_count--;
527 $step_count = -1 if $step_count == 0;
528 }
529  
530 # warn "Change Direction/Step backward command, key '" . (($key == 44) ? ',' : '<') . "', detected.\n";
531 return;
532 }
533  
534 warn "No handler for key " . chr($key) . ", (window=$win_id)\n";
535 }
536  
537 #------------------------------------------------------------------------
538 # Create a new OpenGL context window for image display
539 #------------------------------------------------------------------------
540 sub display_new_window {
541 my ($height, $width, $zoom, $name, $off_r, $off_c, $window_id) = @_;
542  
543 my ($window_width, $window_height);
544 my ($zoom_x, $zoom_y);
545  
546 if ( $width <= 0 || $height <= 0 || $zoom == 0.0 )
547 {
548 die "display_new_window: invalid arguments!\n";
549 }
550  
551 $window_width = int($zoom*$width + 0.5);
552 $window_height = int($zoom*$height + 0.5);
553  
554 # compute zoom factors to make graphics overlay the image precisely
555 $zoom_x = $window_width/$width;
556 $zoom_y = $window_height/$height;
557  
558 # create display window
559 if (! $finished_glutInit ) {
560 glutInit() unless OpenGL::done_glutInit();
561 glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE);
562 glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION) if OpenGL::_have_freeglut();
563 $finished_glutInit = 1;
564 }
565 glutInitWindowSize( $window_width, $window_height );
566 glutInitWindowPosition( $off_r, $off_c );
567 $window_id = glutCreateWindow( $name );
568  
569 # set some standard defaults
570 glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
571 glClearColor( 0.0, 0.0, 0.0, 0.0 );
572 glViewport( 0, 0, $window_width, $window_height );
573  
574 # set coordinate frame for graphics in window
575 glMatrixMode( GL_PROJECTION );
576 glLoadIdentity();
577  
578 gluOrtho2D( 0, $width, $height, 0 );
579  
580 glMatrixMode( GL_MODELVIEW );
581 glLoadIdentity();
582  
583 # set zoom factors for image display
584 glPixelZoom( $zoom_x, -$zoom_y );
585  
586 # set origin for drawing images as the top-left corner of the window
587 glRasterPos2i( 0, 0 );
588  
589 # success
590 return $window_id;
591 };
592  
593 #------------------------------------------------------------------------
594 # Display piddle as 2-D image in window using OpenGL
595 #------------------------------------------------------------------------
596  
597 =head1 FUNCTIONS
598  
599 =head2 imag2d
600  
601 =for ref
602  
603 Display a 2-D image in a figure window
604  
605 imag2d() creates a plain FreeGLUT OpenGL window and displays
606 the input image with 1:1 aspect ratio for pixels. The window
607 resize is constrained to the actual ratio of the image
608 dimensions. The initial display size is currently a 200x200
609 window to prevent things from being too small by default.
610  
611 The image to display can have dimensions ($c,$M,$N) where for
612 $c==4 the display is in GL_RGBA, for $c==3 the display is GL_RGB,
613 for $c==2 the display is GL_LUMINANCE_ALPHA, and for $c==1 or for
614 for dimensions ($M,$N) then the display is GL_LUMINANCE.
615  
616 This routine does not yet thread but multiple images may be
617 viewed at the same time in separate windows by multiple
618 calls to imag2d(). TriD graphics visualization windows and the
619 imag2d() windows may be created and used independently.
620  
621 NOTE: If you are twiddling a TriD window, the imag2d()
622 windows are active as well. If you call twiddle()
623 the sub, only the imag2d() windows will update correctly.
624  
625 =for usage
626  
627 $window_id = imag2d($image, $name, $zoom, $x_off, $y_off);
628
629 creates a new image figure window from the input piddle
630 with the given title, zoom factor, and position (if possible)
631
632 $window_id - may be used to refer to the figure window
633
634 $image - 2D image piddle with at least 2 or 3 dimensions
635 e.g. [M,N], [1,M,N], [2,M,N], [3,M,N], [4,M,N]
636
637 $name - the name to use for the figure window (optional)
638
639 $zoom - desired (float) pixel zoom factor (optional)
640
641 ($x_off, $y_off) - desired window pixel position (optional)
642 with (0,0) as the top left pixel of the
643 display
644  
645 =for example
646  
647 use PDL::Graphics2D; # imports imag2d() and twiddle()
648  
649 $a = sequence(64,48,3); # make test RGB image
650 $a = $a->mv(2,0); # color must be dim(0) with size [0..4]
651 $a /= $a->max; # pixel values in [0.0,1.0]
652 $a = sin(10*$a);
653 $w1 = imag2d($a); # with parens...
654 $w2 = imag2d $a->sqrt; # or without
655 $w3 = imag2d $a**2;
656  
657  
658 =head2 imag2d_update
659  
660 =for ref
661  
662 Update an existing imag2d window with new piddle data
663  
664 =for usage
665  
666 $image = random(3,64,48)/2 + 0.25; # random pixel image
667 $win = imag2d($image); # create original image display
668  
669 imag2d_update($win, $image->sequence/$image->nelem); # update data
670  
671 C<imag2d_update> allows one to update an C<imag2d> display window
672 by replacing the associated image data with new contents. The
673 new image data must be the same type and shape as the previous.
674  
675 Eventually, we would like to implement this via some sort of
676 dataflow that would be transparent to the user.
677  
678 =cut
679  
680 =head2 twiddle
681  
682 =for ref
683  
684 Enable GUI interaction with a FreeGLUT display window. With an argument, it sets
685 the default value for the auto-twiddling state. C< 0 > will disable the automatic
686 twiddling and C< 1 >, or true, will enable twiddling.
687  
688 =for usage
689  
690 twiddle(); # same as twiddle(undef)
691  
692 Runs the FreeGLUT event loop so window GUI operations
693 such as resize, expose, mouse click,.. work
694  
695 twiddle(0); # disables twiddle looping for next twiddle() call
696 twiddle(1); # re-enables default twiddle looping for next twiddle() call
697
698 =cut
699  
700  
701 sub imag2d {
702 my ($img, $name, $zoom, $off_r, $off_c) = (undef,"Figure $cur_fig_num", undef, 0, 0);
703  
704 # need to add error checking here
705 $img = (shift)->copy;
706 $name = shift if scalar(@_);
707 $zoom = shift if scalar(@_);
708 $off_r = shift if scalar(@_);
709 $off_c = shift if scalar(@_);
710  
711 my $window_id;
712 my ($gldrawformat, $gldrawtype, $glds);
713  
714 # determine display pixel format and type to use
715 if ($img->ndims > 2 && $img->dim(0) == 4) {
716 $gldrawformat = GL_RGBA;
717 $glds = 1;
718 } elsif ($img->ndims > 2 && $img->dim(0) == 3) {
719 $gldrawformat = GL_RGB;
720 $glds = 1;
721 } elsif ($img->ndims > 2 && $img->dim(0) == 2) {
722 $gldrawformat = GL_LUMINANCE_ALPHA;
723 $glds = 1;
724 } elsif ($img->ndims > 2 && $img->dim(0) == 1) {
725 $gldrawformat = GL_LUMINANCE;
726 $glds = 1;
727 } else {
728 $gldrawformat = GL_LUMINANCE;
729 $glds = 0;
730 };
731  
732 # convert to float if double for display
733 if ($img->type->symbol eq 'PDL_D') { # clean up code
734 $img = $img->float;
735 }
736  
737 # determine display pixel type to use
738 if ($img->type->symbol eq 'PDL_F') {
739 $gldrawtype = GL_FLOAT;
740 } elsif ($img->type->symbol eq 'PDL_B') {
741 $gldrawtype = GL_UNSIGNED_BYTE;
742 } elsif ($img->type->symbol eq 'PDL_S') {
743 $gldrawtype = GL_SHORT;
744 } elsif ($img->type->symbol eq 'PDL_US') {
745 $gldrawtype = GL_UNSIGNED_SHORT;
746 } elsif ($img->type->symbol eq 'PDL_L') {
747 $gldrawtype = ( $gldrawformat == GL_RGBA ) ? GL_UNSIGNED_INT_8_8_8_8 : GL_INT;
748 } else {
749 die "display_image: unsupported data type '", $img->type->symbol, "' for image display\n";
750 }
751  
752 # create display window
753 my ($im_height, $im_width);
754 $im_height = $img->dim($glds+1);
755 $im_width = $img->dim($glds+0);
756 if ( !defined($zoom) and ( $im_width < 200 or $im_height < 200 ) ) {
757 # adjust zoom to make initial window bigger than 200px
758 my $mindim = ($im_width < $im_height) ? $im_width : $im_height;
759 my $zoomest = int( 200 / $mindim );
760 $zoomest += 1 unless $zoomest == 200/$mindim;
761 print STDERR "imag2d: estimated zoom factor is $zoomest\n" if $debug;
762 $zoom = $zoomest;
763 }
764 $zoom = defined($zoom) ? $zoom : 1.0;
765  
766 print STDERR "imag2d: calling display_new_window( "
767 . $img->dim($glds+1) . ", "
768 . $img->dim($glds+0) . ", $zoom, $name, $off_r, $off_c )" if $debug;
769  
770 if ( ! defined( $window_id = display_new_window( $img->dim($glds+1), $img->dim($glds+0), $zoom, $name, $off_r, $off_c ) ) ) {
771 print STDERR "imag2d: failure\n";
772 return;
773 }
774  
775 # add GLUT window id to title
776 glutSetWindowTitle($name . ": WinID $window_id");
777 $cur_fig_num++;
778  
779 # set callback function for image display
780 glutDisplayFunc ( \&display_image );
781  
782 # set callback function for keypress events
783 glutKeyboardFunc ( \&key_ops );
784  
785 # set callback for mouse clicks
786 glutMouseFunc( \&mouse_click );
787  
788 # set callback for image window resize
789 glutReshapeFunc( \&resize_window );
790  
791 glutCreateMenu( \&ModeMenu );
792 glutAddMenuEntry( "End MainLoop", $RELEASE );
793 glutAttachMenu(GLUT_RIGHT_BUTTON);
794  
795 # add image and window to list
796 push @imag2d_list, { window_id => $window_id, img => $img };
797  
798 # set callback for image window close
799 glutCloseFunc( \&close_imag2d_window );
800  
801 # success
802 glRasterPos2i( 0, 0 );
803 glDrawPixels_s( $img->dim($glds+0), $img->dim($glds+1), $gldrawformat, $gldrawtype, $img->get_dataref );
804 glFlush();
805  
806 # we don't twiddle if in PDL shell and glutRunning is on
807 {
808 no warnings 'once';
809 twiddle() unless defined $PERLDL::TERM and ref $Term::ReadLine::toloop;
810 }
811  
812 return $window_id;
813 }
814  
815 #------------------------------------------------------------------------
816 # Update imag2d() window image data
817 #------------------------------------------------------------------------
818 sub imag2d_update {
819 my ($win_id, $image) = @_;
820 my $img;
821  
822 return unless scalar(@imag2d_list);
823  
824 # search for image corresponding to window
825 foreach my $entry ( @imag2d_list ) {
826 if ( $entry->{window_id} == $win_id ) {
827 $img = $entry->{img}; # 2D piddle for now
828 last;
829 }
830 }
831  
832 die "imag2d_update: callback could not find image window\n" unless defined $img;
833  
834 # update display window
835 # TODO: do we need to save and restore the current window?
836 # For now: calling imag2d_update makes that window current
837 glutSetWindow($win_id);
838  
839 $img .= $image->sever;
840 glutPostRedisplay();
841  
842 # update display but don't force twiddle()
843 glutMainLoopEvent();
844  
845 return $win_id;
846 }
847  
848 #------------------------------------------------------------------------
849 # Close a specific imag2d window
850 #------------------------------------------------------------------------
851 sub close_imag2d_window {
852  
853 my $win_id = glutGetWindow();
854  
855 if ( ! scalar(@imag2d_list) ) {
856 $imag2d_is_twiddling = 0;
857 return;
858 }
859  
860 # search for image corresponding to window
861 my ($entry, $found_it);
862 foreach $entry ( @imag2d_list ) {
863 if ($entry->{window_id} == $win_id) {
864 $found_it = 1;
865 last;
866 }
867 }
868  
869 print STDERR "close_imag2d_window: started with " . scalar(@imag2d_list) . " windows.\n" if $debug;
870 if ($found_it) {
871 @imag2d_list = grep { $_->{window_id} != $win_id } @imag2d_list;
872 } else {
873 warn "close_imag2d_window: could not find open window\n";
874 }
875 print STDERR "close_imag2d_window: finished with " . scalar(@imag2d_list) . " windows.\n" if $debug;
876 }
877  
878 #------------------------------------------------------------------------
879 # Close all imag2d windows
880 #------------------------------------------------------------------------
881 sub close_imag2d {
882  
883 return unless scalar(@imag2d_list);
884  
885 # process all image windows
886 foreach my $entry ( @imag2d_list ) {
887 glutDestroyWindow($entry->{window_id});
888 }
889  
890 @imag2d_list = ();
891 }
892  
893 #------------------------------------------------------------------------
894 # Simple twiddle for perldl (use [qQ] to exit)
895 #------------------------------------------------------------------------
896 sub twiddle {
897 my ($keeptwiddling) = @_;
898  
899 if (defined $keeptwiddling) {
900 $imag2d_keep_twiddling = $keeptwiddling;
901 return;
902 }
903  
904 $imag2d_is_twiddling = (defined $imag2d_keep_twiddling) ? $imag2d_keep_twiddling : 1;
905  
906 if ( $imag2d_is_twiddling ) {
907 print STDERR "Type Q or q to stop twiddling...\n";
908 while ($imag2d_is_twiddling && scalar(@imag2d_list)) {
909 glutMainLoopEvent();
910 }
911 print STDERR "Stopped twiddle-ing!\n";
912 }
913 glutMainLoopEvent();
914 }
915  
916 #------------------------------------------------------------------------
917 # Threaded image display as tiles (code from PDL::Graphics::TriD::Image)
918 #------------------------------------------------------------------------
919  
920 # N-D piddle -> 2-D
921 sub flatten {
922 my ($this,$bin_align) = @_;
923  
924 my @dims = $this->dims;
925 my $imdim0 = shift @dims; # get rid of the '3'
926  
927 my $xd = $dims[0]; my $yd = $dims[1];
928 my $xdr = $xd; my $ydr = $yd;
929  
930 # Calculate the whole width of the image.
931 my $ind = 0;
932 my $xm = 0; my $ym = 0;
933 for (@dims[2..$#dims]) {
934 if ($ind % 2 == 0) {
935 $xd ++; # = $dims[$ind-2];
936 $xd *= $_;
937 $xdr ++;
938 $xdr *= $_;
939 $xm++;
940 } else {
941 $yd ++; # = $dims[$ind-2];
942 $yd *= $_;
943 $ydr ++;
944 $ydr *= $_;
945 $ym++;
946 }
947 $ind++;
948 }
949 $xd -= $xm; $yd -= $ym;
950  
951 # R because the final texture must be 2**x-aligned ;(
952 my ($txd ,$tyd, $xxd, $yyd);
953 if ($bin_align) {
954 for ($txd = 0; $txd < 12 and 2**$txd < $xdr; $txd++) {};
955 for ($tyd = 0; $tyd < 12 and 2**$tyd < $ydr; $tyd++) {};
956 $txd = 2**$txd; $tyd = 2**$tyd;
957 $xxd = ($xdr > $txd ? $xdr : $txd);
958 $yyd = ($ydr > $tyd ? $ydr : $tyd);
959 } else {
960 $xxd=$txd=$xdr; $yyd=$tyd=$ydr;
961 }
962  
963 my $p = PDL->zeroes(PDL::float(),$imdim0,$xxd,$yyd);
964  
965 # # object is PDL not PDL::Graphics::TriD::Image
966 # if(defined $this->{Opts}{Bg}) {
967 # $p .= $this->{Opts}{Bg};
968 # }
969  
970 # print "MKFOOP\n";
971 my $foop = $p->slice(":,0:".($xdr-1).",0:".($ydr-1));
972  
973 $ind = $#dims;
974 my $firstx = 1;
975 my $firsty = 1;
976 my $spi;
977 for (@dims[reverse(2..$#dims)]) {
978 $foop->make_physdims();
979 # print "FOOP: \n"; $foop->dump;
980 if ($ind % 2 == 0) {
981 $spi = $foop->getdim(1)/$_;
982 $foop = $foop->splitdim(1,$spi)->slice(":,0:-2")->mv(2,3);
983 } else {
984 $spi = $foop->getdim(2)/$_;
985 $foop = $foop->splitdim(2,$spi)->slice(":,:,0:-2");
986 }
987 # print "IND+\n";
988 $ind++; # Just to keep even/odd correct
989 }
990 # $foop->dump;
991 print "ASSGNFOOP!\n" if $PDL::debug;
992  
993 $foop .= $this->{Im};
994 # print "P: $p\n";
995 return wantarray() ? ($p,$xd,$yd,$txd,$tyd) : $p;
996 }
997  
998 sub toimage {
999 # initially very simple implementation
1000 my ($this) = @_;
1001 return $this->flatten(0);
1002 }
1003  
1004 1;
1005