-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComposite.cpp
More file actions
2450 lines (2137 loc) · 103 KB
/
Copy pathComposite.cpp
File metadata and controls
2450 lines (2137 loc) · 103 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) 2024-2025: Arizona Board of Regents on Behalf of the University of Arizona
*/
#ifdef WIN32
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Composite.h"
using namespace asdp::render;
//======================================
// Added by Sang Yoon to share the head orientation information of detailed view window
// with the overview window.
// This information is used for drawing a rectangle in the overview window
// showing the user's head orientation of detailed view window (DrawHeadOrientation()).
// Note that the mutually exclusive access to the variables between the composite submodules
// associated with overview and detailed view windows is controlled using a mutex (overview_mutex)
// in Composite::Render() and DrawHeadOrientation(). In the composite submodule associated with
// the detailed view window, the head orientation information of the detailed view window is stored
// to the global variables, and in the composite submodule associated with the overview window,
// the values of the global variables are read.
std::mutex g_overview_mutex;
glm::mat4 g_detailed_view_translate;
float g_detailed_view_leftf;
float g_detailed_view_rightf;
float g_detailed_view_topf;
float g_detailed_view_bottomf;
float g_detailed_view_nearf;
//======================================
//======================================
// Added by Sang Yoon to fix a bug in drawing a line where the cylindrical projection is used
glm::mat4 g_overview_translate; // model-view matrix of overview window; copied in the Render() method and used in the DrawHeadOrientation() method
//======================================
Composite::~Composite()
{
// Empty destructor.
}
void Composite::Render(asdp::Time scanOutTime, std::vector<ViewRenderInfo> views)
{
// Initialize for rendering if it has not already been done. Do this while holding
// a mutex lock so we don't have it happen in two threads as a race.
{
std::lock_guard<std::mutex> lock(m_initMutex);
if (!m_initialized) {
if (!SetupRendering()) {
std::cerr << "Composite::Render(): Could not set up rendering" << std::endl;
return;
}
m_initialized = true;
}
}
// Set up the geometry for all of the views so the world is consistent across views.
SetupRenderFrame(scanOutTime);
// Render each view
for (size_t eye = 0; eye < views.size(); eye++) {
const ViewRenderInfo& view = views[eye];
// Only set up the frame buffer and clear the buffers if we're the first eye or if the
// eyes use different frame buffers or different color buffers.
if ((eye == 0) || (views[eye].frameBuffer != views[0].frameBuffer) || (views[eye].colorBuffer != views[0].colorBuffer)) {
// Bind the frame buffer and assign the appropriate textures.
glBindFramebuffer(GL_FRAMEBUFFER, view.frameBuffer);
if (view.frameBuffer != 0) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, view.colorBuffer, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, view.depthBuffer, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
std::cerr << "Composite::Render(): Frame buffer is not complete" << std::endl;
}
}
if (m_doClear) {
// Clear the buffers. The clear color is sky blue to distingiush from a camera with a black texture.
glClearColor(0.6f, 0.8f, 1.0f, 1.0f);
GLbitfield clearBits = 0;
if ((view.frameBuffer == 0) || (view.colorBuffer != 0)) { clearBits |= GL_COLOR_BUFFER_BIT; }
if ((view.frameBuffer == 0) || (view.depthBuffer != 0)) { clearBits |= GL_DEPTH_BUFFER_BIT; }
glClear(clearBits);
}
}
// Turn on depth testing so we get proper rendering. The default frame buffer has depth.
if ((view.frameBuffer == 0) || (view.depthBuffer != 0)) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
}
// Set up the viewport for this view.
glViewport(view.x, view.y, view.width, view.height);
// Rotate the view to match the helicopter's orientation, looking down the +Y axis with
// the up vector being Z. This rotates the camera by 90 degrees around the X axis. Because
// we're rotating the world rather than the camera, we rotate in the opposite direction.
glm::mat4 HelicopterRotateX = glm::rotate(glm::mat4(1.0f),
glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
// Compute the view-projection matrix (no model described here) from the ViewRenderInfo.
// NOTE: We translate and rotate in the opposite direction because we're moving the world rather
// than the camera but the offset and orientation are specified for camera movement.
// NOTE: We also do the order of operations in reverse because we're moving the world rather
// than the camera.
glm::quat rotQuat;
rotQuat.w = view.orientation[0];
rotQuat.x = view.orientation[1];
rotQuat.y = view.orientation[2];
rotQuat.z = view.orientation[3];
rotQuat = glm::inverse(rotQuat);
glm::mat4 ViewRotate = HelicopterRotateX * glm::toMat4(rotQuat);
// Translate the view based on the specified viewpoint (negative due to world vs. camera).
glm::mat4 ViewTranslate = glm::translate(ViewRotate,
glm::vec3(-view.viewpoint[0], -view.viewpoint[1], -view.viewpoint[2]));
// Compute the projection matrix from the ViewRenderInfo.
double leftFrust = tan(glm::radians(view.leftHalfFOV)) * view.nearClip;
double rightFrust = tan(glm::radians(view.rightHalfFOV)) * view.nearClip;
double bottomFrust = tan(glm::radians(view.bottomHalfFOV)) * view.nearClip;
double topFrust = tan(glm::radians(view.topHalfFOV)) * view.nearClip;
glm::mat4 Projection = glm::frustum<float>(leftFrust, rightFrust, bottomFrust, topFrust,
view.nearClip, view.farClip);
glm::mat4 VP = Projection * ViewTranslate;
//======================================
// Added by Sang Yoon to pass the information about viewing frustum and head pose of the detailed view window
// to the composite submodule for the overview window.
// This information is used for drawing a rectangle showing the head orientation of detailed view window in the overview window
if (eye == 0 && m_detailed_view) {
std::lock_guard<std::mutex> lock(g_overview_mutex);
g_detailed_view_translate = ViewTranslate;
g_detailed_view_leftf = leftFrust;
g_detailed_view_rightf = rightFrust;
g_detailed_view_topf = topFrust;
g_detailed_view_bottomf = bottomFrust;
g_detailed_view_nearf = view.nearClip;
}
//======================================
// Call the derived-class method to render the geometry into this viewpoint.
//======================================
// Revised by Sang Yoon to support the cylindrical projection
// Original:
//RenderView(scanOutTime, glm::value_ptr(VP));
// Revised:
RenderView(scanOutTime, glm::value_ptr(VP), glm::value_ptr(ViewTranslate), view);
//======================================
//======================================
// Added by Sang Yoon to fix a bug in drawing a line where the cylindrical projection is used
if (m_overview)
g_overview_translate = ViewTranslate; // This matrix is used in DrawHeadOrientation() method.
//======================================
//======================================
// Added by Sang Yoon to draw a rectangle to show the head orientation of detailed view window in the overview window
// Note that in drawing this rectangle the shiftPoints or PoseAdjuster is not considered.
if (m_overview)
DrawHeadOrientation(view.farClip, view.width); // view.farClip is used for determining a radius of a big sphere.
// view.width (screen width) is used for determining the line thickness of rectangle.
//======================================
}
// Unset things
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Done with the data for a render frame. If the code in this method requires the
// frame rendering to have completed before it returns, it must call glFinish() or
// use a synchronization object to ensure this.
TearDownRenderFrame();
// Wait until the rendering has finished.
glFinish();
}
void Composite::checkShaderError(GLuint shaderId, const std::string& exceptionMsg) {
GLint result = GL_FALSE;
int infoLength = 0;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result);
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLength);
if (result == GL_FALSE) {
std::vector<GLchar> errorMessage(infoLength + 1);
glGetShaderInfoLog(shaderId, infoLength, NULL, &errorMessage[0]);
std::cerr << &errorMessage[0] << std::endl;
throw std::runtime_error(exceptionMsg);
}
}
void Composite::checkProgramError(GLuint programId, const std::string& exceptionMsg) {
GLint result = GL_FALSE;
int infoLength = 0;
glGetProgramiv(programId, GL_LINK_STATUS, &result);
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLength);
if (result == GL_FALSE) {
std::vector<GLchar> errorMessage(infoLength + 1);
glGetProgramInfoLog(programId, infoLength, NULL, &errorMessage[0]);
std::cerr << &errorMessage[0] << std::endl;
throw std::runtime_error(exceptionMsg);
}
}
//==================================================================================================
// Objects needed by the CompositeCube class.
/// @brief Helper class that handles defining and drawing a cube.
class asdp::render::CompositeCube::MeshCube {
public:
MeshCube(GLfloat scale, size_t numTriangles = 6 * 2 * 15 * 15) {
// Figure out how many quads we have per edge. There
// is a minimum of 1.
size_t numQuads = numTriangles / 2;
size_t numQuadsPerFace = numQuads / 6;
size_t numQuadsPerEdge = static_cast<size_t> (sqrt(numQuadsPerFace));
if (numQuadsPerEdge < 1) { numQuadsPerEdge = 1; }
// Construct a white square with the specified number of
// quads as the +Z face of the cube. We'll copy this and
// then multiply by the correct face color, and we'll
// adjust the coordinates by rotation to match each face.
std::vector<GLfloat> whiteBufferData;
std::vector<GLfloat> faceBufferData;
for (size_t i = 0; i < numQuadsPerEdge; i++) {
for (size_t j = 0; j < numQuadsPerEdge; j++) {
// Modulate the color of each quad by a random luminance,
// leaving all vertices the same color.
GLfloat color = 0.5f + rand() * 0.5f / RAND_MAX;
const size_t numTris = 2;
const size_t numColors = 3;
const size_t numVerts = 3;
for (size_t c = 0; c < numColors * numTris * numVerts; c++) {
whiteBufferData.push_back(color);
}
// Send the two triangles that make up this quad, where the
// quad covers the appropriate fraction of the face from
// -scale to scale in X and Y.
GLfloat Z = scale;
GLfloat minX = -scale + i * (2 * scale) / numQuadsPerEdge;
GLfloat maxX = -scale + (i + 1) * (2 * scale) / numQuadsPerEdge;
GLfloat minY = -scale + j * (2 * scale) / numQuadsPerEdge;
GLfloat maxY = -scale + (j + 1) * (2 * scale) / numQuadsPerEdge;
faceBufferData.push_back(minX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(minX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(minX);
faceBufferData.push_back(maxY);
faceBufferData.push_back(Z);
faceBufferData.push_back(maxX);
faceBufferData.push_back(minY);
faceBufferData.push_back(Z);
}
}
// Make a copy of the vertices for each face, then modulate
// the color by the face color and rotate the coordinates to
// put them on the correct cube face.
// +Z is blue and is in the same location as the original
// faces.
{
std::array<GLfloat, 3> modColor = { 0.0, 0.0, 1.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = X, Y = Y, Z = Z
std::array<GLfloat, 3> scales = { 1.0f, 1.0f, 1.0f };
std::array<size_t, 3> indices = { 0, 1, 2 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
// -Z is cyan and is in the opposite size from the
// original face (mirror all 3).
{
std::array<GLfloat, 3> modColor = { 0.0, 1.0, 1.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = -X, Y = -Y, Z = -Z
std::array<GLfloat, 3> scales = { -1.0f, -1.0f, -1.0f };
std::array<size_t, 3> indices = { 0, 1, 2 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
// +X is red and is rotated -90 degrees from the original
// around Y.
{
std::array<GLfloat, 3> modColor = { 1.0, 0.0, 0.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = Z, Y = Y, Z = -X
std::array<GLfloat, 3> scales = { 1.0f, 1.0f, -1.0f };
std::array<size_t, 3> indices = { 2, 1, 0 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
// -X is magenta and is rotated 90 degrees from the original
// around Y.
{
std::array<GLfloat, 3> modColor = { 1.0, 0.0, 1.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = -Z, Y = Y, Z = X
std::array<GLfloat, 3> scales = { -1.0f, 1.0f, 1.0f };
std::array<size_t, 3> indices = { 2, 1, 0 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
// +Y is green and is rotated -90 degrees from the original
// around X.
{
std::array<GLfloat, 3> modColor = { 0.0, 1.0, 0.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = X, Y = Z, Z = -Y
std::array<GLfloat, 3> scales = { 1.0f, 1.0f, -1.0f };
std::array<size_t, 3> indices = { 0, 2, 1 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
// -Y is yellow and is rotated 90 degrees from the original
// around X.
{
std::array<GLfloat, 3> modColor = { 1.0, 1.0, 0.0 };
std::vector<GLfloat> myBufferData =
colorModulate(whiteBufferData, modColor);
// X = X, Y = -Z, Z = Y
std::array<GLfloat, 3> scales = { 1.0f, -1.0f, 1.0f };
std::array<size_t, 3> indices = { 0, 2, 1 };
std::vector<GLfloat> myFaceBufferData =
vertexRotate(faceBufferData, indices, scales);
// Catenate the colors onto the end of the
// color buffer.
colorBufferData.insert(colorBufferData.end(),
myBufferData.begin(), myBufferData.end());
// Catenate the vertices onto the end of the
// vertex buffer.
vertexBufferData.insert(vertexBufferData.end(),
myFaceBufferData.begin(), myFaceBufferData.end());
}
}
~MeshCube() {
if (initialized) {
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &colorBuffer);
}
}
void init() {
if (!initialized) {
// Unbind any vertex array object.
glBindVertexArray(0);
// Vertex buffer
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(vertexBufferData[0]) * vertexBufferData.size(),
vertexBufferData.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Color buffer
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(colorBufferData[0]) * colorBufferData.size(),
colorBufferData.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
initialized = true;
}
}
void draw() {
init();
// Unbind any currently bound vertex array object.
// We cannot use vertex array objects because we're potentially going to be called
// from multiple OpenGL contexts in different threads and VAOs are not shared between
// contexts.
glBindVertexArray(0);
// Enable the vertex attribute arrays we are going to use
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// Bind the vertex buffer object
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
// Bind the color buffer object
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
// Draw our geometry
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexBufferData.size()));
}
private:
MeshCube(const MeshCube&) = delete;
MeshCube& operator=(const MeshCube&) = delete;
bool initialized = false;
GLuint colorBuffer = 0;
GLuint vertexBuffer = 0;
std::vector<GLfloat> colorBufferData;
std::vector<GLfloat> vertexBufferData;
// Multiply each triple of colors by the specified color.
std::vector<GLfloat> colorModulate(std::vector<GLfloat> const& inVec,
std::array<GLfloat, 3> const& clr) {
std::vector<GLfloat> out;
size_t elements = inVec.size() / 3;
if (elements * 3 != inVec.size()) {
// We don't have an even multiple of 3 elements, so bail.
return out;
}
out = inVec;
for (size_t i = 0; i < elements; i++) {
for (size_t c = 0; c < 3; c++) {
out[3 * i + c] *= clr[c];
}
}
return out;
}
// Swizzle each triple of coordinates by the specified
// index and then multiply by the specified scale. This
// lets us implement a poor-man's rotation matrix, where
// we pick which element (0-2) and which polarity (-1 or
// 1) to use.
std::vector<GLfloat> vertexRotate(
std::vector<GLfloat> const& inVec,
std::array<size_t, 3> const& indices,
std::array<GLfloat, 3> const& scales) {
std::vector<GLfloat> out;
size_t elements = inVec.size() / 3;
if (elements * 3 != inVec.size()) {
// We don't have an even multiple of 3 elements, so bail.
return out;
}
out.resize(inVec.size());
for (size_t i = 0; i < elements; i++) {
for (size_t p = 0; p < 3; p++) {
out[3 * i + p] = inVec[3 * i + indices[p]] * scales[p];
}
}
return out;
}
};
static const GLchar* cubeVertexShader =
R"(#version 330 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 vertexColor;
out vec3 fragmentColor;
uniform mat4 modelViewProjection;
//======================================
// Added by Sang Yoon to support a cylindrical projection
uniform int useCP;
uniform float lh_hfov_rad;
uniform float rh_hfov_rad;
uniform float bh_vfov_rad;
uniform float th_vfov_rad;
uniform float near;
uniform float far;
uniform mat4 modelViewMatrix;
//======================================
void main()
{
//======================================
// Revised by Sang Yoon to support a cylindrical projection
// Original: gl_Position = modelViewProjection * vec4(position,1);
// Revised:
if (useCP == 0) {
gl_Position = modelViewProjection * vec4(position,1);
} else {
vec4 p = modelViewMatrix * vec4(position, 1.0);
float length_xz = length(p.xz);
float theta_x = atan(p.x, -p.z); // angle around y axis (angle in horizontal direction)
float theta_y = atan(p.y, length_xz); // angle around bent x axis (angle in vertical direction)
gl_Position = vec4((theta_x - lh_hfov_rad)/(rh_hfov_rad - lh_hfov_rad) * 2.0 - 1.0,
(theta_y - bh_vfov_rad)/(th_vfov_rad - bh_vfov_rad) * 2.0 - 1.0,
(length_xz - near)/(far - near) * 2.0 - 1.0,
1.0);
}
//======================================
fragmentColor = vertexColor;
})";
static const GLchar* cubeFragmentShader =
R"(#version 330 core
in vec3 fragmentColor;
out vec3 color;
void main()
{
color = fragmentColor;
})";
CompositeCube::CompositeCube(double radius)
: Composite()
, m_radius(radius)
, m_programId(0)
, m_modelViewProjectionUniformId(0)
//======================================
// Added by Sang Yoon to pass the parameters for cylindrical projection to GPU
// (separately transfer horizontal FOV, vertical FOV, near, far, projection matrix, and model view matrix to the vertex shader).
, m_useCPUniformId(0)
, m_lh_hfovUniformId(0)
, m_rh_hfovUniformId(0)
, m_bh_vfovUniformId(0)
, m_th_vfovUniformId(0)
, m_nearUniformId(0)
, m_farUniformId(0)
, m_modelViewUniformId(0)
//======================================
{
}
bool CompositeCube::SetupRendering()
{
// Initialize GLEW in our context. It is okay to initialize it more than once.
glewExperimental = true;
if (glewInit() != GLEW_OK) {
std::cerr << "CompositeCube::CompositeCube(): Failed to initialize GLEW" << std::endl;
return false;
}
// Clear any GL error that Glew caused. Apparently on Non-Windows
// platforms, this can cause a spurious error 1280.
glGetError();
try {
// Construct the shader programs.
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
// vertex shader
glShaderSource(vertexShaderId, 1, &cubeVertexShader, NULL);
glCompileShader(vertexShaderId);
checkShaderError(vertexShaderId, "Vertex shader compilation failed.");
// fragment shader
glShaderSource(fragmentShaderId, 1, &cubeFragmentShader, NULL);
glCompileShader(fragmentShaderId);
checkShaderError(fragmentShaderId, "Fragment shader compilation failed.");
// linking shader program
m_programId = glCreateProgram();
glAttachShader(m_programId, vertexShaderId);
glAttachShader(m_programId, fragmentShaderId);
glLinkProgram(m_programId);
checkProgramError(m_programId, "Shader program link failed.");
// once linked into a program, we no longer need the shaders.
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
} catch (std::runtime_error& e) {
std::cerr << "CompositeCube::SetupRendering(): " << e.what() << std::endl;
return false;
}
m_modelViewProjectionUniformId = glGetUniformLocation(m_programId, "modelViewProjection");
//======================================
// Added by Sang Yoon to pass the parameters used in the cylindrical projection to the vertex shader
m_useCPUniformId = glGetUniformLocation(m_programId, "useCP");
m_lh_hfovUniformId = glGetUniformLocation(m_programId, "lh_hfov_rad");
m_rh_hfovUniformId = glGetUniformLocation(m_programId, "rh_hfov_rad");
m_bh_vfovUniformId = glGetUniformLocation(m_programId, "bh_vfov_rad");
m_th_vfovUniformId = glGetUniformLocation(m_programId, "th_vfov_rad");
m_nearUniformId = glGetUniformLocation(m_programId, "near");
m_farUniformId = glGetUniformLocation(m_programId, "far");
m_modelViewUniformId = glGetUniformLocation(m_programId, "modelViewMatrix");
//======================================
// Make our geometry object, which will draw itself. On the XSight, make it monochrome.
size_t quadsPerEdge = 10;
size_t trianglesPerSide = 2 * quadsPerEdge * quadsPerEdge;
// 6 faces
size_t numTriangles = static_cast<size_t>(trianglesPerSide * 6);
m_roomCube = std::shared_ptr<MeshCube>(new MeshCube(m_radius, numTriangles));
return true;
}
CompositeCube::~CompositeCube()
{
glDeleteProgram(m_programId);
}
void CompositeCube::SetupRenderFrame(asdp::Time scanOutTime)
{
}
//======================================
// Revised by Sang Yoon to support the cylindrical projection
// The arguments used for the cylindrical projection are added: modelViewMatrix, hFOVf, vFOVf, nearf, and farf.
void CompositeCube::RenderView(asdp::Time scanOutTime, const float* viewProjection,
const float* modelViewMatrix, const ViewRenderInfo& vri)
{
glUseProgram(m_programId);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
if (!m_CP_enabled) // If the flag for cylindrical projection is not enabled, use the perspective projection
// (following the original execution flow of RenderView()).
{
// Set the model-view-projection matrix and draw the cube.
glUniformMatrix4fv(m_modelViewProjectionUniformId, 1, GL_FALSE, viewProjection);
glUniform1i(m_useCPUniformId, 0);
}
else // If the flag for cylindrical projection is enabled, use the cylindrical projection.
{
glUniform1i(m_useCPUniformId, 1);
glUniform1f(m_lh_hfovUniformId, vri.leftHalfFOV * M_PI / 180.0);
glUniform1f(m_rh_hfovUniformId, vri.rightHalfFOV * M_PI / 180.0);
glUniform1f(m_bh_vfovUniformId, vri.bottomHalfFOV * M_PI / 180.0);
glUniform1f(m_th_vfovUniformId, vri.topHalfFOV * M_PI / 180.0);
glUniform1f(m_nearUniformId, vri.nearClip);
glUniform1f(m_farUniformId, vri.farClip);
glUniformMatrix4fv(m_modelViewUniformId, 1, GL_FALSE, modelViewMatrix);
}
m_roomCube->draw();
}
//======================================
void CompositeCube::TearDownRenderFrame()
{
glUseProgram(0);
}
//======================================
// Added by Sang Yoon to draw a rectangle to show the head orientation of detailed view window in the overview window
void CompositeCube::DrawHeadOrientation(float view_farf, int screen_width)
{
// Do nothing for CompositeCube.
}
//======================================
//==================================================================================================
// Objects needed by the CompositeCameras class.
static const GLchar* camerasVertexShader =
R"(#version 330 core
mat4 axisAngleToMatrix(vec3 axis, float angle)
{
float c = cos(angle);
float s = sin(angle);
float t = 1.0 - c;
float x = axis.x;
float y = axis.y;
float z = axis.z;
mat4 mat = mat4(1.0);
mat[0][0] = t * x * x + c;
mat[0][1] = t * x * y - s * z;
mat[0][2] = t * x * z + s * y;
mat[1][0] = t * x * y + s * z;
mat[1][1] = t * y * y + c;
mat[1][2] = t * y * z - s * x;
mat[2][0] = t * x * z - s * y;
mat[2][1] = t * y * z + s * x;
mat[2][2] = t * z * z + c;
return mat;
}
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
layout (location = 2) in float aVignetteGain;
out vec2 TexCoord;
out float vignetteGain;
out float depthColor;
uniform mat4 viewProjection;
uniform mat4 poseAdjust; ///< Moves points in helicopter space to their capture-time positions.
// The following are for the camera rotation and translation during the frame, and they are
// in the helicopter coordinate system.
uniform vec3 fVelocity; ///< The change in position over a frame time from frame center
uniform vec3 fAxis; ///< The axis around which the camera is rotating during the frame
uniform float fAngle; ///< The angle of rotation around the axis during a frame time in radians
uniform float depthScale; ///< If this is >= 0, scales the depth by this amount and sends to fragment shader.
//======================================
// Added by Sang Yoon to support a cylindrical projection
uniform int useCP;
uniform float lh_hfov_rad;
uniform float rh_hfov_rad;
uniform float bh_vfov_rad;
uniform float th_vfov_rad;
uniform float near;
uniform float far;
uniform mat4 modelViewMatrix;
//======================================
void main()
{
// Determine the time within a frame that this vertex is being rendered.
// The center vertex (Y texture coordinate 0.5) is at time 0, the top at -0.5, the bottom at 0.5.
// Because the Y texture coordinate is 0 at the top, we need to invert it.
float time = -(aTexCoord.y - 0.5);
// Construct a rotation matrix for the camera's rotation around the axis during a frame time.
mat4 delta = axisAngleToMatrix(fAxis, fAngle * time);
// Add the scaled velocity as a translation to the position in this matrix.
vec3 shift = fVelocity * time;
delta[3][0] = shift.x;
delta[3][1] = shift.y;
delta[3][2] = shift.z;
// Apply the matrices to the position to get the final projected position.
// Perform the within-frame distortion first (it is in helicopter space), then the pose adjustment
// (to previous helicopter space), and finally the view+projection.
//======================================
// Revised by Sang Yoon to support a cylindrical projection
// Original: gl_Position = viewProjection * poseAdjust * delta * vec4(aPos, 1.0);
// Revised:
if (useCP == 0) {
gl_Position = viewProjection * poseAdjust * delta * vec4(aPos, 1.0);
} else {
//======================================
// Revised by Sang Yoon to fix a bug in drawing a line where the cylindrical projection is used
// Original: vec4 p = modelViewMatrix * poseAdjust * delta * vec4(aPos, 1.0);
// Revised:
vec4 p = modelViewMatrix * vec4(aPos, 1.0);
//======================================
float length_xz = length(p.xz);
float theta_x = atan(p.x, -p.z); // angle around y axis (angle in horizontal direction)
float theta_y = atan(p.y, length_xz); // angle around bent x axis (angle in vertical direction)
gl_Position = vec4((theta_x - lh_hfov_rad)/(rh_hfov_rad - lh_hfov_rad) * 2.0 - 1.0,
(theta_y - bh_vfov_rad)/(th_vfov_rad - bh_vfov_rad) * 2.0 - 1.0,
(length_xz - near)/(far - near) * 2.0 - 1.0,
1.0);
}
//======================================
// Pass the texture coordinate and vignette gain to the fragment shader.
TexCoord = vec2(aTexCoord.x, aTexCoord.y);
vignetteGain = aVignetteGain;
// If we are scaling the depth, do it here. Otherwise, send -1
depthColor = depthScale >= 0.0 ? gl_Position.z * depthScale : -1.0f;
})";
static const GLchar* camerasFragmentShader =
R"(#version 330 core
out vec4 FragColor;
in vec2 TexCoord;
in float vignetteGain;
in float depthColor;
uniform sampler2D imageTexture;
uniform sampler1D toneMapTexture;
uniform float offset;
uniform float gain;
uniform float depthScale; ///< If this is >= 0, scales the depth by this amount and sends to fragment shader.
void main()
{
if (depthScale >= 0.0) {
// If the depth value has been set to a non-negative value, use it as the color.
FragColor = vec4(depthColor, depthColor, depthColor, 1.0);
} else {
// Look up the intensity from the image texture and then use the tone map to get the color.
// Apply offset, gain, and vignette gain. The texture sampler should be set to GL_CLAMP_TO_EDGE.
float intensity = vignetteGain * gain * (offset + texture(imageTexture, TexCoord).r);
FragColor = texture(toneMapTexture, intensity);
}
})";
CompositeCameras::CompositeCameras(std::vector< std::shared_ptr<CameraRenderInfo> >& cameraRenderInfo, GLuint toneMaptexture,
std::shared_ptr<PoseAdjuster> poseAdjuster, Time cameraFrameInterval,
uint32_t renderOffsetMicroseconds, Time renderFrameInterval, RenderTimingInfo *renderTimingInfo,
std::shared_ptr<asdp::render::RangeEstimator> rangeEstimator,
double defaultStaticDepth,
AnnotationCallbackFunction annotationCallback, void* annotationUserData)
: Composite()
, m_cameraRenderInfos(cameraRenderInfo)
, m_toneMapTexture(toneMaptexture)
, m_poseAdjuster(poseAdjuster)
, m_cameraFrameInterval(cameraFrameInterval)
, m_renderOffsetMicroseconds(renderOffsetMicroseconds)
, m_renderFrameInterval(renderFrameInterval)
, m_renderTimingInfo(renderTimingInfo)
, m_rangeEstimator(rangeEstimator)
, m_defaultStaticDepth(defaultStaticDepth)
, m_annotationCallback(annotationCallback)
, m_annotationUserData(annotationUserData)
, m_programId(0)
, m_viewProjectionUniformId(0)
, m_poseAdjustUniformId(0)
, m_fVelocityUniformID(0)
, m_fAxisUniformID(0)
, m_fAngleUniformID(0)
, m_offsetUniformID(0)
, m_gainUniformID(0)
, m_depthScaleUniformID(0)
, m_globalExposureGain(cameraFrameInterval.seconds + cameraFrameInterval.microseconds * 1e-6)
, m_imageTextureId(0)
, m_toneMapTextureId(0)
//======================================
// Added by Sang Yoon to pass the parameters for cylindrical projection to GPU
// (separately transfer horizontal FOV, vertical FOV, near, far, projection matrix, and model view matrix to the vertex shader).
, m_useCPUniformId(0)
, m_lh_hfovUniformId(0)
, m_rh_hfovUniformId(0)
, m_bh_vfovUniformId(0)
, m_th_vfovUniformId(0)
, m_nearUniformId(0)
, m_farUniformId(0)
, m_modelViewUniformId(0)
//======================================
//======================================
// Added by Sang Yoon to specificy the color of retangle indicating the head orientation of detailed view in the overview window
, m_head_orientation_colorTexture(0)
, m_head_orientation_toneMapTexture(0)
//======================================
{
}
bool CompositeCameras::SetupRendering()
{
// Initialize GLEW in our context. It is okay to initialize it more than once.
// NOTE: SetupRendering() is only called once for each object if it works, so we won't be initializing
// GLEW every render frame here, only once per CompositeCameras object.
glewExperimental = true;
GLenum ret = glewInit();
if (ret != GLEW_OK) {
std::cerr << "CompositeCameras::SetupRendering(): Failed to initialize GLEW: " << ret << std::endl;
return false;
}
// Clear any GL error that Glew caused. Apparently on Non-Windows
// platforms, this can cause a spurious error 1280.
glGetError();
// Construct a RenderText and RenderHaloedLines object for drawing text annotations.
try {
// Set the width and height to something small; we will resize it later.
m_renderText = std::shared_ptr<asdp::render::RenderText>(new asdp::render::RenderText(10,10));
m_renderHaloedLines = std::shared_ptr<asdp::render::RenderHaloedLines>(new asdp::render::RenderHaloedLines());
} catch (std::runtime_error& e) {
std::cerr << "CompositeCameras::SetupRendering(): Failed to create RenderText and RenderHaloedLines objects: " << e.what() << std::endl;
}
// Construct the shader programs.
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
try {
// vertex shader
glShaderSource(vertexShaderId, 1, &camerasVertexShader, NULL);
glCompileShader(vertexShaderId);
checkShaderError(vertexShaderId, "Vertex shader compilation failed.");
// fragment shader
glShaderSource(fragmentShaderId, 1, &camerasFragmentShader, NULL);
glCompileShader(fragmentShaderId);
checkShaderError(fragmentShaderId, "Fragment shader compilation failed.");
// linking shader program
m_programId = glCreateProgram();
glAttachShader(m_programId, vertexShaderId);
glAttachShader(m_programId, fragmentShaderId);
glLinkProgram(m_programId);
checkProgramError(m_programId, "Shader program link failed.");
// once linked into a program, we no longer need the shaders.
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
} catch (std::runtime_error& e) {
std::cerr << "CompositeCameras::SetupRendering(): " << e.what() << std::endl;
return false;
}
// Get the IDs for all of the uniform parameters we will want to change.
m_viewProjectionUniformId = glGetUniformLocation(m_programId, "viewProjection");
m_poseAdjustUniformId = glGetUniformLocation(m_programId, "poseAdjust");
m_fVelocityUniformID = glGetUniformLocation(m_programId, "fVelocity");
m_fAxisUniformID = glGetUniformLocation(m_programId, "fAxis");
m_fAngleUniformID = glGetUniformLocation(m_programId, "fAngle");
m_offsetUniformID = glGetUniformLocation(m_programId, "offset");
m_gainUniformID = glGetUniformLocation(m_programId, "gain");
m_depthScaleUniformID = glGetUniformLocation(m_programId, "depthScale");
m_imageTextureId = glGetUniformLocation(m_programId, "imageTexture");
m_toneMapTextureId = glGetUniformLocation(m_programId, "toneMapTexture");
if (m_viewProjectionUniformId == -1 || m_poseAdjustUniformId == -1 || m_fVelocityUniformID == -1 ||
m_fAxisUniformID == -1 || m_fAngleUniformID == -1 || m_imageTextureId == -1 || m_toneMapTextureId == -1 ||
m_offsetUniformID == -1 || m_gainUniformID == -1 || m_depthScaleUniformID == -1) {
std::cerr << "CompositeCameras::SetupRendering(): Failed to get uniform IDs" << std::endl;
std::cerr << " viewProjection: " << m_viewProjectionUniformId << std::endl;
std::cerr << " poseAdjust: " << m_poseAdjustUniformId << std::endl;
std::cerr << " fVelocity: " << m_fVelocityUniformID << std::endl;
std::cerr << " fAxis: " << m_fAxisUniformID << std::endl;
std::cerr << " fAngle: " << m_fAngleUniformID << std::endl;
std::cerr << " offset: " << m_offsetUniformID << std::endl;