OvrApp.cpp 15.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/************************************************************************************

Filename    :   OvrApp.cpp
Content     :   Trivial use of the application framework.
Created     :   
Authors     :   

Copyright   :   Copyright 2014 Oculus VR, LLC. All Rights reserved.

*************************************************************************************/

#include <unistd.h>

#include "OvrApp.h"
#include "GuiSys.h"
#include "OVR_Locale.h"

18
19
20
21
22
23
#include "NOMADVRLib/atoms.hpp"
#include "NOMADVRLib/ConfigFile.h"
#include "NOMADVRLib/atomsGL.h"
#include "NOMADVRLib/UnitCellShaders.h"
#include "NOMADVRLib/TessShaders.h"
#include "NOMADVRLib/polyhedron.h"
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

using namespace OVR;

void eprintf( const char *fmt, ... )
{
	va_list args;
	char buffer[ 2048 ];

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

	LOG("Error in NOMADGearvrT");
	if (*fmt=='\0')
		LOG("Empty format");
	LOG("<%s>", buffer);
}

#if defined( OVR_OS_ANDROID )
extern "C" {

jlong Java_oculus_MainActivity_nativeSetAppInterface( JNIEnv * jni, jclass clazz, jobject activity,
		jstring fromPackageName, jstring commandString, jstring uriString )
{
	LOG( "nativeSetAppInterface" );
	return (new OvrTemplateApp::OvrApp())->SetActivity( jni, clazz, activity, fromPackageName, commandString, uriString );
}

} // extern "C"

#endif

#if 0
    #define GL( func )		func; EglCheckErrors();
#else
    #define GL( func )		func;
#endif

62
#include "rply/rply.h"
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

//static int vertex_cb(p_ply_argument argument);
//static int face_cb(p_ply_argument argument);

#include "stb_image.h"

