hellovr_opengl_main.cpp 91.7 KB
Newer Older
1
//========= Copyright Valve Corporaion ============//
2
#define NOMINMAX
3

4
#define _CRTDBG_MAP_ALLOC
5
6
7
8
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
9

10
#include <vector>
11
12
13
14

#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
15
//#include <SDL_ttf.h>
16
17
18
19
#include <gl/glu.h>
#include <stdio.h>
#include <string>
#include <cstdlib>
20
#include <algorithm>
21
22
23

#include <winsock2.h>

24
25
26
27
28
29
#include <openvr.h>

#include "shared/lodepng.h"
#include "shared/Matrices.h"
#include "shared/pathtools.h"

30
#include "rply/rply.h"
31

32
33
34
35
36
37
#include "NOMADVRLib/ConfigFile.h"
#include "NOMADVRLib/atoms.hpp"
#include "NOMADVRLib/atomsGL.h"

#include "NOMADVRLib/TessShaders.h"
#include "NOMADVRLib/UnitCellShaders.h"
38
#include "NOMADVRLib/IsoShaders.h"
39
#include "NOMADVRLib/CompileGLShader.h"
40

41
42
#include "NOMADVRLib/polyhedron.h"

43
#include "NOMADVRLib/IsosurfacesGL.h"
44

45
#define TESSSUB 16
46
47
48

//TTF_Font* font;

49
50
51
52
53
54
55
56
57
58
59
//#define LOCALTEST

/*#ifdef LOCALTEST
#define PATH "Y:\\v2t\\datasets\\mpcdf_CO2_CaO\\cubes-bigger\\IsosurfacesFixed\\"
#else
#define PATH "data\\CO2-CaO-B\\"
//#define PATH "C:\\Users\\mobile\\Desktop\\openvrDemos\\win64\\data\\CO2-CaO-B\\"
#endif
*/
#define ZLAYERS 12

60

61
62
63
64
65
66

#define MAXGPU 300

//shown on https://www.vbw-bayern.de/vbw/Aktionsfelder/Innovation-F-T/Forschung-und-Technologie/Zukunft-digital-Big-Data.jsp

#define GRID 1
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
#define NUMLODS 1


#define NUMPLY (TIMESTEPS * ISOS)

class CGLRenderModel
{
public:
	CGLRenderModel( const std::string & sRenderModelName );
	~CGLRenderModel();

	bool BInit( const vr::RenderModel_t & vrModel, const vr::RenderModel_TextureMap_t & vrDiffuseTexture );
	void Cleanup();
	void Draw();
	const std::string & GetName() const { return m_sModelName; }

private:
	GLuint m_glVertBuffer;
	GLuint m_glIndexBuffer;
	GLuint m_glVertArray;
	GLuint m_glTexture;
	GLsizei m_unVertexCount;
	std::string m_sModelName;
};

static bool g_bPrintf = true;

//-----------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
class CMainApplication
{
public:
	CMainApplication(int argc, char *argv[]);
	virtual ~CMainApplication();

	bool BInit();
	bool BInitGL();
	bool BInitCompositor();

	void SetupRenderModels();

	void Shutdown();

	void RunMainLoop();
	bool HandleInput();
	void ProcessVREvent(const vr::VREvent_t & event);
	void RenderFrame();
116
117
118
	void HapticFeedback();
	void HapticFeedback(int device);

119
120
121
122
123

	bool SetupTexturemaps();
	bool SetupDepthPeeling();

	void SetupScene();
124
125
	void SetupIsosurfaces();
	void SetupAtoms();
126
	void SetupUnitCell();
127
128
	void SetupMarker();

129

130
131
132
133
134
135
136
137
138
	void DrawControllers();

	bool SetupStereoRenderTargets();
	void SetupDistortion();
	void SetupCameras();

	void RenderStereoTargets();
	void RenderDistortion();
	void RenderScene(vr::Hmd_Eye nEye);
139
	void RenderAtoms(const vr::Hmd_Eye &nEye);
140
141
142
	void RenderAtomsUnitCell(const vr::Hmd_Eye &nEye, int p[3]);

	void RenderUnitCell(const vr::Hmd_Eye &nEye);
143
	//Vector3 GetDisplacement(int p[3]);
144

145
146
147
	Matrix4 GetHMDMatrixProjectionEye(vr::Hmd_Eye nEye);
	Matrix4 GetHMDMatrixPoseEye(vr::Hmd_Eye nEye);
	Matrix4 GetCurrentViewProjectionMatrix(vr::Hmd_Eye nEye);
148
	Matrix4 GetCurrentViewMatrix( vr::Hmd_Eye nEye );
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
	void UpdateHMDMatrixPose();

	Matrix4 ConvertSteamVRMatrixToMatrix4(const vr::HmdMatrix34_t &matPose);

	bool CreateAllShaders();

	void SetupRenderModelForTrackedDevice(vr::TrackedDeviceIndex_t unTrackedDeviceIndex);
	CGLRenderModel *FindOrLoadRenderModel(const char *pchRenderModelName);
	void RenderAllTrackedRenderModels(vr::Hmd_Eye nEye);
private:
	bool m_bDebugOpenGL;
	bool m_bVerbose;
	bool m_bPerf;
	bool m_bVblank;
	bool m_bGlFinishHack;

	vr::IVRSystem *m_pHMD;
	vr::IVRRenderModels *m_pRenderModels;
	std::string m_strDriver;
	std::string m_strDisplay;
	vr::TrackedDevicePose_t m_rTrackedDevicePose[vr::k_unMaxTrackedDeviceCount];
	Matrix4 m_rmat4DevicePose[vr::k_unMaxTrackedDeviceCount];
	bool m_rbShowTrackedDevice[vr::k_unMaxTrackedDeviceCount];

	std::vector<float> **vertdataarray; //[LOD][PLY]
#ifndef INDICESGL32
	std::vector<short> **vertindicesarray;//[LOD][PLY]
#else
	std::vector<GLuint> **vertindicesarray;//[LOD][PLY]
#endif
private: // SDL bookkeeping
	SDL_Window *m_pWindow;
	uint32_t m_nWindowWidth;
	uint32_t m_nWindowHeight;

	SDL_GLContext m_pContext;

	void PaintGrid(const vr::Hmd_Eye &nEye, const int iso);
187
188
	bool PaintBox();

189
190
191
192
193
194
195
196

private: // OpenGL bookkeeping
	int m_iTrackedControllerCount;
	int m_iTrackedControllerCount_Last;
	int m_iValidPoseCount;
	int m_iValidPoseCount_Last;
	bool m_bShowCubes;
	bool buttonPressed[2][vr::k_unMaxTrackedDeviceCount]; //grip, application menu
197
198
	bool AtomsButtonPressed[2];
	bool showAtoms;
199
200
201
202
203
204
205
206
207
208
209
210
211
212
	std::string m_strPoseClasses;                            // what classes we saw poses for this frame
	char m_rDevClassChar[vr::k_unMaxTrackedDeviceCount];   // for each device, a character representing its class

	int m_iSceneVolumeWidth;
	int m_iSceneVolumeHeight;
	int m_iSceneVolumeDepth;
	float m_fScaleSpacing;
	float m_fScale;

	int m_iSceneVolumeInit;                                  // if you want something other than the default 20x20x20

