-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSandboxClient.cpp
More file actions
1614 lines (1411 loc) · 59.5 KB
/
Copy pathSandboxClient.cpp
File metadata and controls
1614 lines (1411 loc) · 59.5 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
/***********************************************************************
SandboxClient - Vrui application connect to a remote AR Sandbox and
render its bathymetry and water level.
Copyright (c) 2019-2026 Oliver Kreylos
This file is part of the Augmented Reality Sandbox (SARndbox).
The Augmented Reality Sandbox is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The Augmented Reality Sandbox is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with the Augmented Reality Sandbox; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#include "SandboxClient.h"
#include <string>
#include <stdexcept>
#include <iostream>
#include <Misc/PrintInteger.h>
#include <Misc/FunctionCalls.h>
#include <Misc/MessageLogger.h>
#include <Comm/TCPPipe.h>
#include <Math/Math.h>
#include <Geometry/LinearUnit.h>
#include <GL/gl.h>
#include <GL/GLMaterialTemplates.h>
#include <GL/GLMiscTemplates.h>
#include <GL/GLLightTracker.h>
#include <GL/GLContextData.h>
#include <GL/Extensions/GLARBDepthClamp.h>
#include <GL/Extensions/GLARBDepthTexture.h>
#include <GL/Extensions/GLARBFragmentShader.h>
#include <GL/Extensions/GLARBShadow.h>
#include <GL/Extensions/GLARBTextureFloat.h>
#include <GL/Extensions/GLARBTextureRectangle.h>
#include <GL/Extensions/GLARBTextureRg.h>
#include <GL/Extensions/GLARBVertexBufferObject.h>
#include <GL/Extensions/GLARBVertexShader.h>
#include <GL/GLModels.h>
#include <GL/GLGeometryWrappers.h>
#include <GL/GLTransformationWrappers.h>
#include <Vrui/Viewer.h>
#include <Vrui/CoordinateManager.h>
#include <Vrui/Lightsource.h>
#include <Vrui/LightsourceManager.h>
#include <Vrui/ToolManager.h>
#include <Vrui/DisplayState.h>
#include "TextureTracker.h"
#include "ElevationColorMap.h"
/****************************************************
Static eleemnts of class SandboxClient::TeleportTool:
****************************************************/
SandboxClient::TeleportToolFactory* SandboxClient::TeleportTool::factory=0;
/********************************************
Methods of class SandboxClient::TeleportTool:
********************************************/
void SandboxClient::TeleportTool::applyNavState(void) const
{
/* Compose and apply the navigation transformation: */
Vrui::NavTransform nav=physicalFrame;
nav*=Vrui::NavTransform::rotate(Vrui::Rotation::rotateZ(azimuth));
nav*=Geometry::invert(surfaceFrame);
Vrui::setNavigationTransformation(nav);
}
void SandboxClient::TeleportTool::initNavState(void)
{
/* Calculate the main viewer's current head and foot positions: */
Point headPos=Vrui::getMainViewer()->getHeadPosition();
footPos=Vrui::calcFloorPoint(headPos);
headHeight=Geometry::dist(headPos,footPos);
/* Set up a physical navigation frame around the main viewer's current head position: */
calcPhysicalFrame(headPos);
/* Calculate the initial environment-aligned surface frame in navigation coordinates: */
surfaceFrame=Vrui::getInverseNavigationTransformation()*physicalFrame;
Vrui::NavTransform newSurfaceFrame=surfaceFrame;
/* Align the initial frame with the application's surface and calculate Euler angles: */
AlignmentData ad(surfaceFrame,newSurfaceFrame,Vrui::getMeterFactor()*Scalar(0.25),Vrui::getMeterFactor());
Scalar elevation,roll;
align(ad,azimuth,elevation,roll);
/* Move the physical frame to the foot position, and adjust the surface frame accordingly: */
newSurfaceFrame*=Geometry::invert(physicalFrame)*Vrui::NavTransform::translate(footPos-headPos)*physicalFrame;
physicalFrame.leftMultiply(Vrui::NavTransform::translate(footPos-headPos));
/* Apply the initial navigation state: */
surfaceFrame=newSurfaceFrame;
applyNavState();
}
void SandboxClient::TeleportTool::initClass(void)
{
/* Create a factory object for the teleporting tool class: */
factory=new TeleportToolFactory("TeleportTool","Teleport",Vrui::getToolManager()->loadClass("SurfaceNavigationTool"),*Vrui::getToolManager());
/* Set the teleport tool class' input layout: */
factory->setNumButtons(2);
factory->setButtonFunction(0,"Toggle");
factory->setButtonFunction(1,"Teleport");
/* Register the teleport tool class with Vrui's tool manager: */
Vrui::getToolManager()->addClass(factory,Vrui::ToolManager::defaultToolFactoryDestructor);
}
SandboxClient::TeleportTool::TeleportTool(const Vrui::ToolFactory* factory,const Vrui::ToolInputAssignment& inputAssignment)
:Vrui::SurfaceNavigationTool(factory,inputAssignment),
cast(false)
{
sphereRenderer.setVariableRadius();
cylinderRenderer.setVariableRadius();
}
SandboxClient::TeleportTool::~TeleportTool(void)
{
}
const Vrui::ToolFactory* SandboxClient::TeleportTool::getFactory(void) const
{
return factory;
}
void SandboxClient::TeleportTool::buttonCallback(int buttonSlotIndex,Vrui::InputDevice::ButtonCallbackData* cbData)
{
switch(buttonSlotIndex)
{
case 0:
if(cbData->newButtonState) // Button has just been pressed
{
/* Act depending on this tool's current state: */
if(isActive())
{
if(!cast)
{
/* Deactivate this tool: */
deactivate();
}
}
else
{
/* Try activating this tool: */
if(activate())
{
/* Initialize the navigation state: */
initNavState();
}
}
}
break;
case 1:
if(isActive())
{
if(cbData->newButtonState)
cast=true;
else
{
/* Teleport to the end of the cast arc if there is one: */
if(!castArc.empty())
surfaceFrame.leftMultiply(Vrui::NavTransform::translate(castArc.back()-surfaceFrame.getOrigin()));
cast=false;
}
}
break;
}
}
void SandboxClient::TeleportTool::frame(void)
{
if(isActive())
{
/* Calculate the new head and foot positions: */
Point newHead=Vrui::getMainViewer()->getHeadPosition();
Point newFootPos=Vrui::calcFloorPoint(newHead);
headHeight=Geometry::dist(newHead,newFootPos);
/* Create a physical navigation frame around the new foot position: */
calcPhysicalFrame(newFootPos);
/* Calculate the movement from walking: */
Vector move=newFootPos-footPos;
footPos=newFootPos;
/* Transform the movement vector from physical space to the physical navigation frame: */
move=physicalFrame.inverseTransform(move);
/* Rotate by the current azimuth angle: */
move=Vrui::Rotation::rotateZ(-azimuth).transform(move);
/* Move the surface frame: */
Vrui::NavTransform newSurfaceFrame=surfaceFrame;
newSurfaceFrame*=Vrui::NavTransform::translate(move);
/* Re-align the surface frame with the surface: */
AlignmentData ad(surfaceFrame,newSurfaceFrame,Vrui::getMeterFactor()*Scalar(0.25),Vrui::getMeterFactor());
align(ad);
/* Apply the newly aligned surface frame: */
surfaceFrame=newSurfaceFrame;
applyNavState();
if(cast)
{
/* Establish boundaries of the castable area: */
Scalar xMin=application->bDomain.min[0];
Scalar xMax=application->bDomain.max[0];
Scalar yMin=application->bDomain.min[1];
Scalar yMax=application->bDomain.max[1];
/* Cast an arc from the current input device position: */
castArc.clear();
Point cp=Vrui::getInverseNavigationTransformation().transform(getButtonDevicePosition(1));
Vector cv=Vrui::getInverseNavigationTransformation().transform(getButtonDeviceRayDirection(1)*(Vrui::getMeterFactor()*Scalar(10)));
Vector ca(0,0,-Vrui::getInverseNavigationTransformation().getScaling()*Vrui::getMeterFactor()*Scalar(9.81));
/* Check if the cast is potentially valid: */
if((cp[0]>=xMin||cv[0]>Scalar(0))&&(cp[0]<=xMax||cv[0]<Scalar(0))&&(cp[1]>=yMin||cv[1]>Scalar(0))&&(cp[1]<=yMax||cv[1]<Scalar(0)))
{
castArc.push_back(cp);
Scalar stepSize(0.05);
for(int i=0;i<100;++i)
{
Point cpn=cp+cv*stepSize;
/* Limit casting to the valid bathymetry area: */
Vector normal=Vector::zero;
Scalar lambda(1);
if(cp[0]>=xMin&&cpn[0]<xMin)
{
Scalar l=(xMin-cp[0])/(cpn[0]-cp[0]);
if(lambda>l)
{
normal=Vector(1,0,0);
lambda=l;
}
}
if(cp[0]<=xMax&&cpn[0]>xMax)
{
Scalar l=(xMax-cp[0])/(cpn[0]-cp[0]);
if(lambda>l)
{
normal=Vector(-1,0,0);
lambda=l;
}
}
if(cp[1]>=yMin&&cpn[1]<yMin)
{
Scalar l=(yMin-cp[1])/(cpn[1]-cp[1]);
if(lambda>l)
{
normal=Vector(0,1,0);
lambda=l;
}
}
if(cp[1]<=yMax&&cpn[1]>yMax)
{
Scalar l=(yMax-cp[1])/(cpn[1]-cp[1]);
if(lambda>l)
{
normal=Vector(0,-1,0);
lambda=l;
}
}
/* Intersect the arc with the bathymetry: */
Scalar l=application->intersectLine(cp,cpn);
if(lambda>l)
{
normal=Vector::zero;
lambda=l;
}
if(lambda<Scalar(1))
{
cpn=Geometry::affineCombination(cp,cpn,lambda);
/* Stop casting if the arc hit the ground; otherwise, reflect the arc: */
if(normal==Vector::zero)
{
castArc.push_back(cpn);
break;
}
else
{
// cv-=normal*(Scalar(2)*(cv*normal)); // Fully elastic reflection
cv-=normal*(cv*normal); // Fully inelastic reflection
}
}
castArc.push_back(cpn);
cp=cpn;
cv+=ca*(stepSize*lambda);
}
}
}
}
}
void SandboxClient::TeleportTool::display(GLContextData& contextData) const
{
if(isActive()&&cast&&!castArc.empty())
{
/* Draw the cast arc: */
Vrui::goToNavigationalSpace(contextData);
Scalar radius=Vrui::getInchFactor()*Scalar(1)*Vrui::getInverseNavigationTransformation().getScaling();
glMaterialAmbientAndDiffuse(GLMaterialEnums::FRONT,GLColor<GLfloat,4>(0.0f,1.0f,0.0f));
glMaterialSpecular(GLMaterialEnums::FRONT,GLColor<GLfloat,4>(0.333f,0.333f,0.333f));
glMaterialShininess(GLMaterialEnums::FRONT,32.0f);
glMaterialEmission(GLMaterialEnums::FRONT,GLColor<GLfloat,4>(1.0f,0.0f,0.0f));
sphereRenderer.enable(Vrui::getNavigationTransformation().getScaling(),contextData);
glBegin(GL_POINTS);
for(std::vector<Point>::const_iterator caIt=castArc.begin();caIt!=castArc.end();++caIt)
glVertex4f((*caIt)[0],(*caIt)[1],(*caIt)[2],radius);
glVertex4f(castArc.back()[0],castArc.back()[1],castArc.back()[2],Vrui::getMeterFactor()*Scalar(0.125)*Vrui::getInverseNavigationTransformation().getScaling());
glEnd();
sphereRenderer.disable(contextData);
cylinderRenderer.enable(Vrui::getNavigationTransformation().getScaling(),contextData);
glBegin(GL_LINE_STRIP);
for(std::vector<Point>::const_iterator caIt=castArc.begin();caIt!=castArc.end();++caIt)
glVertex4f((*caIt)[0],(*caIt)[1],(*caIt)[2],radius);
glEnd();
cylinderRenderer.disable(contextData);
glPopMatrix();
}
}
/****************************************
Methods of class SandboxClient::DataItem:
****************************************/
SandboxClient::DataItem::DataItem(void)
:bathymetryTexture(0),waterTexture(0),snowTexture(0),textureVersion(0),
depthTexture(0),depthTextureSize(0,0),
bathymetryVertexBuffer(0),bathymetryIndexBuffer(0),
waterVertexBuffer(0),waterIndexBuffer(0),
lightStateVersion(0)
{
/* Initialize required OpenGL extensions: */
GLARBDepthClamp::initExtension();
GLARBDepthTexture::initExtension();
GLARBFragmentShader::initExtension();
GLARBShaderObjects::initExtension();
GLARBShadow::initExtension();
GLARBTextureFloat::initExtension();
GLARBTextureRectangle::initExtension();
GLARBTextureRg::initExtension();
GLARBVertexBufferObject::initExtension();
GLARBVertexShader::initExtension();
Shader::initExtensions();
TextureTracker::initExtensions();
/* Create texture objects: */
GLuint textures[4];
glGenTextures(4,textures);
bathymetryTexture=textures[0];
waterTexture=textures[1];
snowTexture=textures[2];
depthTexture=textures[3];
/* Create buffer objects: */
GLuint buffers[4];
glGenBuffersARB(4,buffers);
bathymetryVertexBuffer=buffers[0];
bathymetryIndexBuffer=buffers[1];
waterVertexBuffer=buffers[2];
waterIndexBuffer=buffers[3];
}
SandboxClient::DataItem::~DataItem(void)
{
/* Destroy texture objects: */
GLuint textures[4];
textures[0]=bathymetryTexture;
textures[1]=waterTexture;
textures[2]=waterTexture;
textures[3]=depthTexture;
glDeleteTextures(4,textures);
/* Destroy buffer objects: */
GLuint buffers[4];
buffers[0]=bathymetryVertexBuffer;
buffers[1]=bathymetryIndexBuffer;
buffers[2]=waterVertexBuffer;
buffers[3]=waterIndexBuffer;
glDeleteBuffersARB(4,buffers);
}
/******************************
Methods of class SandboxClient:
******************************/
SandboxClient::Scalar SandboxClient::intersectLine(const SandboxClient::Point& p0,const SandboxClient::Point& p1) const
{
/* Convert the points to grid coordinates: */
Point gp0(p0[0]/cellSize[0]-Scalar(1),p0[1]/cellSize[1]-Scalar(1),p0[2]);
Point gp1(p1[0]/cellSize[0]-Scalar(1),p1[1]/cellSize[1]-Scalar(1),p1[2]);
Vector gd=gp1-gp0;
/* Clip the line segment against the grid's boundaries: */
Scalar l0(0);
Scalar l1(1);
for(int i=0;i<2;++i)
{
/* Clip against the lower boundary: */
Scalar b(0);
if(gp0[i]<b)
{
if(gp1[i]>b)
l0=Math::max(l0,(b-gp0[i])/gd[i]);
else
return Scalar(1);
}
else if(gp1[i]<b)
{
if(gp0[i]>b)
l1=Math::min(l1,(b-gp0[i])/gd[i]);
else
return Scalar(1);
}
/* Clip against the upper boundary: */
b=Scalar(bSize[i]-1);
if(gp0[i]>b)
{
if(gp1[i]<b)
l0=Math::max(l0,(b-gp0[i])/gd[i]);
else
return Scalar(1);
}
else if(gp1[i]>b)
{
if(gp0[i]<b)
l1=Math::min(l1,(b-gp0[i])/gd[i]);
else
return Scalar(1);
}
}
if(l0>=l1)
return Scalar(1);
/* Find the grid cell containing the first point: */
Point gp=Geometry::affineCombination(gp0,gp1,l0);
unsigned int cp[2];
for(int i=0;i<2;++i)
cp[i]=Math::clamp(int(Math::floor(gp[i])),int(0),int(bSize[i])-2);
Scalar cl0=l0;
while(cl0<l1)
{
/* Calculate the line parameter where the line segment leaves the current cell: */
Scalar cl1=l1;
int exit=-1;
for(int i=0;i<2;++i)
{
Scalar el=cl1;
if(gp0[i]<gp1[i])
el=(Scalar(cp[i]+1)-gp0[i])/gd[i];
else if(gp0[i]>gp1[i])
el=(Scalar(cp[i])-gp0[i])/gd[i];
if(cl1>el)
{
cl1=el;
exit=i;
}
}
/* Intersect the line segment with the surface inside the current cell: */
const RemoteClient::GridScalar* cell=remoteClient->getBathymetryGrid()+(cp[1]*bSize[0]+cp[0]);
Scalar c0=cell[0];
Scalar c1=cell[1];
Scalar c2=cell[bSize[0]];
Scalar c3=cell[bSize[0]+1];
Scalar cx0=Scalar(cp[0]);
Scalar cx1=Scalar(cp[0]+1);
Scalar cy0=Scalar(cp[1]);
Scalar cy1=Scalar(cp[1]+1);
Scalar fxy=c0-c1+c3-c2;
Scalar fx=(c1-c0)*cy1-(c3-c2)*cy0;
Scalar fy=(c2-c0)*cx1-(c3-c1)*cx0;
Scalar f=(c0*cx1-c1*cx0)*cy1-(c2*cx1-c3*cx0)*cy0;
Scalar a=fxy*gd[0]*gd[1];
Scalar bc0=(fxy*gp0[1]+fx);
Scalar bc1=(fxy*gp0[0]+fy);
Scalar b=bc0*gd[0]+bc1*gd[1]-gd[2];
Scalar c=bc0*gp0[0]+bc1*gp0[1]-gp0[2]-fxy*gp0[0]*gp0[1]+f;
Scalar il=cl1;
if(a!=Scalar(0))
{
/* Solve the quadratic equation and use the smaller valid solution: */
Scalar det=b*b-Scalar(4)*a*c;
if(det>=Scalar(0))
{
det=Math::sqrt(det);
if(a>Scalar(0))
{
/* Test the smaller intersection first: */
il=b>=Scalar(0)?(-b-det)/(Scalar(2)*a):(Scalar(2)*c)/(-b+det);
if(il<cl0)
il=b>=Scalar(0)?(Scalar(2)*c)/(-b-det):(-b+det)/(Scalar(2)*a);
}
else
{
/* Test the smaller intersection first: */
il=b>=Scalar(0)?(Scalar(2)*c)/(-b-det):(-b+det)/(Scalar(2)*a);
if(il<cl0)
il=b>=Scalar(0)?(-b-det)/(Scalar(2)*a):(Scalar(2)*c)/(-b+det);
}
}
}
else
{
/* Solve the linear equation: */
il=-c/b;
}
/* Check if the intersection is valid: */
if(il>=cl0&&il<cl1)
return il;
/* Go to the next cell: */
if(exit>=0)
{
if(gd[exit]<Scalar(0))
--cp[exit];
else
++cp[exit];
}
cl0=cl1;
}
return Scalar(1);
}
void SandboxClient::serverMessageCallback(Threads::EventDispatcher::IOEvent& event)
{
SandboxClient* thisPtr=static_cast<SandboxClient*>(event.getUserData());
try
{
/* Let the remote client process the update message: */
thisPtr->remoteClient->processUpdate();
}
catch(const std::runtime_error&)
{
/* Show an error message and disconnect from the remote AR Sandbox: */
Misc::sourcedUserError(__PRETTY_FUNCTION__,"Disconnected from remote AR Sandbox");
event.removeListener();
thisPtr->connected=false;
}
/* Request a new frame: */
Vrui::requestUpdate();
}
void SandboxClient::alignSurfaceFrame(Vrui::SurfaceNavigationTool::AlignmentData& alignmentData)
{
/* Get the frame's base point: */
Point base=alignmentData.surfaceFrame.getOrigin();
/* Snap the base point to the currently locked bathymetry grid: */
base[2]=remoteClient->calcBathymetry(base[0],base[1]);
/* Align the frame with the bathymetry surface's x and y directions: */
alignmentData.surfaceFrame=Vrui::NavTransform(base-Point::origin,Vrui::Rotation::identity,alignmentData.surfaceFrame.getScaling());
}
void SandboxClient::compileShaders(SandboxClient::DataItem* dataItem,const GLLightTracker& lightTracker) const
{
/*********************************************************************
Compile and link the bathymetry shader:
*********************************************************************/
{
Shader& shader=dataItem->bathymetryShader;
/* Create the vertex shader source code: */
std::string vertexShaderDefines="\
#extension GL_ARB_texture_rectangle : enable\n";
std::string vertexShaderFunctions;
std::string vertexShaderUniforms="\
uniform sampler2DRect bathymetrySampler; // Sampler for the bathymetry texture\n\
uniform vec2 bathymetryCellSize; // Cell size of the bathymetry grid\n";
if(elevationColorMap!=0)
{
vertexShaderUniforms+="\
uniform sampler1D elevationColorMapSampler; // Sampler for the elevation color map texture\n\
uniform vec2 elevationColorMapScale; // Scale and offset to sample the elevation color map\n";
}
std::string vertexShaderVaryings="\
varying float dist; // Eye-space distance to vertex for fogging\n";
std::string vertexShaderMain="\
void main()\n\
{\n\
/* Get the vertex's grid-space z coordinate from the bathymetry texture: */\n\
vec4 vertexGc=gl_Vertex;\n\
vertexGc.z=texture2DRect(bathymetrySampler,vertexGc.xy).r;\n\
\n\
/* Calculate the vertex's grid-space normal vector: */\n\
vec3 normalGc;\n\
normalGc.x=(texture2DRect(bathymetrySampler,vec2(vertexGc.x-1.0,vertexGc.y)).r-texture2DRect(bathymetrySampler,vec2(vertexGc.x+1.0,vertexGc.y)).r)*bathymetryCellSize.y;\n\
normalGc.y=(texture2DRect(bathymetrySampler,vec2(vertexGc.x,vertexGc.y-1.0)).r-texture2DRect(bathymetrySampler,vec2(vertexGc.x,vertexGc.y+1.0)).r)*bathymetryCellSize.x;\n\
normalGc.z=2.0*bathymetryCellSize.x*bathymetryCellSize.y;\n\
\n\
/* Transform the vertex and its normal vector from grid space to eye space for illumination: */\n\
vertexGc.x=(vertexGc.x+0.5)*bathymetryCellSize.x;\n\
vertexGc.y=(vertexGc.y+0.5)*bathymetryCellSize.y;\n\
vec4 vertexEc=gl_ModelViewMatrix*vertexGc;\n\
vec3 normalEc=normalize(gl_NormalMatrix*normalGc);\n\
\n\
/* Initialize the vertex color accumulators: */\n";
if(elevationColorMap!=0)
{
vertexShaderMain+="\
/* Look up the elevation color map value: */\n\
vec4 elevationColor=texture1D(elevationColorMapSampler,vertexGc.z*elevationColorMapScale.x+elevationColorMapScale.y);\n\
vec4 ambDiff=gl_LightModel.ambient*elevationColor;\n";
}
else
{
vertexShaderMain+="\
vec4 ambDiff=gl_LightModel.ambient*gl_FrontMaterial.ambient;\n";
}
vertexShaderMain+="\
vec4 spec=vec4(0.0,0.0,0.0,0.0);\n\
\n\
/* Accumulate all enabled light sources: */\n";
/* Create light application functions for all enabled light sources: */
for(int lightIndex=0;lightIndex<lightTracker.getMaxNumLights();++lightIndex)
if(lightTracker.getLightState(lightIndex).isEnabled())
{
/* Create the light accumulation function: */
vertexShaderFunctions+=lightTracker.createAccumulateLightFunction(lightIndex);
/* Call the light application function from the bathymetry vertex shader's main function: */
vertexShaderMain+="\
accumulateLight";
char liBuffer[12];
vertexShaderMain.append(Misc::print(lightIndex,liBuffer+11));
if(elevationColorMap!=0)
vertexShaderMain+="(vertexEc,normalEc,elevationColor,elevationColor,gl_FrontMaterial.specular,gl_FrontMaterial.shininess,ambDiff,spec);\n";
else
vertexShaderMain+="(vertexEc,normalEc,gl_FrontMaterial.ambient,gl_FrontMaterial.diffuse,gl_FrontMaterial.specular,gl_FrontMaterial.shininess,ambDiff,spec);\n";
}
/* Finalize the vertex shader's main function: */
vertexShaderMain+="\
dist=length(vertexEc.xyz);\n\
gl_FrontColor=ambDiff+spec;\n\
gl_Position=gl_ModelViewProjectionMatrix*vertexGc;\n\
}\n";
/* Compile the vertex shader: */
shader.addShader(glCompileVertexShaderFromStrings(5,vertexShaderDefines.c_str(),vertexShaderFunctions.c_str(),vertexShaderUniforms.c_str(),vertexShaderVaryings.c_str(),vertexShaderMain.c_str()));
/* Create the fragment shader source code: */
std::string fragmentShaderMain="\
uniform vec4 waterColor; // Color of water surface for fogging\n\
uniform float waterOpacity; // Opacity of water for fogging\n\
\n\
varying float dist; // Eye-space distance to vertex for fogging\n\
\n\
void main()\n\
{\n\
gl_FragColor=mix(waterColor,gl_Color,exp(-dist*waterOpacity));\n\
}\n";
/* Compile the fragment shader: */
shader.addShader(glCompileFragmentShaderFromString(fragmentShaderMain.c_str()));
/* Link the shader program: */
shader.link();
/* Retrieve the bathymetry shader program's uniform variable locations: */
shader.setUniformLocation("bathymetrySampler");
shader.setUniformLocation("bathymetryCellSize");
shader.setUniformLocation("waterColor");
shader.setUniformLocation("waterOpacity");
if(elevationColorMap!=0)
{
shader.setUniformLocation("elevationColorMapSampler");
shader.setUniformLocation("elevationColorMapScale");
}
}
/*********************************************************************
Compile and link the opaque water shader:
*********************************************************************/
{
Shader& shader=dataItem->opaqueWaterShader;
/* Create the vertex shader source code: */
std::string vertexShaderDefines="\
#extension GL_ARB_texture_rectangle : enable\n";
std::string vertexShaderFunctions;
std::string vertexShaderVaryings="\
varying float vertexWaterDepth; // Water depth at a surface's vertex\n";
std::string vertexShaderUniforms="\
uniform sampler2DRect waterSampler; // Sampler for the water surface texture\n\
uniform sampler2DRect bathymetrySampler; // Sampler for the bathymetry texture\n\
uniform vec2 waterCellSize; // Cell size of the water surface grid\n";
std::string vertexShaderMain="\
void main()\n\
{\n\
/* Get the vertex's grid-space z coordinate from the water surface texture: */\n\
vec4 vertexGc=gl_Vertex;\n\
vertexGc.z=texture2DRect(waterSampler,vertexGc.xy).r;\n\
\n\
/* Calculate the vertex's grid-space normal vector: */\n\
vec3 normalGc;\n\
normalGc.x=(texture2DRect(waterSampler,vec2(vertexGc.x-1.0,vertexGc.y)).r-texture2DRect(waterSampler,vec2(vertexGc.x+1.0,vertexGc.y)).r)*waterCellSize.y;\n\
normalGc.y=(texture2DRect(waterSampler,vec2(vertexGc.x,vertexGc.y-1.0)).r-texture2DRect(waterSampler,vec2(vertexGc.x,vertexGc.y+1.0)).r)*waterCellSize.x;\n\
normalGc.z=1.0*waterCellSize.x*waterCellSize.y;\n\
\n\
/* Get the bathymetry elevation at the same location and calculate the vertex's water depth: */\n\
float bathy=(texture2DRect(bathymetrySampler,vertexGc.xy-vec2(1.0,1.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(1.0,0.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(0.0,1.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(0.0,0.0)).r)*0.25;\n\
vertexWaterDepth=vertexGc.z-bathy;\n\
\n\
/* Transform the vertex and its normal vector from grid space to eye space for illumination: */\n\
vertexGc.x=(vertexGc.x-0.5)*waterCellSize.x;\n\
vertexGc.y=(vertexGc.y-0.5)*waterCellSize.y;\n\
vec4 vertexEc=gl_ModelViewMatrix*vertexGc;\n\
vec3 normalEc=normalize(gl_NormalMatrix*normalGc);\n\
\n\
/* Initialize the vertex color accumulators: */\n\
vec4 ambDiff=gl_LightModel.ambient*gl_FrontMaterial.ambient;\n\
vec4 spec=vec4(0.0,0.0,0.0,0.0);\n\
\n\
/* Accumulate all enabled light sources: */\n";
/* Create light application functions for all enabled light sources: */
for(int lightIndex=0;lightIndex<lightTracker.getMaxNumLights();++lightIndex)
if(lightTracker.getLightState(lightIndex).isEnabled())
{
/* Create the light accumulation function: */
vertexShaderFunctions+=lightTracker.createAccumulateLightFunction(lightIndex);
/* Call the light application function from the bathymetry vertex shader's main function: */
vertexShaderMain+="\
accumulateLight";
char liBuffer[12];
vertexShaderMain.append(Misc::print(lightIndex,liBuffer+11));
vertexShaderMain+="(vertexEc,normalEc,gl_FrontMaterial.ambient,gl_FrontMaterial.diffuse,gl_FrontMaterial.specular,gl_FrontMaterial.shininess,ambDiff,spec);\n";
}
/* Finalize the vertex shader's main function: */
vertexShaderMain+="\
gl_FrontColor=vec4(ambDiff.xyz+spec.xyz,1.0);\n\
gl_BackColor=gl_FrontColor;\n\
gl_Position=gl_ModelViewProjectionMatrix*vertexGc;\n\
}\n";
/* Compile the vertex shader: */
shader.addShader(glCompileVertexShaderFromStrings(5,vertexShaderDefines.c_str(),vertexShaderFunctions.c_str(),vertexShaderVaryings.c_str(),vertexShaderUniforms.c_str(),vertexShaderMain.c_str()));
/* Create the fragment shader source code: */
std::string fragmentShaderVaryings="\
varying float vertexWaterDepth; // Water depth at a surface's vertex\n";
std::string fragmentShaderUniforms="\
uniform float waterDepthThreshold; // Depth threshold under which a vertex is considered dry\n";
std::string fragmentShaderMain="\
void main()\n\
{\n\
/* Discard the fragment if the ground underneath is actually dry: */\n\
if(vertexWaterDepth<waterDepthThreshold)\n\
discard;\n\
gl_FragColor=gl_Color;\n\
}\n";
/* Compile the fragment shader: */
shader.addShader(glCompileFragmentShaderFromStrings(3,fragmentShaderVaryings.c_str(),fragmentShaderUniforms.c_str(),fragmentShaderMain.c_str()));
/* Link the shader program: */
shader.link();
/* Retrieve the shader program's uniform variable locations: */
shader.setUniformLocation("waterSampler");
shader.setUniformLocation("bathymetrySampler");
shader.setUniformLocation("waterCellSize");
shader.setUniformLocation("waterDepthThreshold");
}
/*********************************************************************
Compile and link the transparent water shader:
*********************************************************************/
{
Shader& shader=dataItem->transparentWaterShader;
/* Create the vertex shader source code: */
std::string vertexShaderDefines="\
#extension GL_ARB_texture_rectangle : enable\n";
std::string vertexShaderFunctions;
std::string vertexShaderVaryings="\
varying float vertexWaterDepth; // Water depth at a surface's vertex\n";
std::string vertexShaderUniforms="\
uniform sampler2DRect waterSampler; // Sampler for the water surface texture\n\
uniform sampler2DRect bathymetrySampler; // Sampler for the bathymetry texture\n\
uniform vec2 waterCellSize; // Cell size of the water surface grid\n";
std::string vertexShaderMain="\
void main()\n\
{\n\
/* Get the vertex's grid-space z coordinate from the water surface texture: */\n\
vec4 vertexGc=gl_Vertex;\n\
vertexGc.z=texture2DRect(waterSampler,vertexGc.xy).r;\n\
\n\
/* Calculate the vertex's grid-space normal vector: */\n\
vec3 normalGc;\n\
normalGc.x=(texture2DRect(waterSampler,vec2(vertexGc.x-1.0,vertexGc.y)).r-texture2DRect(waterSampler,vec2(vertexGc.x+1.0,vertexGc.y)).r)*waterCellSize.y;\n\
normalGc.y=(texture2DRect(waterSampler,vec2(vertexGc.x,vertexGc.y-1.0)).r-texture2DRect(waterSampler,vec2(vertexGc.x,vertexGc.y+1.0)).r)*waterCellSize.x;\n\
normalGc.z=1.0*waterCellSize.x*waterCellSize.y;\n\
\n\
/* Get the bathymetry elevation at the same location and calculate the vertex's water depth: */\n\
float bathy=(texture2DRect(bathymetrySampler,vertexGc.xy-vec2(1.0,1.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(1.0,0.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(0.0,1.0)).r\n\
+texture2DRect(bathymetrySampler,vertexGc.xy-vec2(0.0,0.0)).r)*0.25;\n\
vertexWaterDepth=vertexGc.z-bathy;\n\
\n\
/* Transform the vertex and its normal vector from grid space to eye space for illumination: */\n\
vertexGc.x*=waterCellSize.x;\n\
vertexGc.y*=waterCellSize.y;\n\
vec4 vertexEc=gl_ModelViewMatrix*vertexGc;\n\
vec3 normalEc=normalize(gl_NormalMatrix*normalGc);\n\
\n\
/* Initialize the vertex color accumulators: */\n\
vec4 ambDiff=gl_LightModel.ambient*gl_FrontMaterial.ambient;\n\
vec4 spec=vec4(0.0,0.0,0.0,0.0);\n\
\n\
/* Accumulate all enabled light sources: */\n";
/* Create light application functions for all enabled light sources: */
for(int lightIndex=0;lightIndex<lightTracker.getMaxNumLights();++lightIndex)
if(lightTracker.getLightState(lightIndex).isEnabled())
{
/* Create the light accumulation function: */
vertexShaderFunctions+=lightTracker.createAccumulateLightFunction(lightIndex);
/* Call the light application function from the bathymetry vertex shader's main function: */
vertexShaderMain+="\
accumulateLight";
char liBuffer[12];
vertexShaderMain.append(Misc::print(lightIndex,liBuffer+11));
vertexShaderMain+="(vertexEc,normalEc,gl_FrontMaterial.ambient,gl_FrontMaterial.diffuse,gl_FrontMaterial.specular,gl_FrontMaterial.shininess,ambDiff,spec);\n";
}
/* Finalize the vertex shader's main function: */
vertexShaderMain+="\
gl_FrontColor=vec4(ambDiff.xyz+spec.xyz,1.0);\n\
gl_BackColor=gl_FrontColor;\n\
gl_Position=gl_ModelViewProjectionMatrix*vertexGc;\n\
}\n";
/* Compile the vertex shader: */
shader.addShader(glCompileVertexShaderFromStrings(5,vertexShaderDefines.c_str(),vertexShaderFunctions.c_str(),vertexShaderVaryings.c_str(),vertexShaderUniforms.c_str(),vertexShaderMain.c_str()));
std::string fragmentShaderDefines="\
#extension GL_ARB_texture_rectangle : enable\n";
std::string fragmentShaderVaryings="\
varying float vertexWaterDepth; // Water depth at a surface's vertex\n";
std::string fragmentShaderUniforms="\
uniform sampler2DRect depthSampler; // Sampler for the depth buffer texture\n\
uniform mat4 depthMatrix; // Matrix to transform fragment coordinates to model space\n\
uniform float waterOpacity; // Scale factor for fogging\n\
uniform float waterDepthThreshold; // Depth threshold under which a vertex is considered dry\n";
/* Create the fragment shader source code: */
std::string fragmentShaderMain="\
void main()\n\
{\n\
/* Discard the fragment if the ground underneath is actually dry: */\n\
if(vertexWaterDepth<waterDepthThreshold)\n\
discard;\n\
\n\
/* Transform the fragment currently in the pixel back to model space: */\n\
vec4 oldFrag=depthMatrix*vec4(gl_FragCoord.xy,texture2DRect(depthSampler,gl_FragCoord.xy).x,1.0);\n\
vec4 newFrag=depthMatrix*vec4(gl_FragCoord.xyz,1.0);\n\
float modelDist=length(newFrag.xyz/newFrag.w-oldFrag.xyz/oldFrag.w);\n\
// gl_FragColor=vec4(gl_Color.xyz,1.0-exp(-modelDist*waterOpacity));\n\
gl_FragColor=vec4(vec3(0.2,0.5,0.8),1.0-exp(-modelDist*waterOpacity));\n\
}\n";
/* Compile the fragment shader: */
shader.addShader(glCompileFragmentShaderFromStrings(4,fragmentShaderDefines.c_str(),fragmentShaderVaryings.c_str(),fragmentShaderUniforms.c_str(),fragmentShaderMain.c_str()));
/* Link the shader program: */
shader.link();
/* Retrieve the shader program's uniform variable locations: */
shader.setUniformLocation("waterSampler");
shader.setUniformLocation("bathymetrySampler");
shader.setUniformLocation("waterCellSize");
shader.setUniformLocation("depthSampler");
shader.setUniformLocation("depthMatrix");
shader.setUniformLocation("waterOpacity");
shader.setUniformLocation("waterDepthThreshold");
}
/*********************************************************************
Compile and link the snow shader:
*********************************************************************/
{
Shader& shader=dataItem->snowShader;
/* Create the vertex shader source code: */
std::string vertexShaderDefines="\
#extension GL_ARB_texture_rectangle : enable\n";
std::string vertexShaderFunctions;
std::string vertexShaderVaryings="\
varying float vertexSnowHeight; // Snow height at a surface's vertex\n";
std::string vertexShaderUniforms="\
uniform sampler2DRect snowSampler; // Sampler for the snow height texture\n\
uniform sampler2DRect bathymetrySampler; // Sampler for the bathymetry texture\n\
uniform vec2 waterCellSize; // Cell size of the water surface grid\n";
std::string vertexShaderMain="\
void main()\n\
{\n\
/* Get the vertex's snow height from the snow height texture: */\n\
vertexSnowHeight=texture2DRect(snowSampler,gl_Vertex.xy).r;\n\
\n\
/* Get the bathymetry elevation at the same location and calculate the vertex's grid-space z coordinate: */\n\
float b0=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(1.0,1.0)).r;\n\
float b1=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(1.0,0.0)).r;\n\
float b2=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(0.0,1.0)).r;\n\
float b3=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(0.0,0.0)).r;\n\
float bathy=(b0+b1+b2+b3)*0.25;\n\
vec4 vertexGc=gl_Vertex;\n\
vertexGc.z=vertexSnowHeight+bathy;\n\
\n\
/* Calculate the vertex's grid-space normal vector: */\n\
float b4=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(1.0,2.0)).r;\n\
float b5=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(0.0,2.0)).r;\n\
float b6=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(2.0,1.0)).r;\n\
float b7=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(-1.0,1.0)).r;\n\
float b8=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(2.0,0.0)).r;\n\
float b9=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(-1.0,0.0)).r;\n\
float b10=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(1.0,-1.0)).r;\n\
float b11=texture2DRect(bathymetrySampler,gl_Vertex.xy-vec2(0.0,-1.0)).r;\n\
vec3 normalGc;\n\
float zxm=texture2DRect(snowSampler,vec2(vertexGc.x-1.0,vertexGc.y)).r+(b6+b0+b8+b2)*0.25;\n\
float zxp=texture2DRect(snowSampler,vec2(vertexGc.x+1.0,vertexGc.y)).r+(b1+b7+b3+b9)*0.25;\n\
normalGc.x=(zxm-zxp)*waterCellSize.y;\n\
float zym=texture2DRect(snowSampler,vec2(vertexGc.x,vertexGc.y-1.0)).r+(b4+b5+b0+b1)*0.25;\n\
float zyp=texture2DRect(snowSampler,vec2(vertexGc.x,vertexGc.y+1.0)).r+(b2+b3+b10+b11)*0.25;\n\
normalGc.y=(zym-zyp)*waterCellSize.x;\n\
normalGc.z=1.0*waterCellSize.x*waterCellSize.y;\n\
\n\
/* Transform the vertex and its normal vector from grid space to eye space for illumination: */\n\
vertexGc.x*=waterCellSize.x;\n\
vertexGc.y*=waterCellSize.y;\n\
vec4 vertexEc=gl_ModelViewMatrix*vertexGc;\n\
vec3 normalEc=normalize(gl_NormalMatrix*normalGc);\n\
\n\
/* Initialize the vertex color accumulators: */\n\
vec4 ambDiff=gl_LightModel.ambient*gl_FrontMaterial.ambient;\n\
vec4 spec=vec4(0.0,0.0,0.0,0.0);\n\
\n\
/* Accumulate all enabled light sources: */\n";
/* Create light application functions for all enabled light sources: */
for(int lightIndex=0;lightIndex<lightTracker.getMaxNumLights();++lightIndex)
if(lightTracker.getLightState(lightIndex).isEnabled())
{
/* Create the light accumulation function: */
vertexShaderFunctions+=lightTracker.createAccumulateLightFunction(lightIndex);
/* Call the light application function from the bathymetry vertex shader's main function: */
vertexShaderMain+="\
accumulateLight";
char liBuffer[12];
vertexShaderMain.append(Misc::print(lightIndex,liBuffer+11));
vertexShaderMain+="(vertexEc,normalEc,gl_FrontMaterial.ambient,gl_FrontMaterial.diffuse,gl_FrontMaterial.specular,gl_FrontMaterial.shininess,ambDiff,spec);\n";
}