namespace OvrTemplateApp
{
static const int CPU_LEVEL			= 2;
static const int GPU_LEVEL			= 3;
static const int NUM_INSTANCES		= 1;


//static int currentVertex=-1;

//static unsigned int currentCubeIndex=0;
//static unsigned short *cubeIndices;

OvrApp::OvrApp()
	: SoundEffectContext( NULL )
	, SoundEffectPlayer( NULL )
	, GuiSys( OvrGuiSys::Create() )
	, Locale( NULL )
{
    CenterEyeViewMatrix = ovrMatrix4f_CreateIdentity();
}

OvrApp::~OvrApp()
{
	OvrGuiSys::Destroy( GuiSys );
}

void OvrApp::Configure( ovrSettings & settings )
{
    settings.PerformanceParms.CpuLevel = CPU_LEVEL;
    settings.PerformanceParms.GpuLevel = GPU_LEVEL;
    settings.EyeBufferParms.multisamples = 4;
}

void OvrApp::OneTimeInit( const char * fromPackage, const char * launchIntentJSON, const char * launchIntentURI )
{
	OVR_UNUSED( fromPackage );
	OVR_UNUSED( launchIntentJSON );

    LOG("OneTimeInit, launchintentURI");
    LOG(launchIntentURI);
	LOG("launchIntentURI==null");
	LOG("%d", launchIntentURI==nullptr);
	//LOG("length of launchIntentURI=%d", strlen(launchIntentURI));
	//for (unsigned int i=0;i<strlen(launchIntentURI);i++) {
	//	LOG("<%c>: [%d]", launchIntentURI[i], launchIntentURI[i]);
	//}
	const char *defaultURI="file:///sdcard/Oculus/NOMAD/ViveTDefault.ncfg";
	//open a default file if none given
	if (!launchIntentURI || !strcmp(launchIntentURI, "")) {
		LOG(" OneTimeInit changing launchIntentURI");
		launchIntentURI=defaultURI;
	}
	
		LOG("OneTimeInit, launchintentURI");
    LOG(launchIntentURI);
	
	
	const char *configfile=launchIntentURI+6; //discard file://
	
	//change cwd so that relative paths work
	std::string s(configfile);
	chdir(s.substr(0, s.find_last_of("\\/")).c_str());
	
	int r;
	LOG("OneTimeInit, 8");	
	if ((r=loadConfigFile(configfile))<0) {
		if (-100<r) {
			eprintf(loadConfigFileErrors[-r]);
			eprintf("Config file reading error");
		} else if (-200<r){
			
			eprintf(readAtomsXYZErrors[-r-100]);
			eprintf("XYZ file reading error");
		} else if (-300<r) {
			eprintf(readAtomsCubeErrors[-r-200]);
			eprintf("Cube file reading error");
		} else {
			eprintf(readAtomsJsonErrors[-r-300]);
			eprintf("Json reading error");
		}
	
	}
151
152
153
154
	if (!solid) {
		LOG("No atom glyph specified, using Icosahedron");
		solid=new Solid(Solid::Type::Icosahedron);
	}
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
	LOG("OneTimeInit, 2");
	const ovrJava * java = app->GetJava();
	SoundEffectContext = new ovrSoundEffectContext( *java->Env, java->ActivityObject );
	SoundEffectContext->Initialize();
	SoundEffectPlayer = new OvrGuiSys::ovrDummySoundEffectPlayer();
LOG("OneTimeInit, 3");
	Locale = ovrLocale::Create( *app, "default" );
LOG("OneTimeInit, 4");
	String fontName;
	GetLocale().GetString( "@string/font_name", "efigs.fnt", fontName );
	GuiSys->Init( this->app, *SoundEffectPlayer, fontName.ToCStr(), &app->GetDebugLines() );
//LOG("OneTimeInit, 5");
    GL(glGenTextures(2, textures));
    //white
    unsigned char data2[4]={255,255,255,255}; //white texture for non-textured meshes
    glBindTexture(GL_TEXTURE_2D, textures[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);
//LOG("OneTimeInit, 6");
    // Create the programs
	//Leave atoms until we check if android 7 has gles 3.2 or if we use the old icosahedron method with no tesselation
	if (!PrepareUnitCellShader (&UnitCellP, &UnitCellMatrixLoc, &UnitCellColourLoc)) {
		LOG("OneTimeInit, failure compiling Unit Cell Shader");
		return ;
	}
	
	//rgh: for now, we don't have any tess-ready phones
	//if (!PrepareAtomShader(&AtomsP, &AtomMatrixLoc)) {
		hasTess=false;
		if (!PrepareAtomShaderNoTess(&AtomsP, &AtomMatrixLoc))
			eprintf ("PrepareAtomShaderNoTess failed");
	//};
//LOG("OneTimeInit, 7");	
	//atom texture
	//FIXME, add atom texture
	int e;
	
	e=atomTexture(textures[1]);
	if (e!=GL_NO_ERROR)
		eprintf ("atomTexture error %d", e);
//LOG("OneTimeInit, 7A");	
	e=SetupAtoms(&AtomTVAO, &AtomTBuffer);
	if (e!=GL_NO_ERROR)
		eprintf ("SetupAtoms error %d", e);
//LOG("OneTimeInit, 7B");	
	if (!hasTess)
		e=SetupAtomsNoTess(&AtomVAO, &AtomBuffer, &AtomIndices);
//LOG("OneTimeInit, 7C");	
	if (e!=GL_NO_ERROR)
		eprintf ("SetupAtomsNoTess error %d, tess=%d", e, hasTess);
	e=SetupUnitCell(&UnitCellVAO, &UnitCellBuffer, &UnitCellIndexBuffer);
	if (e!=GL_NO_ERROR)
		eprintf ("SetupUnitCell error %d", e);

//	LOG("End of OneTimeInit");
}

void OvrApp::OneTimeShutdown()
{
//	LOG("OneTimeShutdown 1");
	delete SoundEffectPlayer;
	SoundEffectPlayer = NULL;

	delete SoundEffectContext;
	SoundEffectContext = NULL;

	glDeleteProgram(AtomsP);
	glDeleteProgram(UnitCellP);
	
227
    GL(glDeleteTextures(2, textures));
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
//	LOG("OneTimeShutdown 2");
}

bool OvrApp::OnKeyEvent( const int keyCode, const int repeatCount, const KeyEventType eventType )
{
    animateTimesteps=!animateTimesteps;
	eprintf("OnKeyEvent called!");
    return true;
    /*if ( GuiSys->OnKeyEvent( keyCode, repeatCount, eventType ) )
    {
        return true;
    }*/
}

Matrix4f OvrApp::Frame( const VrFrame & vrFrame )
{
	
	LOG("Start Frame");
    CenterEyeViewMatrix = vrapi_GetCenterEyeViewMatrix( &app->GetHeadModelParms(), &vrFrame.Tracking, NULL );

    if (animateTimesteps) {
        animateCounter++;
        if (animateCounter>1/*0*/) {
            animateCounter=0;
            currentSet++;
            if (currentSet>TIMESTEPS-1)
                currentSet=0;
			LOG("currentSet updated, animate timesteps %d", currentSet);
        }
    }
    Matrix4f rot;
    float speed=0.1;
    unsigned int pb=vrFrame.Input.buttonState;
	if (pb&BUTTON_SWIPE_FORWARD && eyedir[2]<speed*0.5) {//move
	   eyedir[2]+=speed;
	   eyedir[1]=0;
	} else if (pb & BUTTON_SWIPE_BACK &&eyedir[2]>speed*-0.5) {
	   eyedir[2]-=speed;
	   eyedir[1]=0;
	} else if (pb & BUTTON_SWIPE_UP) {//next, previous timestep
		currentSet++;
		if (currentSet>TIMESTEPS-1)
			currentSet=0;
		//LOG("currentSet updated, swipe, %d", currentSet);
	} else if (pb & BUTTON_SWIPE_DOWN) {
		currentSet--;
		if (currentSet<0)
			currentSet=TIMESTEPS-1;
		//LOG("currentSet updated, swipe %d", currentSet);
	} /*else dir=Vector4f(0,0,0,0);*/
	if (fabs(eyedir[1]) < 0.5*speed && fabs(eyedir[2]) < 0.5*speed)
		eyedir[1]=eyedir[2]=0.0f;
	if (eyedir[1]!=0 || eyedir[2]!=0) {
	   rot=CenterEyeViewMatrix;
	   rot.Invert();
	}
	Vector4f dir=rot.Transform(eyedir);

	UserTranslation+=dir;
    
    // Update GUI systems last, but before rendering anything.
    GuiSys->Frame( vrFrame, CenterEyeViewMatrix );

    return CenterEyeViewMatrix;
}

void OvrApp::RenderAtoms(const float *m) //m[16]
{
	eprintf ("RenderAtoms start numatoms %d", numAtoms);
	int e;
	if (numAtoms==0)
		return;
	
	if (hasTess) {
	//FIXME, unimplemented
		LOG("FIXME, No Tess code for atoms yet!");
		return;
	} else { //no tess
		glBindVertexArray(AtomVAO[0]);
		glBindTexture(GL_TEXTURE_2D, textures[1]);
		glUseProgram(AtomsP);
		glUniformMatrix4fv(AtomMatrixLoc, 1, GL_FALSE, m);
		if (currentSet==0) {
311
			glDrawElements(GL_TRIANGLES, numAtoms[currentSet]* 3 * solid->nFaces, 
312
313
314
315
316
317
318
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT,
#else
				GL_UNSIGNED_INT,
#endif	
				0);
		} else {
319
			glDrawElements(GL_TRIANGLES, (numAtoms[currentSet]-numAtoms[currentSet-1]) * 3 * solid->nFaces,
320
#ifndef INDICESGL32				
321
				GL_UNSIGNED_SHORT, (void*)(numAtoms[currentSet-1]*sizeof(unsigned short)*3*solid->nFaces)
322
#else
323
				GL_UNSIGNED_INT, (void*)(numAtoms[currentSet-1]*sizeof(unsigned int)*3*solid->nFaces)
324
325
326
327
328
329
330
331
#endif
				);
		}
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("Gl error after Render  Atom timestep =%d: %d\n", currentSet, e);
		//now cloned atoms
		if (numClonedAtoms!=0 && currentSet==0) {
			glBindVertexArray(AtomVAO[1]);
332
			glDrawElements(GL_TRIANGLES, numClonedAtoms* 3 * solid->nFaces, 
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
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT,
#else
				GL_UNSIGNED_INT,
#endif	
				0);			
			
			
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("Gl error after Render cloned Atom timestep =%d: %d\n", currentSet, e);
		} // painting cloned atoms
	} // no tess
}

void OvrApp::RenderAtomTrajectoriesUnitCell()
{
	//now trajectories
if (!showTrajectories)
	return;

int e;
if (!AtomTVAO) {
	LOG("RenderAtomTrajectoriesUnitCell, no atoms");
	return;
}
glBindVertexArray(AtomTVAO[0]);

//glUseProgram(UnitCellP);
//glUniformMatrix4fv(m_nUnitCellMatrixLocation, 1, GL_FALSE, matrix);
float color[4]={1,0,0,1};
glUniform4fv(UnitCellColourLoc, 1, color);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("Gl error after glUniform4fv 2 RenderUnitCell: %d\n", e);
//glEnableVertexAttribArray(0);
//glDisableVertexAttribArray(1);

//LOG("atomtrajectories.size()=%d", atomtrajectories.size());
glBindBuffer(GL_ARRAY_BUFFER, AtomTBuffer[0]);

for (unsigned int i=0;i<atomtrajectories.size();i++) {
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float)*numAtoms[0], 
		(const void *)(0+4*sizeof(float)*atomtrajectories[i]));
		//LOG("atomtrajectoryrestarts[%d].size()=%d", i, atomtrajectoryrestarts[i].size());
	for (unsigned int j=1;j<atomtrajectoryrestarts[i].size();j++) {
		int orig=atomtrajectoryrestarts[i][j-1];
		int count=atomtrajectoryrestarts[i][j]-atomtrajectoryrestarts[i][j-1];
		glDrawArrays(GL_LINE_STRIP, orig, count);

	} //j
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("Gl error after Render Atom trajectories: %d\n", e);
} //i

} //OvrApp::RenderAtomTrajectoriesUnitCell()