	float m_fNearClip;
	float m_fFarClip;

213
214
	void SaveScreenshot (char *name);

215
	GLuint *m_iTexture; //[3+ZLAYERS+1] // white, depth1, depth2, color[ZLAYERS], atomtexture
216
	SDL_Texture **axisTextures; //[6]
217
218
219
	GLuint peelingFramebuffer;
	unsigned int **m_uiVertcount;// [LODS][NUMPLY];

220
	//for isos
221
222
223
	GLuint **m_glSceneVertBuffer; // [LODS][NUMPLY];
	GLuint **m_unSceneVAO; //[LODS][NUMPLY];
	GLuint **m_unSceneVAOIndices; //[LODS][NUMPLY];
224
225
226

	//for atoms
	GLuint *m_glAtomVertBuffer; // [TIMESTEPS];
227
	GLuint *m_unAtomVAO; //[3]; //atoms, cloned atoms, bonds
228
	GLuint BondIndices;
229

230
231
232
233
	//for unit cells
	GLuint m_glUnitCellVertBuffer; // primitive, possibly non-primitive in further. Deformed cube
	GLuint m_glUnitCellIndexBuffer; // 
	GLuint m_unUnitCellVAO; //
234
235
236
	//for markers
	GLuint m_glMarkerVertBuffer;
	GLuint m_unMarkerVAO;
237

238
239
240
241
	int currentset;
	float elapsedtime;
	static const float videospeed;
	int currentiso;
242
	int firstdevice, seconddevice;
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
	GLuint m_unLensVAO;
	GLuint m_glIDVertBuffer;
	GLuint m_glIDIndexBuffer;
	unsigned int m_uiIndexSize;

	GLuint m_glControllerVertBuffer;
	GLuint m_unControllerVAO;
	unsigned int m_uiControllerVertcount;

	Matrix4 m_mat4HMDPose;
	Matrix4 m_mat4eyePosLeft;
	Matrix4 m_mat4eyePosRight;

	Matrix4 m_mat4ProjectionCenter;
	Matrix4 m_mat4ProjectionLeft;
	Matrix4 m_mat4ProjectionRight;

	Vector3 UserPosition;

	struct VertexDataScene
	{
		Vector3 position;
		Vector2 texCoord;
	};

	struct VertexDataLens
	{
		Vector2 position;
		Vector2 texCoordRed;
		Vector2 texCoordGreen;
		Vector2 texCoordBlue;
	};

	GLuint m_unSceneProgramID;
	GLuint m_unLensProgramID;
	GLuint m_unControllerTransformProgramID;
	GLuint m_unRenderModelProgramID;
280
	GLuint m_unAtomsProgramID;
281
	GLuint m_unUnitCellProgramID;
282
	GLuint m_unBlendingProgramID;
283
	GLuint m_unMarkerProgramID;
284
285
286
287
288

	GLint m_nSceneMatrixLocation;
	GLint m_nBlendingIntLocation;
	GLint m_nControllerMatrixLocation;
	GLint m_nRenderModelMatrixLocation;
289
290
	GLint m_nAtomMatrixLocation;
	GLint m_nAtomMVLocation;
291
	GLint m_nUnitCellMatrixLocation, m_nUnitCellColourLocation;
292
	GLint m_nMarkerMatrixLocation;
293
294
295
296
297
298
299
300
301
302
303
304
305

	struct FramebufferDesc
	{
		GLuint m_nDepthBufferId;
		GLuint m_nRenderTextureId;
		GLuint m_nRenderFramebufferId;
		GLuint m_nResolveTextureId;
		GLuint m_nResolveFramebufferId;
	};
	FramebufferDesc leftEyeDesc;
	FramebufferDesc rightEyeDesc;

	bool CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc );
306
	void CleanDepthTexture();
307
308
309
310
311
312
	uint32_t m_nRenderWidth;
	uint32_t m_nRenderHeight;

	std::vector< CGLRenderModel * > m_vecRenderModels;
	CGLRenderModel *m_rTrackedDeviceToRenderModel[ vr::k_unMaxTrackedDeviceCount ];

313
	char *pixels, *pixels2; //for saving screenshots to disk
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
	int framecounter;
	bool savetodisk;
};

const float CMainApplication::videospeed = 0.01f;


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void dprintf( const char *fmt, ... )
{
	va_list args;
	char buffer[ 2048 ];

	va_start( args, fmt );
	vsprintf_s( buffer, fmt, args );
	va_end( args );

	if ( g_bPrintf )
		printf( "%s", buffer );

	OutputDebugStringA( buffer );
337
338
	if (strncmp(buffer, "PoseCount", 9) && strncmp (buffer, "Device", 6))
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", buffer, 0);
339
340
}

341
342
343
344

//pure windows, no sdl
void eprintf( const char *fmt, ... )
{
345
346
347
348
349
350
351
352
	static int numerrors=0;
	numerrors++;
	if (numerrors==25) {
		MessageBoxA(0, "Max messages reached, no further reporting", "Warning", 0);
	}
	if (numerrors>15) {
		return;
	}
353
354
355
356
357
358
359
360
361
362
363
364
365
	va_list args;
	char buffer[ 2048 ];

	va_start( args, fmt );
	vsprintf_s( buffer, fmt, args );
	va_end( args );

	if ( g_bPrintf )
		printf( "%s", buffer );

	MessageBoxA(0, buffer, "Warning", 0);
}

366
367
368
369
370
371
372
373
374
375
376
377
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMainApplication::CMainApplication(int argc, char *argv[])
	: m_pWindow(NULL)
	, m_pContext(NULL)
	, m_nWindowWidth(1920)
	, m_nWindowHeight(1080)
	, m_unSceneProgramID(0)
	, m_unLensProgramID(0)
	, m_unControllerTransformProgramID(0)
	, m_unRenderModelProgramID(0)
378
	, m_unAtomsProgramID(0)
379
	, m_unUnitCellProgramID(0)
380
381
382
383
384
385
386
387
388
389
390
	, m_pHMD(NULL)
	, m_pRenderModels(NULL)
	, m_bDebugOpenGL(false)
	, m_bVerbose(false)
	, m_bPerf(false)
	, m_bVblank(false)
	, m_bGlFinishHack(true)
	, m_glControllerVertBuffer(0)
	, m_unControllerVAO(0)
	, m_unLensVAO(0)
	, m_unSceneVAO(0)
391
392
393
	, m_unSceneVAOIndices(0)
	, m_unAtomVAO(0)
	, m_glAtomVertBuffer(0)
394
395
396
	, m_glUnitCellVertBuffer(-1)
	, m_glUnitCellIndexBuffer(-1)
	, m_unUnitCellVAO(0)
397
398
399
400
	, m_nSceneMatrixLocation(-1)
	, m_nBlendingIntLocation(-1)
	, m_nControllerMatrixLocation(-1)
	, m_nRenderModelMatrixLocation(-1)
401
402
	, m_nAtomMatrixLocation(-1)
	, m_nAtomMVLocation(-1)
403
404
	, m_nUnitCellMatrixLocation(-1)
	, m_nUnitCellColourLocation(-1)
405
406
407
408
409
410
411
412
413
414
415
	, m_iTrackedControllerCount(0)
	, m_iTrackedControllerCount_Last(-1)
	, m_iValidPoseCount(0)
	, m_iValidPoseCount_Last(-1)
	, m_iSceneVolumeInit(20)
	, m_strPoseClasses("")
	, m_bShowCubes(true)
	, currentset(0)
	, elapsedtime(videospeed*float(SDL_GetTicks()))
	, currentiso(ISOS)
	, firstdevice(-1)
