-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdisplay_kernel.cpp
More file actions
1674 lines (1494 loc) · 47.8 KB
/
Copy pathdisplay_kernel.cpp
File metadata and controls
1674 lines (1494 loc) · 47.8 KB
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.
// Copyright (c) 2003, 2004 by Jonathan Brandmeyer and others.
// See the file license.txt for complete license terms.
// See the file authors.txt for a complete list of contributors.
#include "display_kernel.hpp"
#include "util/errors.hpp"
#include "util/tmatrix.hpp"
#include "util/gl_enable.hpp"
#include "material.hpp"
#include "frame.hpp"
#include "text.hpp"
#include "wrap_gl.hpp"
#include <cassert>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <iostream>
#include <boost/scoped_array.hpp>
#include <boost/lexical_cast.hpp>
namespace cvisual {
shared_ptr<display_kernel> display_kernel::selected;
bool display_kernel::enable_shaders = true;
////////////////////////////////////////////////////////////////
// Implementation of display_kernel::waitWhileAnyDisplayVisible()
static mutex displays_visible_lock;
static boost::condition displays_visible_condition;
static int displays_visible = 0;
void set_display_visible( display_kernel*, bool visible ) {
lock L( displays_visible_lock );
if (visible) displays_visible++;
else displays_visible--;
displays_visible_condition.notify_all();
}
void
display_kernel::waitWhileAnyDisplayVisible()
{
python::gil_release gil;
lock L( displays_visible_lock );
while ( displays_visible )
displays_visible_condition.wait( L );
}
////////////////////////////////////////////////////////////////
static const display_kernel::EXTENSION_FUNCTION notImplemented = (display_kernel::EXTENSION_FUNCTION)-1;
void
display_kernel::enable_lights(view& scene)
{
scene.light_count[0] = 0;
scene.light_pos.clear();
scene.light_color.clear();
std::list<shared_ptr<renderable> >::iterator i = layer_world.begin();
std::list<shared_ptr<renderable> >::iterator i_end = layer_world.end();
for(; i != i_end; ++i)
(*i)->render_lights( scene );
std::vector<shared_ptr<renderable> >::iterator j = layer_world_transparent.begin();
std::vector<shared_ptr<renderable> >::iterator j_end = layer_world_transparent.end();
for(; j != j_end; ++j)
(*j)->render_lights( scene );
tmatrix world_camera; world_camera.gl_modelview_get();
vertex p;
// Clear modelview matrix since we are multiplying the light positions ourselves
gl_matrix_stackguard guard;
glLoadIdentity();
for(int i=0; i<scene.light_count[0] && i<8; i++) {
int li = i*4;
// Transform the light into eye space
for(int d=0; d<4; d++) p[d] = scene.light_pos[li+d];
p = world_camera * p;
for(int d=0; d<4; d++) scene.light_pos[li+d] = p[d];
// Enable the light for fixed function lighting. This is unnecessary if everything in the scene
// uses materials and the card supports our shaders, but for now...
int id = GL_LIGHT0 + i;
glLightfv( id, GL_DIFFUSE, &scene.light_color[li]);
glLightfv( id, GL_SPECULAR, &scene.light_color[li]);
glLightfv( id, GL_POSITION, &scene.light_pos[li]);
glEnable(id);
}
for(int i=scene.light_count[0]; i<8; i++)
glDisable( GL_LIGHT0 + i );
glEnable( GL_LIGHTING);
glLightModelfv( GL_LIGHT_MODEL_AMBIENT, &ambient.red);
check_gl_error();
}
void
display_kernel::disable_lights()
{
glDisable( GL_LIGHTING);
}
// Compute the horizontal and vertial tangents of half the field-of-view.
void
display_kernel::tan_hfov( double* x, double* y)
{
// tangent of half the field of view.
double tan_hfov = std::tan( fov*0.5);
double aspect_ratio = (double)view_height / view_width;
if (stereo_mode == PASSIVE_STEREO || stereo_mode == CROSSEYED_STEREO)
aspect_ratio *= 2.0;
if (aspect_ratio > 1.0) {
// Tall window
*x = tan_hfov / aspect_ratio;
*y = tan_hfov;
}
else {
// Wide window
*x = tan_hfov;
*y = tan_hfov * aspect_ratio;
}
}
vector
display_kernel::calc_camera()
{
return camera;
/* old scheme not necessary?
double tan_hfov_x = 0.0;
double tan_hfov_y = 0.0;
tan_hfov( &tan_hfov_x, &tan_hfov_y);
double cot_hfov = 1 / std::min(tan_hfov_x, tan_hfov_y);
return (-forward.norm() * cot_hfov*user_scale).scale(range) + center;
*/
}
display_kernel::display_kernel()
:
exit(true),
visible(false),
explicitly_invisible(false),
fullscreen(false),
title( "VPython" ),
window_x(0), window_y(0), window_width(430), window_height(450),
view_width(-1), view_height(-1),
center(0, 0, 0),
forward(0, 0, -1),
internal_forward(0, 0, -1),
up(0, 1, 0),
forward_changed(true),
fov( 60 * M_PI / 180.0),
autoscale(true),
autocenter(false),
uniform(true),
camera(0,0,0),
user_scale(1.0),
gcf(1.0),
gcfvec(vector(1.0,1.0,1.0)),
gcf_changed(false),
ambient( 0.2f, 0.2f, 0.2f),
show_toolbar( false),
show_rendertime( false),
last_time(0),
background(0, 0, 0), //< Transparent black.
spin_allowed(true),
zoom_allowed(true),
mouse_mode( ZOOM_ROTATE),
stereo_mode( NO_STEREO),
stereodepth( 0.0f),
lod_adjust(0),
realized(false),
mouse( *this ),
range_auto(0.0),
range(0,0,0),
world_extent(0.0)
{
}
display_kernel::~display_kernel()
{
if (visible)
set_display_visible( this, false );
}
void
display_kernel::report_closed() {
if (visible)
set_display_visible( this, false );
VPYTHON_NOTE("report_closed: try to lock realize_lock.");
lock L( realize_lock );
VPYTHON_NOTE("report_closed: locked realize_lock.");
realized = false;
visible = false;
explicitly_invisible = true;
realize_condition.notify_all();
VPYTHON_NOTE("report_closed: executed realize_condition.notify_all().");
}
void
display_kernel::report_camera_motion( int dx, int dy, mouse_button button )
{
// This stuff handles automatic movement of the camera in response to user
// input. See also view_to_world_transform for how the affected variables
// are used to actually position the camera.
// Scaling conventions:
// the full width of the widget rotates the scene horizontally by 120 degrees.
// the full height of the widget rotates the scene vertically by 120 degrees.
// the full height of the widget zooms the scene by a factor of 10
// Panning conventions:
// The full height or width of the widget pans the scene by the eye distance.
// Locking:
// center and forward are already synchronized. The only variable that
// remains to be synchronized is user_scale.
// The vertical and horizontal fractions of the window's height that the
// mouse has traveled for this event.
// TODO: Implement ZOOM_ROLL modes.
float vfrac = (float)dy / view_height;
float hfrac = dx
/ ((stereo_mode == PASSIVE_STEREO || stereo_mode == CROSSEYED_STEREO) ?
(view_width*0.5f) : view_width);
// The amount by which the scene should be shifted in response to panning
// motion.
// TODO: Keep this synchronized with the eye_dist calc in
// world_view_transform
double tan_hfov_x = 0.0;
double tan_hfov_y = 0.0;
tan_hfov( &tan_hfov_x, &tan_hfov_y);
double pan_rate = (center - calc_camera()).mag()
* std::min( tan_hfov_x, tan_hfov_y);
switch (button) {
case NONE: case LEFT:
break;
case MIDDLE:
switch (mouse_mode) {
case FIXED:
// Locked.
break;
case PAN:
// Pan front/back.
if (spin_allowed)
center += pan_rate * vfrac * internal_forward.norm();
break;
case ZOOM_ROLL: case ZOOM_ROTATE:
// Zoom in/out.
if (zoom_allowed)
user_scale *= std::pow( 10.0f, vfrac);
break;
}
break;
case RIGHT:
switch (mouse_mode) {
case FIXED: case ZOOM_ROLL:
break;
case PAN: {
// Pan up/down and left/right.
// A vector pointing along the camera's horizontal axis.
vector horiz_dir = internal_forward.cross(up).norm();
// A vector pointing along the camera's vertical axis.
vector vert_dir = horiz_dir.cross(internal_forward).norm();
if (spin_allowed) {
center += -horiz_dir * pan_rate * hfrac;
center += vert_dir * pan_rate * vfrac;
}
break;
}
case ZOOM_ROTATE: {
if (spin_allowed) {
// Rotate
// First perform the rotation about the up vector.
tmatrix R = rotation( -hfrac * 2.0, up.norm());
internal_forward = R * internal_forward;
// Then perform rotation about an axis orthogonal to up and forward.
double vertical_angle = vfrac * 2.0;
double max_vertical_angle = up.diff_angle(-internal_forward.norm());
// Over the top (or under the bottom) rotation
if (!(vertical_angle >= max_vertical_angle ||
vertical_angle <= max_vertical_angle - M_PI)) {
// Over the top (or under the bottom) rotation
R = rotation( -vertical_angle, internal_forward.cross(up).norm());
forward = internal_forward = R*internal_forward;
forward_changed = true;
}
}
break;
}
}
break;
}
}
void
display_kernel::report_window_resize( int win_x, int win_y, int win_w, int win_h )
{
window_x = win_x; window_y = win_y; window_width = win_w; window_height = win_h;
}
void
display_kernel::report_view_resize( int v_w, int v_h )
{
view_width = std::max(v_w,1); view_height = std::max(v_h,1);
}
void
display_kernel::realize()
{
clear_gl_error();
if (!extensions) {
using namespace std;
VPYTHON_NOTE( "Querying the list of OpenGL extensions.");
extensions.reset( new set<string>());
istringstream strm( string( (const char*)(glGetString( GL_EXTENSIONS))));
copy( istream_iterator<string>(strm), istream_iterator<string>(),
inserter( *extensions, extensions->begin()));
vendor = std::string((const char*)glGetString(GL_VENDOR));
version = std::string((const char*)glGetString(GL_VERSION));
renderer = std::string((const char*)glGetString(GL_RENDERER));
// The test is a hack so that subclasses not bothering to implement getProcAddress just
// don't get any extensions.
if (getProcAddress("display_kernel::getProcAddress") != notImplemented)
glext.init( *this );
}
// Those features of OpenGL that are always used are set up here.
// Depth buffer properties
glClearDepth( 1.0);
glEnable( GL_DEPTH_TEST);
glDepthFunc( GL_LEQUAL);
// Lighting model properties
glShadeModel( GL_SMOOTH);
// TODO: Figure out what the concrete costs/benefits of these commands are.
// glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint( GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable( GL_NORMALIZE);
glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable( GL_COLOR_MATERIAL);
glEnable( GL_BLEND );
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Ensures that fully transparent pixels don't write into the depth buffer,
// ever.
glEnable( GL_ALPHA_TEST);
glAlphaFunc( GL_GREATER, 0.0);
// FSAA. Doesn't seem to have much of an effect on my TNT2 card. Grrr.
if ( hasExtension( "GL_ARB_multisample" ) ) {
glEnable( GL_MULTISAMPLE_ARB);
GLint n_samples, n_buffers;
glGetIntegerv( GL_SAMPLES_ARB, &n_samples);
glGetIntegerv( GL_SAMPLE_BUFFERS_ARB, &n_buffers);
VPYTHON_NOTE( "Using GL_ARB_multisample extension: samples:"
+ boost::lexical_cast<std::string>(n_samples)
+ " buffers: " + boost::lexical_cast<std::string>(n_buffers));
}
check_gl_error();
}
// Set up matricies for transforms from world coordinates to view coordinates
// Precondition: the OpenGL Modelview and Projection matrix stacks should be
// at the bottom.
// Postcondition: active matrix stack is GL_MODELVIEW, matrix stacks are at
// the bottom. Viewing transformations have been applied. geometry.camera
// is initialized.
// whicheye: -1 for left, 0 for center, 1 for right.
void
display_kernel::world_to_view_transform(
view& geometry, int whicheye, bool forpick)
{
// See http://www.stereographics.com/support/developers/pcsdk.htm for a
// discussion regarding the design basis for the frustum offset code.
// gcf scales the region encompassed by scene.range_* into a ROUGHLY 2x2x2 cube.
// Note that this is NOT necessarily the entire world, since scene.range
// can be changed.
// This coordinate system is used for most of the calculations below.
vector scene_center = center.scale(gcfvec);
vector scene_up = up.norm();
vector scene_forward = internal_forward.norm();
// the horizontal and vertical tangents of half the field of view.
double tan_hfov_x;
double tan_hfov_y;
tan_hfov( &tan_hfov_x, &tan_hfov_y);
// The cotangent of half of the wider field of view.
double cot_hfov;
if (!uniform) // We force width to be 2.0 (range.x 1.0)
cot_hfov = 1.0 / tan_hfov_x;
else
cot_hfov = 1.0 / std::max(tan_hfov_x, tan_hfov_y);
// The camera position is chosen by the tightest of the enabled range_* modes.
double cam_to_center_without_zoom = 1e150;
/*if (range_sphere_radius)
cam_to_center_without_zoom = std::min(cam_to_center_without_zoom,
range_sphere_radius / sin( fov * 0.5 ) );
if (range_box_size.nonzero()) {
if (range_unrotated) {
cam_to_center_without_zoom = std::min(cam_to_center_without_zoom,
std::max(range_box_size.x, range_box_size.y) * 0.5 * cot_hfov + range_box_size.z * 0.5);
} else
cam_to_center_without_zoom = std::min(cam_to_center_without_zoom,
range_box_size.mag() * 0.5 / sin( fov * 0.5 ) );
}*/
if (range_auto)
cam_to_center_without_zoom = std::min(cam_to_center_without_zoom,
range_auto);
if (range.nonzero())
cam_to_center_without_zoom = std::min(cam_to_center_without_zoom,
range.x * cot_hfov / 1.02);
if (cam_to_center_without_zoom >= 1e150)
cam_to_center_without_zoom = 10.0 / sin( fov * 0.5 );
cam_to_center_without_zoom *= gcf * 1.02;
// Position camera so that a sphere containing the box range will fit on the screen
// OR a 2*user_scale cube will fit. The former is tighter for "non cubical" ranges
// and the latter is tighter for cubical ones.
/*double radius = range.mag() * gcf * user_scale;
double cam_to_center_without_zoom = 1.02 * std::min( radius / sin( fov * 0.5 ),
cot_hfov + 1.0 );*/
vector scene_camera = scene_center - cam_to_center_without_zoom*user_scale*scene_forward;
double nearest, farthest;
world_extent.get_near_and_far(internal_forward, nearest, farthest); // nearest and farthest points relative to scene.center when projected onto forward
nearest = nearest*gcf;
farthest = farthest*gcf;
double cam_to_center = (scene_center - scene_camera).mag();
// Z buffer resolution is highly sensitive to nearclip - a "small" camera will have terrible z buffer
// precision for distant objects. PLEASE don't fiddle with this unless you know what kind of
// test cases you need to see the results, including at nonstandard fields of view and 24 bit
// z buffers!
// The equation for nearclip below is designed to give similar z buffer resolution at all fields of
// view. It's a little weird, but seems to give acceptable results in all the cases I've been able
// to test.
// The other big design question here is the effect of "zoom" (user_scale) on the near clipping plane.
// Most users will have the mental model that this moves the camera closer to the scene, rather than
// scaling the scene up. There is actually a difference since the camera has a finite "size".
// Unfortunately, following this model leads to a problem with zooming in a lot! The problem is
// especially pronounced at tiny fields of view, which typically have an enormous camera very far away;
// when you try to zoom in the big camera "crashes" into the tiny scene! So instead we use the
// slightly odd model of scaling the scene, or equivalently making the camera smaller as you zoom in.
double fwz = cam_to_center_without_zoom + 1.0;
double nearclip = fwz * fwz / (100 + fwz) * user_scale;
// TODO: nearclip = std::max( nearclip, (cam_to_center + nearest) * 0.95 ); //< ?? boost z buffer resolution if there's nothing close to camera?
double farclip = (farthest + cam_to_center) * 1.05; //< actual maximum z in scene plus a little
farclip = std::max( farclip, nearclip * 1.001 ); //< just in case everything is behind the camera!
// Here is the stereodepth and eye offset machinery from Visual 3, where the docs claimed that
// stereodepth=0 was the default (zero-parallax plane at screen surface;
// stereodepth=1 moves the center of the scene to the screen surface;
// stereodepth=2 moves the back of the scene to the screen surface:
/*
double farclip = cotfov + ext;
double nearclip = 0.0;
if ((cam - display->c_center).mag() < display->c_extent.mag()) {
// Then the camera is within the scene. Pick a value that looks OK.
nearclip = 0.015;
}
else {
nearclip = cotfov - ext*1.5;
if (nearclip < 0.01*farclip)
nearclip = 0.01*farclip;
}
double R = nearclip*hfov;
double T = nearclip*vfov;
double fl = 0.5*ext + ext*stereodepth + nearclip; //focal length
double eyeOffset = eyesign*fl/60.0; // eye separation 1/30 of focallength
double eyeOffset1 = eyeOffset * (nearclip/fl);
frustum(proj, iproj, -R-eyeOffset1, R-eyeOffset1, -T, T, nearclip, farclip);
*/
// A multiple of the number of cam_to_center's away from the camera to place
// the zero-parallax plane.
// The distance from the camera to the zero-parallax plane.
double focallength = cam_to_center+0.5*stereodepth;
// Translate camera left/right 2% of the viewable width of the scene at
// the distance of its center.
//double camera_stereo_offset = tan_hfov_x * cam_to_center * 0.02;
double camera_stereo_offset = tan_hfov_x * focallength * 0.02;
vector camera_stereo_delta = camera_stereo_offset
* up.cross( scene_camera).norm() * whicheye;
scene_camera += camera_stereo_delta;
scene_center += camera_stereo_delta;
// The amount to translate the frustum to the left and right.
double frustum_stereo_offset = camera_stereo_offset * nearclip
/ focallength * whicheye;
// Finally, the OpenGL transforms based on the geometry just calculated.
clear_gl_error();
// Position the camera.
glMatrixMode( GL_MODELVIEW);
glLoadIdentity();
#if 0 // Enable this to peek at the actual scene geometry.
int max_proj_stack_depth = -1;
int max_mv_stack_depth = -1;
int proj_stack_depth = -1;
int mv_stack_depth = -1;
glGetIntegerv( GL_MAX_PROJECTION_STACK_DEPTH, &max_proj_stack_depth);
glGetIntegerv( GL_MAX_MODELVIEW_STACK_DEPTH, &max_mv_stack_depth);
glGetIntegerv( GL_PROJECTION_STACK_DEPTH, &proj_stack_depth);
glGetIntegerv( GL_MODELVIEW_STACK_DEPTH, &mv_stack_depth);
std::cerr << "scene_geometry: camera:" << scene_camera
<< " true camera:" << camera << std::endl
<< " center:" << scene_center << " true center:" << center << std::endl
<< " forward:" << scene_forward << " true forward:" << forward << std::endl
<< " up:" << scene_up << " range:" << range << " gcf:" << gcf << std::endl
<< " nearclip:" << nearclip << " nearest:" << nearest << std::endl
<< " farclip:" << farclip << " farthest:" << farthest << std::endl
<< " user_scale:" << user_scale << std::endl
<< " cot_hfov:" << cot_hfov << " tan_hfov_x:" << tan_hfov_x << std::endl
<< " tan_hfov_y: " << tan_hfov_y << std::endl
<< " window_width:" << window_width << " window_height:" << window_height << std::endl
<< " max_proj_depth:" << max_proj_stack_depth << " current_proj_depth:" << proj_stack_depth << std::endl
<< " max_mv_depth:" << max_mv_stack_depth << " current_mv_depth:" << mv_stack_depth << std::endl;
world_extent.dump_extent();
std::cerr << std::endl;
#endif
gluLookAt(
scene_camera.x, scene_camera.y, scene_camera.z,
scene_center.x, scene_center.y, scene_center.z,
scene_up.x, scene_up.y, scene_up.z);
tmatrix world_camera; world_camera.gl_modelview_get();
inverse( geometry.camera_world, world_camera );
//vector scene_range = range * gcf;
//glScaled( 1.0/scene_range.x, 1.0/scene_range.y, 1.0/scene_range.z);
// Establish a parallel-axis asymmetric stereo projection frustum.
glMatrixMode( GL_PROJECTION);
if (!forpick)
glLoadIdentity();
if (whicheye == 1) {
frustum_stereo_offset = -frustum_stereo_offset;
}
else if (whicheye == 0) {
frustum_stereo_offset = 0;
}
if (nearclip<=0 || farclip<=nearclip || tan_hfov_x<=0 || tan_hfov_y<=0) {
std::ostringstream msg;
msg << "VPython degenerate projection: " << nearclip << " " << farclip << " " << tan_hfov_x << " " << tan_hfov_y;
VPYTHON_CRITICAL_ERROR( msg.str());
std::exit(1);
}
glFrustum(
-nearclip * tan_hfov_x + frustum_stereo_offset,
nearclip * tan_hfov_x + frustum_stereo_offset,
-nearclip * tan_hfov_y,
nearclip * tan_hfov_y,
nearclip,
farclip );
glMatrixMode( GL_MODELVIEW);
check_gl_error();
// The true camera position, in world space.
camera = scene_camera/gcf;
// Finish initializing the view object.
geometry.camera = camera;
geometry.tan_hfov_x = tan_hfov_x;
geometry.tan_hfov_y = tan_hfov_y;
// The true viewing vertical direction is not the same as what is needed for
// gluLookAt().
geometry.up = internal_forward.cross_b_cross_c(up, internal_forward).norm();
}
// Calculate a new extent for the universe, adjust gcf, center, and world_scale
// as required.
void
display_kernel::recalc_extent(void)
{
double tan_hfov_x;
double tan_hfov_y;
tan_hfov( &tan_hfov_x, &tan_hfov_y );
double tan_hfov = std::max(tan_hfov_x, tan_hfov_y);
while (1) { //< Might have to do this twice for autocenter
world_extent = extent_data( tan_hfov );
tmatrix l_cw;
l_cw.translate( -center );
extent ext( world_extent, l_cw );
world_iterator i( layer_world.begin());
world_iterator end( layer_world.end());
while (i != end) {
i->grow_extent( ext);
++i;
}
world_trans_iterator j( layer_world_transparent.begin());
world_trans_iterator j_end( layer_world_transparent.end());
while (j != j_end) {
j->grow_extent( ext);
++j;
}
if (autocenter) {
vector c = world_extent.get_center() + center;
if ( (center-c).mag2() > (center.mag2() + c.mag2()) * 1e-6 ) {
// Change center and recalculate extent (since camera_z depends on center)
center = c;
continue;
}
}
break;
}
if (autoscale && uniform) {
double r = world_extent.get_camera_z();
if (r > range_auto) range_auto = r;
else if ( 3.0*r < range_auto ) range_auto = 3.0*r;
}
// Rough scale calculation for gcf. Doesn't need to be exact.
// TODO: If extent and range are very different in scale, we are using extent to drive
// gcf. Both options have pros and cons.
double mr = world_extent.get_range(vector(0,0,0)).mag();
double scale = mr ? 1.0 / mr : 1.0;
if (!uniform && range.nonzero()) {
gcf_changed = true;
gcf = 1.0/range.x;
double width = (stereo_mode == PASSIVE_STEREO || stereo_mode == CROSSEYED_STEREO)
? view_width*0.5 : view_width;
gcfvec = vector(1.0/range.x, (view_height/width)/range.y, 0.1/range.z);
} else {
// TODO: Instead of changing gcf so much, we could change it only when it is 2x
// off, to aid primitives whose caching may depend on gcf (but are there any?)
if (gcf != scale) {
gcf = scale;
gcf_changed = true;
}
gcfvec = vector(gcf,gcf,gcf);
}
}
void display_kernel::implicit_activate() {
if (!visible && !explicitly_invisible)
set_visible( true );
}
void
display_kernel::add_renderable( shared_ptr<renderable> obj)
{
// Driven from visual/primitives.py set_visible
if (!obj->translucent())
layer_world.push_back( obj);
else
layer_world_transparent.push_back( obj);
if (!obj->is_light())
implicit_activate();
}
void
display_kernel::remove_renderable( shared_ptr<renderable> obj)
{
// Driven from visual/primitives.py set_visible
if (!obj->translucent()) {
std::remove( layer_world.begin(), layer_world.end(), obj);
layer_world.pop_back();
}
else {
std::remove( layer_world_transparent.begin(), layer_world_transparent.end(), obj);
layer_world_transparent.pop_back();
}
}
bool
display_kernel::draw(
view& scene_geometry, int whicheye)
{
// Set up the base modelview and projection matrices
world_to_view_transform( scene_geometry, whicheye);
// Render all opaque objects in the world space layer
enable_lights(scene_geometry);
world_iterator i( layer_world.begin());
world_iterator i_end( layer_world.end());
while (i != i_end) {
if (i->translucent()) {
// The color of the object has become transparent when it was not
// initially. Move it to the transparent layer. The penalty for
// being rendered in the transparent layer when it is opaque is only
// a small speed hit when it has to be sorted. Therefore, that case
// is not tested at all. (TODO Untrue-- rendering opaque objects in transparent
// layer makes it possible to have opacity artifacts with a single convex
// opaque objects, provided other objects in the scene were ONCE transparent)
layer_world_transparent.push_back( *i.base());
i = layer_world.erase(i.base());
continue;
}
i->outer_render( scene_geometry);
++i;
}
// Perform a depth sort of the transparent world from back to front.
if (layer_world_transparent.size() > 1)
std::stable_sort(
layer_world_transparent.begin(), layer_world_transparent.end(),
z_comparator( internal_forward.norm()));
// Render translucent objects in world space.
world_trans_iterator j( layer_world_transparent.begin());
world_trans_iterator j_end( layer_world_transparent.end());
while (j != j_end) {
j->outer_render( scene_geometry );
++j;
}
// Render all objects in screen space.
disable_lights();
gl_disable depth_test( GL_DEPTH_TEST);
typedef std::multimap<vector, displaylist, z_comparator>::iterator
screen_iterator;
screen_iterator k( scene_geometry.screen_objects.begin());
screen_iterator k_end( scene_geometry.screen_objects.end());
while ( k != k_end) {
k->second.gl_render();
++k;
}
scene_geometry.screen_objects.clear();
return true;
}
// Renders the entire scene.
bool
display_kernel::render_scene(void)
{
// TODO: Exception handling?
if (!realized) {
realize();
lock L(realize_lock);
realized = true;
realize_condition.notify_all();
}
double start_time, cycle;
if (show_rendertime) {
start_time = render_timer.elapsed();
cycle = start_time - last_time;
last_time = start_time;
}
try {
recalc_extent();
view scene_geometry( internal_forward.norm(), center, view_width,
view_height, forward_changed, gcf, gcfvec, gcf_changed, glext);
scene_geometry.lod_adjust = lod_adjust;
scene_geometry.enable_shaders = enable_shaders;
clear_gl_error();
on_gl_free.frame();
glClearColor( background.red, background.green, background.blue, 0);
// Control which type of stereo to perform.
switch (stereo_mode) {
case NO_STEREO:
scene_geometry.anaglyph = false;
scene_geometry.coloranaglyph = false;
glViewport( 0, 0, view_width, view_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw(scene_geometry, 0);
break;
case ACTIVE_STEREO:
scene_geometry.anaglyph = false;
scene_geometry.coloranaglyph = false;
glViewport( 0, 0, view_width, view_height);
glDrawBuffer( GL_BACK_LEFT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, -1);
glDrawBuffer( GL_BACK_RIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, 1);
break;
case REDBLUE_STEREO:
// Red channel
scene_geometry.anaglyph = true;
scene_geometry.coloranaglyph = false;
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, view_width, view_height);
glColorMask( GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
draw( scene_geometry, -1);
// Blue channel
glColorMask( GL_FALSE, GL_FALSE, GL_TRUE, GL_TRUE);
glClear( GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, 1);
// Put everything back
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
break;
case REDCYAN_STEREO:
// Red channel
scene_geometry.anaglyph = true;
scene_geometry.coloranaglyph = true;
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, view_width, view_height);
glColorMask( GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
draw( scene_geometry, -1);
// Green and Blue channels
glColorMask( GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
glClear( GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, 1);
// Put everything back
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
break;
case YELLOWBLUE_STEREO:
// Red and green channels
scene_geometry.anaglyph = true;
scene_geometry.coloranaglyph = true;
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, view_width, view_height);
glColorMask( GL_TRUE, GL_TRUE, GL_FALSE, GL_TRUE);
draw( scene_geometry, -1);
// Blue channel
glColorMask( GL_FALSE, GL_FALSE, GL_TRUE, GL_TRUE);
glClear( GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, 1);
// Put everything back
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
break;
case GREENMAGENTA_STEREO:
// Green channel
scene_geometry.anaglyph = true;
scene_geometry.coloranaglyph = true;
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, view_width, view_height);
glColorMask( GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE);
draw( scene_geometry, -1);
// Red and blue channels
glColorMask( GL_TRUE, GL_FALSE, GL_TRUE, GL_TRUE);
glClear( GL_DEPTH_BUFFER_BIT);
draw( scene_geometry, 1);
// Put everything back
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
break;
case PASSIVE_STEREO: {
// Also handle viewport modifications.
scene_geometry.view_width = view_width/2;
scene_geometry.anaglyph = false;
scene_geometry.coloranaglyph = false;
int stereo_width = int(scene_geometry.view_width);
// Left eye
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, stereo_width, view_height );
draw( scene_geometry, -1);
// Right eye
glViewport( stereo_width+1, 0, stereo_width, view_height);
draw( scene_geometry, 1);
break;
}
case CROSSEYED_STEREO: {
// Also handle viewport modifications.
scene_geometry.view_width = view_width/2;
scene_geometry.anaglyph = false;
scene_geometry.coloranaglyph = false;
int stereo_width = int(scene_geometry.view_width);
// Left eye
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, stereo_width, view_height);
draw( scene_geometry, 1);
// Right eye
glViewport( stereo_width+1, 0, stereo_width, view_height );
draw( scene_geometry, -1);
break;
}
}
if (show_rendertime) {
double render_time = render_timer.elapsed()-start_time, flush_time = -1;
#if 0 //< Only for performance measurement; disable in shipping code
glFinish();
flush_time = render_timer.elapsed() - start_time - render_time;
#endif
std::wostringstream render_msg;
render_msg.precision(3);
// render time does not include pick time, which may be negligible
//render_msg << "cycle: " << int(1000*cycle) <<
// " render: " << int(1000*(render_time));
// render_time is only a portion of the actual paint time in render_manager.cpp,
// so it is misleading to display it. In render_manager.cpp is measured actual paint time,
// and buffer swap time, and it generates the interval to the start of the next paint.
// The cycle time assumes only one scene, but at least it is accurate in this important special case.
render_msg << "cycle: " << int(1000*cycle);
if (flush_time>=0) render_msg << " flush: " << int(1000*flush_time);
glColor3f(
1.0f - background.red, 1.0f-background.green, 1.0f-background.blue);
glMatrixMode( GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D( 0, view_width, 0, view_height);
glMatrixMode( GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
{
gl_disable depth_test(GL_DEPTH_TEST);
boost::shared_ptr<font> default_font = font::find_font();
boost::shared_ptr<layout> lay_out = default_font->lay_out( render_msg.str());
lay_out->gl_render( scene_geometry, vector(5, lay_out->extent( scene_geometry ).y + 3));
}
glPopMatrix();
glMatrixMode( GL_PROJECTION);
glPopMatrix();
glMatrixMode( GL_MODELVIEW);
}
// Cleanup
check_gl_error();
gcf_changed = false;
forward_changed = false;
}
catch (gl_error e) {
std::ostringstream msg;
msg << "OpenGL error: " << e.what() << ", aborting.\n";
VPYTHON_CRITICAL_ERROR( msg.str());
std::exit(1);
}
if (show_rendertime) {
render_time = render_timer.elapsed()-start_time;
}
// TODO: Can we delay picking until the Python program actually wants one of these attributes?
mouse.get_mouse().cam = camera;
boost::tie( mouse.get_mouse().pick, mouse.get_mouse().pickpos, mouse.get_mouse().position) =
pick( mouse.get_x(), mouse.get_y() );
on_gl_free.frame();
return true;
}
boost::tuple< shared_ptr<renderable>, vector, vector>
display_kernel::pick( int x, int y, float d_pixels)
{
using boost::scoped_array;
shared_ptr<renderable> best_pick;
vector pickpos;
vector mousepos;
try {
clear_gl_error();
// Notes:
// culled polygons don't count. glRasterPos() does count.
// Allocate a selection buffer of uints. Format for returned hits is:
// {uint32: n_names}{uint32: minimunm depth}{uint32: maximum depth}
// {unit32[n_names]: name_stack}
// n_names is the depth of the name stack at the time of the hit.
// minimum and maximum depth are the minimum and maximum values in the
// depth buffer scaled between 0 and 2^32-1. (source is [0,1])
// name_stack is the full contents of the name stack at the time of the
// hit.
size_t hit_buffer_size = std::max(
(layer_world.size()+layer_world_transparent.size())*4,
world_extent.get_select_buffer_depth());
// Allocate an exception-safe buffer for the GL to talk back to us.
scoped_array<unsigned int> hit_buffer(
new unsigned int[hit_buffer_size]);
// unsigned int hit_buffer[hit_buffer_size];
// Allocate a std::vector<shared_ptr<renderable> > to lookup names
// as they are rendered.
std::vector<shared_ptr<renderable> > name_table;
// Pass the name stack to OpenGL with glSelectBuffer.