void OvrApp::RenderUnitCell(const Matrix4f eyeViewProjection)
{
	eprintf ("RenderUnitCell, has_abc=%d", has_abc);
	if (!has_abc)
		return;
	if (UnitCellVAO==0)
		eprintf ("Error, Unit Cell VAO not loaded");
	int e;
	
	int p[3];
	for (p[0]=0;p[0]<repetitions[0];(p[0])++)
		for (p[1]=0;p[1]<repetitions[1];(p[1])++)
			for (p[2]=0;p[2]<repetitions[2];(p[2])++)
				{
					float delta[3];
					GetDisplacement(p, delta);
					Vector3f iPos(delta[0]+UserTranslation[0], delta[1]+UserTranslation[1], delta[2]+UserTranslation[2]);
					Matrix4f trans=Matrix4f::Translation(iPos);
					//trans.translate(iPos).rotateX(-90).translate(UserPosition);
					Matrix4f transform = eyeViewProjection*trans;
					float t[16];
					for (int i=0;i<4;i++)
						for (int j=0;j<4;j++)
							t[j*4+i]=transform.M[i][j];
					glUseProgram(UnitCellP);
					glUniformMatrix4fv(UnitCellMatrixLoc, 1, GL_FALSE, t);
					if ((e = glGetError()) != GL_NO_ERROR)
						eprintf("Gl error after glUniform4fv 1 RenderUnitCell: %d\n", e);
					float color[4]={1,1,1,1};
					glUniform4fv(UnitCellColourLoc, 1, color);
					if ((e = glGetError()) != GL_NO_ERROR)
						eprintf("Gl error after glUniform4fv 2 RenderUnitCell: %d\n", e);
					glBindVertexArray(UnitCellVAO);
					if ((e = glGetError()) != GL_NO_ERROR)
						eprintf("Gl error after glBindVertexArray RenderUnitCell: %d\n", e);
					glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
					if ((e = glGetError()) != GL_NO_ERROR)
						eprintf("Gl error after RenderUnitCell: %d\n", e);
					//atom trajectories
					RenderAtomTrajectoriesUnitCell();
					RenderAtoms(t);
				}
}