416
	, seconddevice(-1)
417
	, m_iTexture(0)
418
	, axisTextures(0)
419
420
421
422
	, peelingFramebuffer(0)
	, m_uiVertcount(0)
	, m_glSceneVertBuffer(0)
	//, UserPosition(Vector3(-101.0f * 0.15f*0.5f*GRID + 12.5f, -15.0f, -101.0f * 0.15f*0.5f*GRID + 101.0f * 0.15f*0.25f))
423
	, UserPosition(Vector3(-userpos[0] /** 0.04f*/, -userpos[1] /** 0.04f*/, -userpos[2] /** 0.04f*/))
424
425
426
427
428
429
430
431
432
433
	, vertdataarray(0)
	, vertindicesarray(0)
	, pixels(0)
	, framecounter(0)
	, savetodisk(false)
{
	for (int j=0;j<2;j++)
		for (int i = 0; i < vr::k_unMaxTrackedDeviceCount; i++) {
			buttonPressed[j][i] = false;
		}
434
	showAtoms=true;
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
	for( int i = 1; i < argc; i++ )
	{
		if( !stricmp( argv[i], "-gldebug" ) )
		{
			m_bDebugOpenGL = true;
		}
		else if( !stricmp( argv[i], "-verbose" ) )
		{
			m_bVerbose = true;
		}
		else if( !stricmp( argv[i], "-novblank" ) )
		{
			m_bVblank = false;
		}
		else if( !stricmp( argv[i], "-noglfinishhack" ) )
		{
			m_bGlFinishHack = false;
		}
		else if( !stricmp( argv[i], "-noprintf" ) )
		{
			g_bPrintf = false;
		}
		else if ( !stricmp( argv[i], "-cubevolume" ) && ( argc > i + 1 ) && ( *argv[ i + 1 ] != '-' ) )
		{
			m_iSceneVolumeInit = atoi( argv[ i + 1 ] );
			i++;
		}
	}
	// other initialization tasks are done in BInit
	memset(m_rDevClassChar, 0, sizeof(m_rDevClassChar));
};


//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CMainApplication::~CMainApplication()
{
	// work is done in Shutdown
	dprintf( "Shutdown" );
}


//-----------------------------------------------------------------------------
// Purpose: Helper to get a string from a tracked device property and turn it
//			into a std::string
//-----------------------------------------------------------------------------
std::string GetTrackedDeviceString( vr::IVRSystem *pHmd, vr::TrackedDeviceIndex_t unDevice, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError *peError = NULL )
{
	uint32_t unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, NULL, 0, peError );
	if( unRequiredBufferLen == 0 )
		return "";

	char *pchBuffer = new char[ unRequiredBufferLen ];
	unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, pchBuffer, unRequiredBufferLen, peError );
	std::string sResult = pchBuffer;
	delete [] pchBuffer;
	return sResult;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInit()
{


	if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
	{
		printf("%s - SDL could not initialize! SDL Error: %s\n", __FUNCTION__, SDL_GetError());
		return false;
	}

	// Loading the SteamVR Runtime
	vr::EVRInitError eError = vr::VRInitError_None;
	m_pHMD = vr::VR_Init( &eError, vr::VRApplication_Scene );

	if ( eError != vr::VRInitError_None )
	{
		m_pHMD = NULL;
		char buf[1024];
		sprintf_s( buf, sizeof( buf ), "Unable to init VR runtime: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
		SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
		return false;
	}


	m_pRenderModels = (vr::IVRRenderModels *)vr::VR_GetGenericInterface( vr::IVRRenderModels_Version, &eError );
	if( !m_pRenderModels )
	{
		m_pHMD = NULL;
		vr::VR_Shutdown();

		char buf[1024];
		sprintf_s( buf, sizeof( buf ), "Unable to get render model interface: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
		SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
		return false;
	}

	int nWindowPosX = 0;
	int nWindowPosY = 0;
	m_nWindowWidth = 1920;
	m_nWindowHeight = 1080;
	Uint32 unWindowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN /*| SDL_WINDOW_FULLSCREEN_DESKTOP*/; //rgh: interferes with mode change to 100Hz refresh

	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
	//SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

	SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 );
	SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 0 );
	if( m_bDebugOpenGL )
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );

	m_pWindow = SDL_CreateWindow( "Geophysics OpenVR SDL", nWindowPosX, nWindowPosY, m_nWindowWidth, m_nWindowHeight, unWindowFlags );
	if (m_pWindow == NULL)
	{
		printf( "%s - Window could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}

	m_pContext = SDL_GL_CreateContext(m_pWindow);
	if (m_pContext == NULL)
	{
		printf( "%s - OpenGL context could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}

	glewExperimental = GL_TRUE;
	GLenum nGlewError = glewInit();
	if (nGlewError != GLEW_OK)
	{
		printf( "%s - Error initializing GLEW! %s\n", __FUNCTION__, glewGetErrorString( nGlewError ) );
		return false;
	}
	glGetError(); // to clear the error caused deep in GLEW

	if ( SDL_GL_SetSwapInterval( m_bVblank ? 1 : 0 ) < 0 )
	{
		printf( "%s - Warning: Unable to set VSync! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}


	m_strDriver = "No Driver";
	m_strDisplay = "No Display";

	m_strDriver = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String );
	m_strDisplay = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String );

	std::string strWindowTitle = "Geophysics OpenVR - " + m_strDriver + " " + m_strDisplay;
	SDL_SetWindowTitle( m_pWindow, strWindowTitle.c_str() );
	
	// cube array
 	m_iSceneVolumeWidth = m_iSceneVolumeInit;
 	m_iSceneVolumeHeight = m_iSceneVolumeInit;
 	m_iSceneVolumeDepth = m_iSceneVolumeInit;
 		
595
	m_fScale = 0.04f; //0.15f; //rgh: original too big for room
596
597
598
 	m_fScaleSpacing = 4.0f;
 
 	m_fNearClip = 0.2f;
599
 	m_fFarClip = 200.0f;//rgh: original 30 too small for our skymap
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
 

 
// 		m_MillisecondsTimer.start(1, this);
// 		m_SecondsTimer.start(1000, this);
	
	if (!BInitGL())
	{
		printf("%s - Unable to initialize OpenGL!\n", __FUNCTION__);
		return false;
	}

	if (!BInitCompositor())
	{
		printf("%s - Failed to initialize VR Compositor!\n", __FUNCTION__);
		return false;
	}

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void APIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam)
{
	dprintf( "GL Error: %s\n", message );
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInitGL()
{
	if( m_bDebugOpenGL )
	{
		glDebugMessageCallback(DebugCallback, nullptr);
		glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE );
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	}

	if( !CreateAllShaders() )
		return false;

646
647
	GLenum e;

648
	SetupTexturemaps();
649
650
651
	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
652
	SetupScene();
653
654
655
	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
656
	SetupCameras();
657
658
659
	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
660
	SetupStereoRenderTargets();
661
662
663
	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
664
	SetupDistortion();
665
666
667
	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
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
	SetupDepthPeeling();

	SetupRenderModels();

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInitCompositor()
{
	vr::EVRInitError peError = vr::VRInitError_None;

	if ( !vr::VRCompositor() )
	{
		printf( "Compositor initialization failed. See log file for details\n" );
		return false;
	}

	return true;
}


693
694
695
696
697
698
699
700
701
702
703
704
705
void deleteVaos (GLuint *** vaos, int numlods, int numply)
{
if( *vaos != 0 )
{
	for (int i = 0; i < numlods; i++) {
		glDeleteVertexArrays(numply, (*vaos)[i]);
		delete[] (*vaos)[i];
	}
	delete[] (*vaos);
	*vaos = 0;
}
}

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
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::Shutdown()
{
	if( m_pHMD )
	{
		vr::VR_Shutdown();
		m_pHMD = NULL;
	}

	for( std::vector< CGLRenderModel * >::iterator i = m_vecRenderModels.begin(); i != m_vecRenderModels.end(); i++ )
	{
		delete (*i);
	}
	m_vecRenderModels.clear();
	
	if (vertdataarray) {
		for (int i = 0; i < NUMLODS; i++)
			if (vertdataarray[i])
				delete[] vertdataarray[i];
		delete[]vertdataarray;
		vertdataarray = 0;
	}
	if (vertindicesarray){
		for (int i = 0; i < NUMLODS; i++)
			if (vertindicesarray[i])
				delete[] vertindicesarray[i];
		delete[] vertindicesarray;
		vertindicesarray = 0;
	}
	if (m_pContext)
	{
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE);
		glDebugMessageCallback(nullptr, nullptr);
		if (m_glSceneVertBuffer) {
			for (int i = 0; i < NUMLODS; i++) {
				glDeleteBuffers(NUMPLY, m_glSceneVertBuffer[i]);
				delete[] (m_glSceneVertBuffer[i]);
			}
			delete[] m_glSceneVertBuffer;
			m_glSceneVertBuffer = nullptr;
		}
		glDeleteBuffers(1, &m_glIDVertBuffer);
		glDeleteBuffers(1, &m_glIDIndexBuffer);

		if ( m_unSceneProgramID )
		{
			glDeleteProgram( m_unSceneProgramID );
		}
		if ( m_unControllerTransformProgramID )
		{
			glDeleteProgram( m_unControllerTransformProgramID );
		}
		if ( m_unRenderModelProgramID )
		{
			glDeleteProgram( m_unRenderModelProgramID );
		}
		if ( m_unLensProgramID )
		{
			glDeleteProgram( m_unLensProgramID );
		}
768
769
770
771
		if ( m_unAtomsProgramID )
		{
			glDeleteProgram( m_unAtomsProgramID );
		}
772
773
		if (m_unUnitCellProgramID)
			glDeleteProgram(m_unUnitCellProgramID);
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790

		glDeleteRenderbuffers( 1, &leftEyeDesc.m_nDepthBufferId );
		glDeleteTextures( 1, &leftEyeDesc.m_nRenderTextureId );
		glDeleteFramebuffers( 1, &leftEyeDesc.m_nRenderFramebufferId );
		glDeleteTextures( 1, &leftEyeDesc.m_nResolveTextureId );
		glDeleteFramebuffers( 1, &leftEyeDesc.m_nResolveFramebufferId );

		glDeleteRenderbuffers( 1, &rightEyeDesc.m_nDepthBufferId );
		glDeleteTextures( 1, &rightEyeDesc.m_nRenderTextureId );
		glDeleteFramebuffers( 1, &rightEyeDesc.m_nRenderFramebufferId );
		glDeleteTextures( 1, &rightEyeDesc.m_nResolveTextureId );
		glDeleteFramebuffers( 1, &rightEyeDesc.m_nResolveFramebufferId );

		if( m_unLensVAO != 0 )
		{
			glDeleteVertexArrays( 1, &m_unLensVAO );
		}
791
792
		deleteVaos(&m_unSceneVAO, NUMLODS, NUMPLY);
		if( m_unAtomVAO != 0 )
793
		{
794
			glDeleteVertexArrays(1, m_unAtomVAO);
795
796
797
798
799
			delete[] m_unAtomVAO;
			m_unAtomVAO = 0;
		}		
		if (m_glAtomVertBuffer!=0)
		{
800
			glDeleteBuffers(1, m_glAtomVertBuffer);
801
802
803
804
			delete[] m_glAtomVertBuffer;
			m_glAtomVertBuffer=0;
		}

805
806
807
808
809
810
811
812
813
814
815
		if (m_unUnitCellVAO!=0) {
			glDeleteVertexArrays(1, &m_unUnitCellVAO);
		}
		if (m_glUnitCellVertBuffer!=-1) {
			glDeleteBuffers(1, &m_glUnitCellVertBuffer);
			m_glUnitCellVertBuffer=-1;
		}

		if (m_glUnitCellIndexBuffer!=-1) {
			glDeleteBuffers(1, &m_glUnitCellIndexBuffer);
			m_glUnitCellIndexBuffer=-1;
816
		}
817

818
819
820
821
		if( m_unControllerVAO != 0 )
		{
			glDeleteVertexArrays( 1, &m_unControllerVAO );
		}
822
823
824
825
826
827
828
829
		if (m_unSceneVAOIndices!=0)
		{
			for (int i=0;i<NUMLODS;i++) {
				glDeleteBuffers(NUMPLY, m_unSceneVAOIndices[i]);
				delete[] m_unSceneVAOIndices[i];
			}
			delete[] m_unSceneVAOIndices;
		}
830
		if (m_iTexture != 0) {
831
			glDeleteTextures(3+ZLAYERS+1, m_iTexture);
832
833
834
835
			delete[] m_iTexture;
			m_iTexture = 0;

		}
836
837
838
		if (axisTextures !=0) {
			delete[] axisTextures;
		}
839
840
841
842
843
844
845
846
847
848
		if (peelingFramebuffer!=0)
			glDeleteFramebuffers(1, &peelingFramebuffer);
	}

	if( m_pWindow )
	{
		SDL_DestroyWindow(m_pWindow);
		m_pWindow = NULL;
	}

849
850
851
852
853
854
	if (m_uiVertcount!=0) {
		for (int i=0;i<NUMLODS;i++) {
			delete[] m_uiVertcount[i];
		}
		delete[] m_uiVertcount;
	}
855

856
	if (numAtoms!=0) {
857
		for (int i=0;i<getAtomTimesteps();i++) {
858
859
860
861
862
863
864
865
866
			delete[] atoms[i];
		}
		delete[] atoms;
		delete[] numAtoms;
		numAtoms=0;
		atoms=0;
	}
	if (pixels !=0)
		delete [] pixels;
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
	SDL_Quit();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::HandleInput()
{
	SDL_Event sdlEvent;
	bool bRet = false;

	float speed = 0.02f;

	while (SDL_PollEvent(&sdlEvent) != 0)
	{
		if (sdlEvent.type == SDL_QUIT)
		{
			bRet = true;
		}
		else if (sdlEvent.type == SDL_KEYDOWN)
		{// q is too near 1, disable
			if (sdlEvent.key.keysym.sym == SDLK_ESCAPE
				/*|| sdlEvent.key.keysym.sym == SDLK_q*/)
			{
				bRet = true;
			}
			if (sdlEvent.key.keysym.sym == SDLK_c)
			{
				m_bShowCubes = !m_bShowCubes;
			} else if (sdlEvent.key.keysym.sym == SDLK_s)
			{
				savetodisk = !savetodisk;
			}
			//rgh: add keyboard navigation here
			if (sdlEvent.key.keysym.sym == SDLK_1) {
				currentset++;
903
				if (currentset >= TIMESTEPS)
904
905
906
907
908
					currentset = 0;
			}
			if (sdlEvent.key.keysym.sym == SDLK_2) {
				currentset--;
				if (currentset < 0)
909
					currentset = TIMESTEPS -1;
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
			}
			if (sdlEvent.key.keysym.sym == SDLK_0) {
				currentiso++;
				if (currentiso > ISOS)
					currentiso = 0;
			}
			if (sdlEvent.key.keysym.sym == SDLK_a) {
				Matrix4 tmp = m_mat4HMDPose;
				UserPosition += tmp.invert()*Vector3(0, 0, speed);
				//UserPosition.x += speed;
			}
			if (sdlEvent.key.keysym.sym == SDLK_y) {
				//UserPosition.x -= speed;
				Matrix4 tmp = m_mat4HMDPose;
				UserPosition -= tmp.invert()*Vector3(0, 0, speed);
			}
			if (sdlEvent.key.keysym.sym == SDLK_o) {
				UserPosition[2] -= 0.1f;
				dprintf("%f %f\n", UserPosition[0], UserPosition[2]);
			}
			if (sdlEvent.key.keysym.sym == SDLK_p) {
				UserPosition[2] += 0.1f;
				dprintf("%f %f\n", UserPosition[0], UserPosition[2]);
			}
		}
	}

	// Process SteamVR events
	vr::VREvent_t event;
	while (m_pHMD->PollNextEvent(&event, sizeof(event)))
	{
		ProcessVREvent(event);
	}

	// Process SteamVR controller state
	for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++)
	{
		vr::VRControllerState_t state;
		if (m_pHMD->GetControllerState(unDevice, &state))
		{
950
951
952
			//this hides the controllers when buttons are pressed. Why?! -> 
			//rgh: the name of the variable seems to make it so :o) Possibly so that a different model can be used with the correct deformation
			//m_rbShowTrackedDevice[unDevice] = state.ulButtonPressed == 0;
953
954
955
956
957

			if (!buttonPressed[1][unDevice] && state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_ApplicationMenu)) {
				buttonPressed[1][unDevice] = true;
				if (firstdevice == -1)
					firstdevice = unDevice;
958
				else if(unDevice !=firstdevice && seconddevice==-1)
959
					seconddevice=unDevice;
960
961
962
963
964

				if (firstdevice==unDevice)
					savetodisk = !savetodisk;
				else
					showAtoms= !showAtoms;
965
966
967
968
969
970
			}
			else if (buttonPressed[1][unDevice] && 0 == (state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_ApplicationMenu)))
			{
				buttonPressed[1][unDevice] = false;
			}

971
			
972
973
974
975
976
			if (!buttonPressed[0][unDevice] && state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_Grip))
			{
				buttonPressed[0][unDevice] = true;
				if (firstdevice == -1)
					firstdevice = unDevice;
977
				else if(unDevice !=firstdevice && seconddevice==-1)
978
979
					seconddevice=unDevice;

980
981
982
				if (unDevice == firstdevice) {
					currentset--;
					if (currentset < 0)
983
						currentset = TIMESTEPS - 1;
984
985
986
987
988
989
990
991
992
993
994
995
				} else {
					currentiso++;
					if (currentiso > ISOS)
						currentiso = 0;
				}
			} else if (buttonPressed[0][unDevice] && (state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_Grip)) == 0)
				buttonPressed[0][unDevice] = false;

			if (state.rAxis[1].x >0.1)
			{
				if (firstdevice == -1)
					firstdevice = unDevice;
996
997
				else if (unDevice !=firstdevice && seconddevice==-1)
					seconddevice=unDevice;
998
999
1000
1001
1002
1003
1004
1005
1006
				if (unDevice == firstdevice) {
					Matrix4 tmp = m_mat4HMDPose;
					UserPosition += tmp.invert()*Vector3(0, 0, speed);
				}
				else {
					float newtime = videospeed*float(SDL_GetTicks());;
					if (newtime-elapsedtime > 1) {
						elapsedtime = newtime;
						currentset++;
1007
						if (currentset >= TIMESTEPS)
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
							currentset = 0;
					}
				}
			}
		}
	}

	return bRet;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RunMainLoop()
{
	bool bQuit = false;

	SDL_StartTextInput();
	SDL_ShowCursor( SDL_DISABLE );

	while ( !bQuit )
	{
		bQuit = HandleInput();
		RenderFrame();
1032
		HapticFeedback();
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
	}

	SDL_StopTextInput();
}