Matrix4f OvrApp::DrawEyeView( const int eye, const float fovDegreesX, const float fovDegreesY, ovrFrameParms & frameParms )
{
    OVR_UNUSED( frameParms );
	//LOG ("DrawEyeView 1, timestep=%d", currentSet);
    const Matrix4f eyeViewMatrix = vrapi_GetEyeViewMatrix( &app->GetHeadModelParms(), &CenterEyeViewMatrix, eye );
    //near, far plane set here: 10000 for earth, 100000 for skymap
    const Matrix4f eyeProjectionMatrix = ovrMatrix4f_CreateProjectionFov( fovDegreesX, fovDegreesY, 0.0f, 0.0f, 1,100000/*1.0f, 0.0f*/ );
    const Matrix4f eyeViewProjection = eyeProjectionMatrix * eyeViewMatrix;

    GL( glClearColor( BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1.0f ) );
    GL( glClear( GL_COLOR_BUFFER_BIT ) );

    //GL(        glEnable (GL_BLEND));
    //GL(        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
    GL( glDepthFunc(GL_LEQUAL));
    //GL( glUseProgram( Program.program ) );
    //GL( glUniformMatrix4fv( Program.uView, 1, GL_TRUE, eyeViewMatrix.M[0] ) );
    //GL( glUniformMatrix4fv( Program.uProjection, 1, GL_TRUE, eyeProjectionMatrix.M[0] ) );

    //glBindTexture(GL_TEXTURE_2D, textures[0]); //white
	//LOG ("DrawEyeView 2");
	RenderUnitCell(eyeViewProjection);
	//LOG ("DrawEyeView 3");
    GL( glBindVertexArray( 0 ) );
    GL( glUseProgram( 0 ) );

    GuiSys->RenderEyeView( CenterEyeViewMatrix, eyeViewMatrix, eyeProjectionMatrix );

    frameParms.Layers[VRAPI_FRAME_LAYER_TYPE_WORLD].Flags |= VRAPI_FRAME_LAYER_FLAG_CHROMATIC_ABERRATION_CORRECTION;
	//LOG("End Frame");
    return eyeViewProjection;
}

} // namespace OvrTemplateApp