//-----------------------------------------------------------------------------
// Purpose: Processes a single VR event
//-----------------------------------------------------------------------------
void CMainApplication::ProcessVREvent( const vr::VREvent_t & event )
{
	switch (event.eventType)
	{
		case vr::VREvent_TrackedDeviceActivated:
			{
				SetupRenderModelForTrackedDevice(event.trackedDeviceIndex);
				dprintf("Device %u attached. Setting up render model.\n", event.trackedDeviceIndex);
			}
		break;
		case vr::VREvent_TrackedDeviceDeactivated:
			{
				dprintf("Device %u detached.\n", event.trackedDeviceIndex);
			}
		break;
		case vr::VREvent_TrackedDeviceUpdated:
			{
				dprintf("Device %u updated.\n", event.trackedDeviceIndex);
			}
		break;
		/*
		case vr::VREvent_ButtonTouch:
			{
				buttonPressed = true;
			}
		break;
		case vr::VREvent_ButtonUntouch:
		{
			buttonPressed = false;
		}
		break;*/
		/*case vr::VREvent_ButtonPress:
			{
				m_bShowCubes = ~m_bShowCubes;
			}*/
	}
}


1081
void CMainApplication::HapticFeedback(){
1082
1083
1084
1085
	if (hapticFeedback) {
		HapticFeedback(firstdevice);
		HapticFeedback(seconddevice);
	}
1086
1087
1088
1089
1090
1091
}
//-----------------------------------------------------------------------------
// Purpose: Haptic feedback if controller near an atom
//-----------------------------------------------------------------------------
void CMainApplication::HapticFeedback(int device)
{
1092
1093
	if (!numAtoms)
		return;
1094
1095
1096
1097
1098
	if (device!=-1) {
		vr::VRControllerState_t cs;
		vr::TrackedDevicePose_t dp;
		m_pHMD->GetControllerStateWithPose( vr::TrackingUniverseStanding, device, &cs, &dp );
		if (dp.bPoseIsValid) {
1099
1100
1101
1102
1103
			int mycurrentset;
			if (fixedAtoms)
				mycurrentset=0;
			else
				mycurrentset=currentset;
1104
1105
			vr::HmdMatrix34_t mat=dp.mDeviceToAbsoluteTracking;
			Vector3 controllerPos(mat.m[0][3], mat.m[1][3],mat.m[2][3]);
1106
			int atomsInTimestep;
1107
			if (mycurrentset==0)
1108
1109
				atomsInTimestep=numAtoms[0];
			else
1110
				atomsInTimestep=numAtoms[mycurrentset]-numAtoms[mycurrentset-1];
1111
			for (int i=0;i<atomsInTimestep;i++) {
1112
				float atomr=atomRadius(static_cast<int>(atoms[mycurrentset][i*4+3]));
1113
1114

				//Vector3 posatom(atoms[currentset][i*4+0], atoms[currentset][i*4+1], atoms[currentset][i*4+2]);
1115
				Vector3 posatom(atoms[mycurrentset][i*4+0], atoms[mycurrentset][i*4+2], atoms[mycurrentset][i*4+1]); //y/z flipped
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
				int p[3];
				for (p[0]=0;p[0]<std::max(1,repetitions[0]);(p[0])++)
					for (p[1]=0;p[1]<std::max(1,repetitions[1]);(p[1])++)
						for (p[2]=0;p[2]<std::max(1,repetitions[2]);(p[2])++) {
							float delta[3];
							::GetDisplacement(p, delta);
							Vector3 iPos(delta[0], delta[1], delta[2]);

							Vector3 up(-UserPosition.x, -UserPosition.y, UserPosition.z);
							Vector3 pos=posatom-up+iPos;
							pos=Vector3 (pos.x, pos.y, -pos.z);
							float l=(pos - controllerPos).length();
							if (l<atomr*atomScaling) {
								m_pHMD->TriggerHapticPulse(device, 0, 3000);
								return;
							}
						}
			}
			//now cloned atoms
1135
			if (mycurrentset==0 && clonedAtoms) {
1136
				Vector3 up(-UserPosition.x, -UserPosition.y, UserPosition.z);
1137
				for (int i=0;i<numClonedAtoms;i++) {
1138
1139
					float atomr=atomRadius(static_cast<int>(clonedAtoms[mycurrentset][i*4+3]));
					Vector3 posatom(clonedAtoms[mycurrentset][i*4+0], clonedAtoms[mycurrentset][i*4+2], clonedAtoms[mycurrentset][i*4+1]);
1140
1141
1142
1143
1144
1145
1146
					Vector3 pos=posatom-up;
					pos.z=-pos.z;
					float l=(pos - controllerPos).length();
					if (l<atomr*atomScaling) {
						m_pHMD->TriggerHapticPulse(device, 0, 3000);
						return;
					}
1147
				}
1148
					
1149
			}
1150
1151
1152
		} // pose is valid
			
		
1153
1154
1155
	}
}

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RenderFrame()
{
	// for now as fast as possible
	if ( m_pHMD )
	{
		DrawControllers();
		RenderStereoTargets();
		RenderDistortion();

		vr::Texture_t leftEyeTexture = {(void*)leftEyeDesc.m_nResolveTextureId, vr::API_OpenGL, vr::ColorSpace_Gamma };
		vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture );
		vr::Texture_t rightEyeTexture = {(void*)rightEyeDesc.m_nResolveTextureId, vr::API_OpenGL, vr::ColorSpace_Gamma };
		vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture );
	}

	if ( m_bVblank && m_bGlFinishHack )
	{
		//$ HACKHACK. From gpuview profiling, it looks like there is a bug where two renders and a present
		// happen right before and after the vsync causing all kinds of jittering issues. This glFinish()
		// appears to clear that up. Temporary fix while I try to get nvidia to investigate this problem.
		// 1/29/2014 mikesart
		glFinish();
	}

	// SwapWindow
	{
		SDL_GL_SwapWindow( m_pWindow );
	}

	// Clear
	{
		// We want to make sure the glFinish waits for the entire present to complete, not just the submission
		// of the command. So, we do a clear here right here so the glFinish will wait fully for the swap.
		glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1);
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	}

	// Flush and wait for swap.
	if ( m_bVblank )
	{
		glFlush();
		glFinish();
	}

	// Spew out the controller and pose count whenever they change.
	if ( m_iTrackedControllerCount != m_iTrackedControllerCount_Last || m_iValidPoseCount != m_iValidPoseCount_Last )
	{
		m_iValidPoseCount_Last = m_iValidPoseCount;
		m_iTrackedControllerCount_Last = m_iTrackedControllerCount;
		
		dprintf( "PoseCount:%d(%s) Controllers:%d\n", m_iValidPoseCount, m_strPoseClasses.c_str(), m_iTrackedControllerCount );
	}

	UpdateHMDMatrixPose();
}





//-----------------------------------------------------------------------------
// Purpose: Creates all the shaders used by HelloVR SDL
//-----------------------------------------------------------------------------
bool CMainApplication::CreateAllShaders()
{
1224
	if (GL_NO_ERROR!=PrepareISOTransShader (&m_unSceneProgramID, &m_nSceneMatrixLocation, &m_unBlendingProgramID))
1225
	{
1226
		dprintf( "Error Preparing Transparency shader\n" );
1227
1228
1229
1230
1231
1232
1233
		return false;
	}
	/*m_nBlendingIntLocation = glGetUniformLocation(m_unSceneProgramID, "blending");
	if (m_nBlendingIntLocation == -1)
	{
		dprintf("Unable to find blending uniform in scene shader\n");
		return false;
1234
	}*/ 
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
	m_unControllerTransformProgramID = CompileGLShader(
		"Controller",

		// vertex shader
		"#version 410\n"
		"uniform mat4 matrix;\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec3 v3ColorIn;\n"
		"out vec4 v4Color;\n"
		"void main()\n"
		"{\n"
		"	v4Color.xyz = v3ColorIn; v4Color.a = 1.0;\n"
		"	gl_Position = matrix * position;\n"
		"}\n",

		// fragment shader
		"#version 410\n"
		"in vec4 v4Color;\n"
		"out vec4 outputColor;\n"
		"void main()\n"
		"{\n"
		"   outputColor = v4Color;\n"
		"}\n"
		);
	m_nControllerMatrixLocation = glGetUniformLocation( m_unControllerTransformProgramID, "matrix" );
	if( m_nControllerMatrixLocation == -1 )
	{
		dprintf( "Unable to find matrix uniform in controller shader\n" );
		return false;
	}

	m_unRenderModelProgramID = CompileGLShader( 
		"render model",

		// vertex shader
		"#version 410\n"
		"uniform mat4 matrix;\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec3 v3NormalIn;\n"
		"layout(location = 2) in vec2 v2TexCoordsIn;\n"
		"out vec2 v2TexCoord;\n"
		"void main()\n"
		"{\n"
		"	v2TexCoord = v2TexCoordsIn;\n"
		"	gl_Position = matrix * vec4(position.xyz, 1);\n"
		"}\n",

		//fragment shader
		"#version 410 core\n"
		"uniform sampler2D diffuse;\n"
		"in vec2 v2TexCoord;\n"
		"out vec4 outputColor;\n"
		"void main()\n"
		"{\n"
		"   outputColor = texture( diffuse, v2TexCoord);\n"
		"}\n"

		);
	m_nRenderModelMatrixLocation = glGetUniformLocation( m_unRenderModelProgramID, "matrix" );
	if( m_nRenderModelMatrixLocation == -1 )
	{
		dprintf( "Unable to find matrix uniform in render model shader\n" );
		return false;
	}
1299

1300
1301
	if (!PrepareUnitCellAtomShader (&m_unAtomsProgramID, &m_unUnitCellProgramID, &m_unMarkerProgramID,
		&m_nAtomMatrixLocation, &m_nUnitCellMatrixLocation,  &m_nUnitCellColourLocation, &m_nMarkerMatrixLocation))
1302
		return false;
1303
1304


1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
	m_unLensProgramID = CompileGLShader(
		"Distortion",

		// vertex shader
		"#version 410 core\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec2 v2UVredIn;\n"
		"layout(location = 2) in vec2 v2UVGreenIn;\n"
		"layout(location = 3) in vec2 v2UVblueIn;\n"
		"noperspective  out vec2 v2UVred;\n"
		"noperspective  out vec2 v2UVgreen;\n"
		"noperspective  out vec2 v2UVblue;\n"
		"void main()\n"
		"{\n"
		"	v2UVred = v2UVredIn;\n"
		"	v2UVgreen = v2UVGreenIn;\n"
		"	v2UVblue = v2UVblueIn;\n"
		"	gl_Position = position;\n"
		"}\n",

		// fragment shader
		"#version 410 core\n"
		"uniform sampler2D mytexture;\n"

		"noperspective  in vec2 v2UVred;\n"
		"noperspective  in vec2 v2UVgreen;\n"
		"noperspective  in vec2 v2UVblue;\n"

		"out vec4 outputColor;\n"

		"void main()\n"
		"{\n"
		"	float fBoundsCheck = ( (dot( vec2( lessThan( v2UVgreen.xy, vec2(0.05, 0.05)) ), vec2(1.0, 1.0))+dot( vec2( greaterThan( v2UVgreen.xy, vec2( 0.95, 0.95)) ), vec2(1.0, 1.0))) );\n"
		"	if( fBoundsCheck > 1.0 )\n"
		"	{ outputColor = vec4( 0, 0, 0, 1.0 ); }\n"
		"	else\n"
		"	{\n"
		"		float red = texture(mytexture, v2UVred).x;\n"
		"		float green = texture(mytexture, v2UVgreen).y;\n"
		"		float blue = texture(mytexture, v2UVblue).z;\n"
		"		outputColor = vec4( red, green, blue, 1.0  ); }\n"
		"}\n"
		);


	return m_unSceneProgramID != 0 
		&& m_unControllerTransformProgramID != 0
		&& m_unRenderModelProgramID != 0
		&& m_unLensProgramID != 0;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::SetupTexturemaps()
{

	//rgh: textures:	[0] White texture for textureless meshes
	//					[1,2] Depth texture for depth peeling ping pong (needs to be initialized after SetupStereoRenderTargets)
	//					[3..ZLAYERS+2] Colour textures for transparency
1366
	//sdl_textures: 6	[0..5] a b c alpha beta gamma text for axis labels
1367
1368
1369
	//std::string sExecutableDirectory = Path_StripFilename(Path_GetExecutablePath());
	//std::string strFullPath = Path_MakeAbsolute("../cube_texture.png", sExecutableDirectory);

1370
1371
	m_iTexture = new GLuint[3+ZLAYERS+1]; // white, depth1, depth2, color[ZLAYERS], atomtexture
	glGenTextures(3+ZLAYERS+1, m_iTexture);
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381

	//white
	unsigned char data2[4] = { 255, 255, 255, 255 }; //white texture for non-textured meshes
	glBindTexture(GL_TEXTURE_2D, m_iTexture[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2);

1382
1383
1384
1385
	GLenum e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("opengl error %d, SetupTextureMaps 1\n", e);

1386
	e=atomTexture( m_iTexture[3+ZLAYERS]);
1387

1388
1389
1390
	glBindTexture( GL_TEXTURE_2D, 0 );

	if ((e = glGetError()) != GL_NO_ERROR)
1391
		dprintf("opengl error %d, SetupTextureMaps 2\n", e);
1392

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
	//sdl text http://stackoverflow.com/questions/5289447/using-sdl-ttf-with-opengl/5289823#5289823
	//http://stackoverflow.com/questions/28880562/rendering-text-with-sdl2-and-opengl
	//FIXME TODO
	/*int size=10;
	=TTF_OpenFont("", size);
	axisTextures=new SDL_Texture*[6];

	const wchar_t axis[6]={'a', 'b', 'c', '\u03B1', '\u03B2', '\u03B3'};
	for (int i=0;i<6;i++) {
		axisTextures[i]=TTF_RenderUTF8_Blended();
	}
	*/

1406
1407
1408
1409
1410
	return ( m_iTexture != 0 && e==GL_NO_ERROR);
}

bool CMainApplication::SetupDepthPeeling()
{
1411
1412
1413
1414
	bool e;
	e=::SetupDepthPeeling(m_nRenderWidth, m_nRenderHeight, ZLAYERS, m_iTexture+1, &peelingFramebuffer);
	if (!e)
		dprintf("Errir setting up DepthPeeling\n");
1415

1416
	return (e);
1417
1418
1419
}

//-----------------------------------------------------------------------------
1420
// Purpose: Load the scene into OpenGL
1421
1422
//-----------------------------------------------------------------------------
void CMainApplication::SetupScene()
1423
1424
1425
{
	SetupIsosurfaces();
	SetupAtoms();
1426
1427
	//delete[] clonedAtoms; //required for haptic feedback
	//clonedAtoms=0;
1428
	SetupUnitCell();
1429
1430
1431
1432
1433
1434
1435
	SetupMarker();
}

void CMainApplication::SetupMarker()
{
GLenum e;
e=::SetupMarker(&m_unMarkerVAO, &m_glMarkerVertBuffer);
1436
1437
}

1438
1439
void CMainApplication::SetupUnitCell()
{
1440
1441
1442
1443
	GLenum e;
	e=::SetupUnitCell(&m_unUnitCellVAO, &m_glUnitCellVertBuffer, &m_glUnitCellIndexBuffer);
	if (e!=GL_NO_ERROR)
		dprintf("opengl error %d, SetupUnitCell, l %d\n", e, __LINE__);
1444
}
1445
1446
1447
//-----------------------------------------------------------------------------
// Purpose: Load the atoms into OpenGL
//-----------------------------------------------------------------------------
1448
1449
void CMainApplication::SetupAtoms()
{
1450
	GLenum e;
1451
	e=::SetupAtoms(&m_unAtomVAO, &m_glAtomVertBuffer, &BondIndices);
1452
1453
1454
1455
//	GLuint *vao, *buffer, *index;
//	e=::SetupAtomsNoTess(&vao, &buffer, &index);
	if (e!=GL_NO_ERROR)
		dprintf("opengl error %d, SetupAtoms, l %d\n", e, __LINE__);
1456
1457
1458
}


1459

1460
1461
1462
1463
//-----------------------------------------------------------------------------
// Purpose: Load the isosurfaces into OpenGL
//-----------------------------------------------------------------------------
void CMainApplication::SetupIsosurfaces()
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
{
	if (!m_pHMD)
		return;
	//rgh: add scene loading here
	vertdataarray = new std::vector<float>*[NUMLODS];
#ifndef INDICESGL32
	vertindicesarray = new std::vector<short>*[NUMLODS];
#else
	vertindicesarray = new std::vector<GLuint>*[NUMLODS];
#endif
	for (int i = 0; i < NUMLODS; i++) {//LODS 100%, 25%, 6%, 2% 
		vertdataarray[i] = new std::vector<float>[NUMPLY];
#ifndef INDICESGL32
		vertindicesarray[i] = new std::vector<short>[NUMPLY];
#else
		vertindicesarray[i] = new std::vector<GLuint>[NUMPLY];
#endif
	}

	Matrix4 matScale;
	matScale.scale(m_fScale, m_fScale, m_fScale);
	Matrix4 matTransform;
	/*matTransform.translate(
		-((float)m_iSceneVolumeWidth * m_fScaleSpacing) / 1.f,
		-((float)m_iSceneVolumeHeight * m_fScaleSpacing) / 1.f,
		-((float)m_iSceneVolumeDepth * m_fScaleSpacing) / 1.f);*/
	matTransform.rotateX(-90);
	Matrix4 mat = matScale * matTransform;

	const char *lods[] = {""};

	m_glSceneVertBuffer = new GLuint*[NUMLODS];
	m_uiVertcount = new unsigned int*[NUMLODS];
	m_unSceneVAO = new unsigned int*[NUMLODS];
	m_unSceneVAOIndices = new unsigned int*[NUMLODS];

	GLenum e;


	glClearColor(0,0,0, 1);
	glClear(GL_COLOR_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);

	glUseProgram(m_unControllerTransformProgramID);
	float loadingmat[] = { 2, 0, 0, 0,
		0, 2, 0, 0,
		0, 0, 1, 0,
		-1, -1, 0, 1 };

	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));
	//glDisable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, m_iTexture[1]);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));

	glDisable(GL_CULL_FACE);
	float z = 0.0f; 
	float points[] = {//pos [4], color [3]
		0, 0, z, 1, 1,1,1,
		0, 1, z, 1, 1, 1, 1,
		1, 1, z, 1, 1, 1, 1,
		1, 0, z, 1, 1, 1, 1, };

	//http://stackoverflow.com/questions/21767467/glvertexattribpointer-raising-impossible-gl-invalid-operation
	GLuint myvao;
	glGenVertexArrays(1, &myvao);
	glBindVertexArray(myvao);
	GLuint testBuf;
	glGenBuffers(1, &testBuf);
	glBindBuffer(GL_ARRAY_BUFFER, testBuf);
	glBufferData(GL_ARRAY_BUFFER, 4 * 7 * sizeof(GLfloat), points, GL_STATIC_DRAW);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)0);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(4 * sizeof(float)));
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	

	GLuint iData[] = { 0, 1, 2,
		2, 3, 0 };

	GLuint indexBufferID;
	glGenBuffers(1, &indexBufferID);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iData), iData, GL_STATIC_DRAW);


	for (int i = 0; i < NUMLODS; i++) {
		m_glSceneVertBuffer[i] = new GLuint[NUMPLY];
		m_uiVertcount[i] = new unsigned int[NUMPLY];
		m_unSceneVAO[i] = new unsigned int[NUMPLY];
		m_unSceneVAOIndices[i] = new unsigned int[NUMPLY];


		glGenBuffers(NUMPLY, m_glSceneVertBuffer[i]);
		glGenVertexArrays(NUMPLY, m_unSceneVAO[i]);
	
		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, glGenVertexArrays\n", e);
		// Create and populate the index buffer
		glGenBuffers(NUMPLY, m_unSceneVAOIndices[i]);
		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, glGenBuffers\n", e);

	}

	char tmpname[250];
	for (int currentlod = 0; currentlod < NUMLODS; currentlod++) {
		int time = 1;
		for (int p = 0; p < NUMPLY; p++) {
			glBindVertexArray(myvao);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);
			//loadingmat[0]=(float)currentlod/NUMLODS; //xscaling
			loadingmat[0]=2*(float)p/NUMPLY; //yscaling
			glUniformMatrix4fv(m_nControllerMatrixLocation, 1, GL_FALSE, loadingmat);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);

			SDL_GL_SwapWindow(m_pWindow);

			//http://stackoverflow.com/questions/9052224/error4error-c3861-snprintf-identifier-not-found
			sprintf(tmpname, "%s%s%d-%s.ply", PATH, lods[currentlod], time, plyfiles[p % ISOS]);

			vertdataarray[currentlod][p].clear();
			vertindicesarray[currentlod][p].clear();

			Matrix4 matFinal;