/*
static int vertex_cb(p_ply_argument argument) {
    long what;
    ply_get_argument_user_data(argument, NULL, &what);
    if (what <=2 ) {
        if (what==0)
            OvrTemplateApp::currentVertex++;
        OvrTemplateApp::cubeVertices.positions[OvrTemplateApp::currentVertex][what]=ply_get_argument_value(argument);
    } else if (what <=5 ){
        OvrTemplateApp::cubeVertices.normals[OvrTemplateApp::currentVertex][what-3]=ply_get_argument_value(argument);
    } else if (what >9) {
        OvrTemplateApp::cubeVertices.uvs[OvrTemplateApp::currentVertex][what-10]=ply_get_argument_value(argument);
    } else {
        OvrTemplateApp::cubeVertices.colors[OvrTemplateApp::currentVertex][what-6]=ply_get_argument_value(argument)/255.0;
        //if (what==9)
        //    OvrTemplateApp::currentVertex++;
    }
    return 1;
}

static int face_cb(p_ply_argument argument) {
    long length, value_index;
    ply_get_argument_property(argument, NULL, &length, &value_index);
    //discard the first call with a 3
    if (value_index>=0 && value_index<=2)
        OvrTemplateApp::cubeIndices[OvrTemplateApp::currentCubeIndex++]=(int)(ply_get_argument_value(argument));

    return 1;
}
*/