1610
1611
1612
			//matFinal.translate(translations[p%ISOS][0]+cubetrans[0], translations[p%ISOS][1]+cubetrans[1], translations[p%ISOS][2]+cubetrans[2]);
			Matrix4 matcubetrans, mvs;
			if (voxelSize[0]!=-1) {
1613
			mvs.scale(1.0f / (float)voxelSize[0], 1.0f / (float)voxelSize[1], 1.0f / (float)voxelSize[2]);
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
			matcubetrans.translate(cubetrans[0], cubetrans[1], cubetrans[2]); //angstrom
			//if abc, in abc coordinates
			/*Matrix4 abcm (abc[0][0], abc[1][0], abc[2][0], 0,
				abc[0][1], abc[1][1], abc[2][1], 0,
				abc[0][2], abc[1][2], abc[2][2], 0,
				0, 0, 0, 1);*/
			Matrix4 abcm (abc[0][0], abc[0][1], abc[0][2], 0,
				abc[1][0], abc[1][1], abc[1][2], 0,
				abc[2][0], abc[2][1], abc[2][2], 0,
				0, 0, 0, 1);
			Matrix4 rot;
			rot.rotateX(-90);
			Matrix4 sc;
			sc.scale(supercell[0], supercell[1], supercell[2]);
			Matrix4 sctrans;
			sctrans.translate(-translations[p%ISOS][2], -translations[p%ISOS][1], -translations[p%ISOS][0]);
			matFinal = rot*abcm*sctrans*sc*mvs;
			} else {
				matFinal.translate(translations[p%ISOS][0], translations[p%ISOS][1], translations[p%ISOS][2]);
				matFinal=mat*matFinal;
			}
1635
1636

			if (!AddModelToScene(matFinal.get(), vertdataarray[currentlod][p], vertindicesarray[currentlod][p],
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
				tmpname, false, isocolours[p%ISOS][0]<0, p%ISOS))
			{
				dprintf("Error loading ply file %s\n", tmpname);
				//m_bShowCubes = false;
				//return; 
			}
#ifndef INDICESGL32
			if (vertdataarray[currentlod][p].size() > 65535 * numComponents)
			{
				dprintf("Mesh has more than 64k vertices (%d), unsupported\n", vertdataarray[currentlod][p].size() / numComponents);
				m_bShowCubes = false;
				return;
			}
#endif
			m_uiVertcount[currentlod][p] = vertindicesarray[currentlod][p].size();  //rgh: now pos, normal, color

1653
1654
1655
1656
			if (GL_NO_ERROR!=PrepareGLiso(m_unSceneVAO[currentlod][p], m_glSceneVertBuffer[currentlod][p], 
				vertdataarray[currentlod][p], m_unSceneVAOIndices[currentlod][p], vertindicesarray[currentlod][p]))
				eprintf ("PrepareGLiso, GL error");
			
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861


			//FIXME: after we go to 64 bits, keep the data in ram
			vertdataarray[currentlod][p].clear();
			vertindicesarray[currentlod][p].clear();
			vertdataarray[currentlod][p].resize(0);
			vertindicesarray[currentlod][p].resize(0);


			if (p % ISOS == ISOS - 1)
				time++;

		}
		delete[] vertdataarray[currentlod];
		delete[] vertindicesarray[currentlod];
		vertdataarray[currentlod] = nullptr;
		vertindicesarray[currentlod] = nullptr;

	} // for each lod
	//glEnable(GL_DEPTH_TEST);
	if ((e = glGetError()) != GL_NO_ERROR)
		dpri