oculus2_psprite

view src/main.c @ 5:cd9f1560b909

added a few comments
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 04 Sep 2014 09:01:01 +0300
parents d64830551c32
children 37c753411934 4d6733229e01
line source
1 /* Very simple OculusSDK OpenGL usage example.
2 * Uses SDL2 for event handling and OpenGL context management.
3 *
4 * Author: John Tsiombikas <nuclear@member.fsf.org>
5 * This code is in the public domain. Do whatever you like with it.
6 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <assert.h>
10 #include <SDL2/SDL.h>
11 #include <GL/glew.h>
13 #ifdef WIN32
14 #define OVR_OS_WIN32
15 #endif
16 #ifdef __APPLE__
17 #define OVR_OS_MAC
18 #endif
20 #include <OVR_CAPI.h>
21 #include <OVR_CAPI_GL.h>
23 int init(void);
24 void cleanup(void);
25 void toggle_hmd_fullscreen(void);
26 void display(void);
27 void draw_scene(void);
28 void draw_box(float xsz, float ysz, float zsz, float norm_sign);
29 void update_rtarg(int width, int height);
30 int handle_event(SDL_Event *ev);
31 int key_event(int key, int state);
32 void reshape(int x, int y);
33 unsigned int next_pow2(unsigned int x);
34 void quat_to_matrix(const float *quat, float *mat);
35 unsigned int gen_chess_tex(float r0, float g0, float b0, float r1, float g1, float b1);
37 /* forward declaration to avoid including non-public headers of libovr */
38 OVR_EXPORT void ovrhmd_EnableHSWDisplaySDKRender(ovrHmd hmd, ovrBool enable);
40 static SDL_Window *win;
41 static SDL_GLContext ctx;
42 static int win_width, win_height;
44 static unsigned int fbo, fb_tex, fb_depth;
45 static int fb_width, fb_height;
46 static int fb_tex_width, fb_tex_height;
48 static ovrHmd hmd;
49 static ovrSizei eyeres[2];
50 static ovrEyeRenderDesc eye_rdesc[2];
51 static ovrGLTexture fb_ovr_tex[2];
53 static unsigned int chess_tex;
56 int main(int argc, char **argv)
57 {
58 if(init() == -1) {
59 return 1;
60 }
62 for(;;) {
63 SDL_Event ev;
64 while(SDL_PollEvent(&ev)) {
65 if(handle_event(&ev) == -1) {
66 goto done;
67 }
68 }
69 display();
70 }
72 done:
73 cleanup();
74 return 0;
75 }
78 int init(void)
79 {
80 int i, x, y;
81 unsigned int flags, dcaps;
82 union ovrGLConfig glcfg;
84 /* libovr must be initialized before we create the OpenGL context */
85 ovr_Initialize();
87 SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
89 x = y = SDL_WINDOWPOS_UNDEFINED;
90 flags = SDL_WINDOW_OPENGL;
91 if(!(win = SDL_CreateWindow("press 'f' to move to the HMD", x, y, 1280, 800, flags))) {
92 fprintf(stderr, "failed to create window\n");
93 return -1;
94 }
95 if(!(ctx = SDL_GL_CreateContext(win))) {
96 fprintf(stderr, "failed to create OpenGL context\n");
97 return -1;
98 }
100 glewInit();
102 if(!(hmd = ovrHmd_Create(0))) {
103 fprintf(stderr, "failed to open Oculus HMD, falling back to virtual debug HMD\n");
104 if(!(hmd = ovrHmd_CreateDebug(ovrHmd_DK2))) {
105 fprintf(stderr, "failed to create virtual debug HMD\n");
106 return -1;
107 }
108 }
109 printf("initialized HMD: %s - %s\n", hmd->Manufacturer, hmd->ProductName);
111 /* resize our window to match the HMD resolution */
112 SDL_SetWindowSize(win, hmd->Resolution.w, hmd->Resolution.h);
113 SDL_SetWindowPosition(win, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
114 win_width = hmd->Resolution.w;
115 win_height = hmd->Resolution.h;
117 /* enable position and rotation tracking (and anything else they might add in the future) */
118 ovrHmd_ConfigureTracking(hmd, 0xffffffff, 0);
119 /* retrieve the optimal render target resolution for each eye */
120 eyeres[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1.0);
121 eyeres[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1.0);
123 /* and create a single render target texture to encompass both eyes */
124 fb_width = eyeres[0].w + eyeres[1].w;
125 fb_height = eyeres[0].h > eyeres[1].h ? eyeres[0].h : eyeres[1].h;
126 update_rtarg(fb_width, fb_height);
128 /* fill in the ovrGLTexture structures that describe our render target texture */
129 for(i=0; i<2; i++) {
130 fb_ovr_tex[i].OGL.Header.API = ovrRenderAPI_OpenGL;
131 fb_ovr_tex[i].OGL.Header.TextureSize.w = fb_tex_width;
132 fb_ovr_tex[i].OGL.Header.TextureSize.h = fb_tex_height;
133 /* this next field is the only one that differs between the two eyes */
134 fb_ovr_tex[i].OGL.Header.RenderViewport.Pos.x = i == 0 ? 0 : fb_width / 2.0;
135 fb_ovr_tex[i].OGL.Header.RenderViewport.Pos.y = fb_tex_height - fb_height;
136 fb_ovr_tex[i].OGL.Header.RenderViewport.Size.w = fb_width / 2.0;
137 fb_ovr_tex[i].OGL.Header.RenderViewport.Size.h = fb_height;
138 fb_ovr_tex[i].OGL.TexId = fb_tex; /* both eyes will use the same texture id */
139 }
141 /* fill in the ovrGLConfig structure needed by the SDK to draw our stereo pair
142 * to the actual HMD display (SDK-distortion mode)
143 */
144 memset(&glcfg, 0, sizeof glcfg);
145 glcfg.OGL.Header.API = ovrRenderAPI_OpenGL;
146 glcfg.OGL.Header.RTSize = hmd->Resolution;
147 glcfg.OGL.Header.Multisample = 1;
149 if(hmd->HmdCaps & ovrHmdCap_ExtendDesktop) {
150 printf("running in \"extended desktop\" mode\n");
151 } else {
152 /* to sucessfully draw to the HMD display in "direct-hmd" mode, we have to
153 * call ovrHmd_AttachToWindow
154 * XXX: this doesn't work properly yet due to bugs in the oculus 0.4.1 sdk/driver
155 */
156 #ifdef WIN32
157 void *sys_win = GetActiveWindow();
158 glcfg.OGL.Window = sys_win;
159 glcfg.OGL.DC = wglGetCurrentDC();
160 ovrHmd_AttachToWindow(hmd, sys_win, 0, 0);
161 #endif
162 printf("running in \"direct-hmd\" mode\n");
163 }
165 /* enable low-persistence display and dynamic prediction for lattency compensation */
166 ovrHmd_SetEnabledCaps(hmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction);
168 /* configure SDK-rendering and enable chromatic abberation correction, vignetting, and
169 * timewrap, which shifts the image before drawing to counter any lattency between the call
170 * to ovrHmd_GetEyePose and ovrHmd_EndFrame.
171 */
172 dcaps = ovrDistortionCap_Chromatic | ovrDistortionCap_Vignette | ovrDistortionCap_TimeWarp;
173 if(!ovrHmd_ConfigureRendering(hmd, &glcfg.Config, dcaps, hmd->DefaultEyeFov, eye_rdesc)) {
174 fprintf(stderr, "failed to configure distortion renderer\n");
175 }
177 /* disable the retarded "health and safety warning" */
178 ovrhmd_EnableHSWDisplaySDKRender(hmd, 0);
180 glEnable(GL_DEPTH_TEST);
181 glEnable(GL_CULL_FACE);
182 glEnable(GL_LIGHTING);
183 glEnable(GL_LIGHT0);
184 glEnable(GL_LIGHT1);
185 glEnable(GL_NORMALIZE);
187 glClearColor(0.1, 0.1, 0.1, 1);
189 chess_tex = gen_chess_tex(1.0, 0.7, 0.4, 0.4, 0.7, 1.0);
190 return 0;
191 }
193 void cleanup(void)
194 {
195 if(hmd) {
196 ovrHmd_Destroy(hmd);
197 }
198 ovr_Shutdown();
200 SDL_Quit();
201 }
203 void toggle_hmd_fullscreen(void)
204 {
205 static int fullscr, prev_x, prev_y;
206 fullscr = !fullscr;
208 if(fullscr) {
209 /* going fullscreen on the rift. save current window position, and move it
210 * to the rift's part of the desktop before going fullscreen
211 */
212 SDL_GetWindowPosition(win, &prev_x, &prev_y);
213 SDL_SetWindowPosition(win, hmd->WindowsPos.x, hmd->WindowsPos.y);
214 SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN_DESKTOP);
215 } else {
216 /* return to windowed mode and move the window back to its original position */
217 SDL_SetWindowFullscreen(win, 0);
218 SDL_SetWindowPosition(win, prev_x, prev_y);
219 }
220 }
222 void display(void)
223 {
224 int i;
225 ovrMatrix4f proj;
226 ovrPosef pose[2];
227 float rot_mat[16];
229 /* the drawing starts with a call to ovrHmd_BeginFrame */
230 ovrHmd_BeginFrame(hmd, 0);
232 /* start drawing onto our texture render target */
233 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
234 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
236 /* for each eye ... */
237 for(i=0; i<2; i++) {
238 int eye = hmd->EyeRenderOrder[i];
240 /* -- viewport transformation --
241 * setup the viewport to draw in the left half of the framebuffer when we're
242 * rendering the left eye's view (0, 0, width/2, height), and in the right half
243 * of the framebuffer for the right eye's view (width/2, 0, width/2, height)
244 */
245 glViewport(eye == 0 ? 0 : fb_width / 2, 0, fb_width / 2, fb_height);
247 /* -- projection transformation --
248 * we'll just have to use the projection matrix supplied by the oculus SDK for this eye
249 * note that libovr matrices are the transpose of what OpenGL expects, so we have to
250 * use glLoadTransposeMatrixf instead of glLoadMatrixf to load it.
251 */
252 proj = ovrMatrix4f_Projection(hmd->DefaultEyeFov[eye], 0.5, 500.0, 1);
253 glMatrixMode(GL_PROJECTION);
254 glLoadTransposeMatrixf(proj.M[0]);
256 /* -- view/camera transformation --
257 * we need to construct a view matrix by combining all the information provided by the oculus
258 * SDK, about the position and orientation of the user's head in the world.
259 */
260 pose[eye] = ovrHmd_GetEyePose(hmd, eye);
261 glMatrixMode(GL_MODELVIEW);
262 glLoadIdentity();
263 glTranslatef(eye_rdesc[eye].ViewAdjust.x, eye_rdesc[eye].ViewAdjust.y, eye_rdesc[eye].ViewAdjust.z);
264 /* retrieve the orientation quaternion and convert it to a rotation matrix */
265 quat_to_matrix(&pose[eye].Orientation.x, rot_mat);
266 glMultMatrixf(rot_mat);
267 /* translate the view matrix with the positional tracking */
268 glTranslatef(-pose[eye].Position.x, -pose[eye].Position.y, -pose[eye].Position.z);
269 /* move the camera to the eye level of the user */
270 glTranslatef(0, -ovrHmd_GetFloat(hmd, OVR_KEY_EYE_HEIGHT, 1.65), 0);
272 /* finally draw the scene for this eye */
273 draw_scene();
274 }
276 /* after drawing both eyes into the texture render target, revert to drawing directly to the
277 * display, and we call ovrHmd_EndFrame, to let the Oculus SDK draw both images properly
278 * compensated for lens distortion and chromatic abberation onto the HMD screen.
279 */
280 glBindFramebuffer(GL_FRAMEBUFFER, 0);
281 glViewport(0, 0, win_width, win_height);
283 ovrHmd_EndFrame(hmd, pose, &fb_ovr_tex[0].Texture);
285 assert(glGetError() == GL_NO_ERROR);
286 }
288 void draw_scene(void)
289 {
290 int i;
291 float grey[] = {0.8, 0.8, 0.8, 1};
292 float col[] = {0, 0, 0, 1};
293 float lpos[][4] = {
294 {-8, 2, 10, 1},
295 {0, 15, 0, 1}
296 };
297 float lcol[][4] = {
298 {0.8, 0.8, 0.8, 1},
299 {0.4, 0.3, 0.3, 1}
300 };
302 for(i=0; i<2; i++) {
303 glLightfv(GL_LIGHT0 + i, GL_POSITION, lpos[i]);
304 glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, lcol[i]);
305 }
307 glMatrixMode(GL_MODELVIEW);
309 glPushMatrix();
310 glTranslatef(0, 10, 0);
311 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, grey);
312 glBindTexture(GL_TEXTURE_2D, chess_tex);
313 glEnable(GL_TEXTURE_2D);
314 draw_box(30, 20, 30, -1.0);
315 glDisable(GL_TEXTURE_2D);
316 glPopMatrix();
318 for(i=0; i<4; i++) {
319 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, grey);
320 glPushMatrix();
321 glTranslatef(i & 1 ? 5 : -5, 1, i & 2 ? -5 : 5);
322 draw_box(0.5, 2, 0.5, 1.0);
323 glPopMatrix();
325 col[0] = i & 1 ? 1.0 : 0.3;
326 col[1] = i == 0 ? 1.0 : 0.3;
327 col[2] = i & 2 ? 1.0 : 0.3;
328 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, col);
330 glPushMatrix();
331 if(i & 1) {
332 glTranslatef(0, 0.25, i & 2 ? 2 : -2);
333 } else {
334 glTranslatef(i & 2 ? 2 : -2, 0.25, 0);
335 }
336 draw_box(0.5, 0.5, 0.5, 1.0);
337 glPopMatrix();
338 }
339 }
341 void draw_box(float xsz, float ysz, float zsz, float norm_sign)
342 {
343 glMatrixMode(GL_MODELVIEW);
344 glScalef(xsz * 0.5, ysz * 0.5, zsz * 0.5);
346 if(norm_sign < 0.0) {
347 glFrontFace(GL_CW);
348 }
350 glBegin(GL_QUADS);
351 glNormal3f(0, 0, 1 * norm_sign);
352 glTexCoord2f(0, 0); glVertex3f(-1, -1, 1);
353 glTexCoord2f(1, 0); glVertex3f(1, -1, 1);
354 glTexCoord2f(1, 1); glVertex3f(1, 1, 1);
355 glTexCoord2f(0, 1); glVertex3f(-1, 1, 1);
356 glNormal3f(1 * norm_sign, 0, 0);
357 glTexCoord2f(0, 0); glVertex3f(1, -1, 1);
358 glTexCoord2f(1, 0); glVertex3f(1, -1, -1);
359 glTexCoord2f(1, 1); glVertex3f(1, 1, -1);
360 glTexCoord2f(0, 1); glVertex3f(1, 1, 1);
361 glNormal3f(0, 0, -1 * norm_sign);
362 glTexCoord2f(0, 0); glVertex3f(1, -1, -1);
363 glTexCoord2f(1, 0); glVertex3f(-1, -1, -1);
364 glTexCoord2f(1, 1); glVertex3f(-1, 1, -1);
365 glTexCoord2f(0, 1); glVertex3f(1, 1, -1);
366 glNormal3f(-1 * norm_sign, 0, 0);
367 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
368 glTexCoord2f(1, 0); glVertex3f(-1, -1, 1);
369 glTexCoord2f(1, 1); glVertex3f(-1, 1, 1);
370 glTexCoord2f(0, 1); glVertex3f(-1, 1, -1);
371 glEnd();
372 glBegin(GL_TRIANGLE_FAN);
373 glNormal3f(0, 1 * norm_sign, 0);
374 glTexCoord2f(0.5, 0.5); glVertex3f(0, 1, 0);
375 glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);
376 glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
377 glTexCoord2f(1, 1); glVertex3f(1, 1, -1);
378 glTexCoord2f(0, 1); glVertex3f(-1, 1, -1);
379 glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);
380 glEnd();
381 glBegin(GL_TRIANGLE_FAN);
382 glNormal3f(0, -1 * norm_sign, 0);
383 glTexCoord2f(0.5, 0.5); glVertex3f(0, -1, 0);
384 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
385 glTexCoord2f(1, 0); glVertex3f(1, -1, -1);
386 glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
387 glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
388 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
389 glEnd();
391 glFrontFace(GL_CCW);
392 }
394 /* update_rtarg creates (and/or resizes) the render target used to draw the two stero views */
395 void update_rtarg(int width, int height)
396 {
397 if(!fbo) {
398 /* if fbo does not exist, then nothing does... create every opengl object */
399 glGenFramebuffers(1, &fbo);
400 glGenTextures(1, &fb_tex);
401 glGenRenderbuffers(1, &fb_depth);
403 glBindTexture(GL_TEXTURE_2D, fb_tex);
404 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
405 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
406 }
408 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
410 /* calculate the next power of two in both dimensions and use that as a texture size */
411 fb_tex_width = next_pow2(width);
412 fb_tex_height = next_pow2(height);
414 /* create and attach the texture that will be used as a color buffer */
415 glBindTexture(GL_TEXTURE_2D, fb_tex);
416 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fb_tex_width, fb_tex_height, 0,
417 GL_RGBA, GL_UNSIGNED_BYTE, 0);
418 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_tex, 0);
420 /* create and attach the renderbuffer that will serve as our z-buffer */
421 glBindRenderbuffer(GL_RENDERBUFFER, fb_depth);
422 glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, fb_tex_width, fb_tex_height);
423 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fb_depth);
425 if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
426 fprintf(stderr, "incomplete framebuffer!\n");
427 }
429 glBindFramebuffer(GL_FRAMEBUFFER, 0);
430 printf("created render target: %dx%d (texture size: %dx%d)\n", width, height, fb_tex_width, fb_tex_height);
431 }
433 int handle_event(SDL_Event *ev)
434 {
435 switch(ev->type) {
436 case SDL_QUIT:
437 return -1;
439 case SDL_KEYDOWN:
440 case SDL_KEYUP:
441 if(key_event(ev->key.keysym.sym, ev->key.state == SDL_PRESSED) == -1) {
442 return -1;
443 }
444 break;
446 default:
447 break;
448 }
450 return 0;
451 }
453 int key_event(int key, int state)
454 {
455 if(state) {
456 /*
457 ovrHSWDisplayState hsw;
458 ovrHmd_GetHSWDisplayState(hmd, &hsw);
459 if(hsw.Displayed) {
460 ovrHmd_DismissHSWDisplay(hmd);
461 }
462 */
464 switch(key) {
465 case 27:
466 return -1;
468 case ' ':
469 /* allow the user to recenter by pressing space */
470 ovrHmd_RecenterPose(hmd);
471 break;
473 case 'f':
474 /* press f to move the window to the HMD */
475 toggle_hmd_fullscreen();
476 break;
478 default:
479 break;
480 }
481 }
482 return 0;
483 }
485 unsigned int next_pow2(unsigned int x)
486 {
487 x -= 1;
488 x |= x >> 1;
489 x |= x >> 2;
490 x |= x >> 4;
491 x |= x >> 8;
492 x |= x >> 16;
493 return x + 1;
494 }
496 /* convert a quaternion to a rotation matrix */
497 void quat_to_matrix(const float *quat, float *mat)
498 {
499 mat[0] = 1.0 - 2.0 * quat[1] * quat[1] - 2.0 * quat[2] * quat[2];
500 mat[4] = 2.0 * quat[0] * quat[1] + 2.0 * quat[3] * quat[2];
501 mat[8] = 2.0 * quat[2] * quat[0] - 2.0 * quat[3] * quat[1];
502 mat[12] = 0.0f;
504 mat[1] = 2.0 * quat[0] * quat[1] - 2.0 * quat[3] * quat[2];
505 mat[5] = 1.0 - 2.0 * quat[0]*quat[0] - 2.0 * quat[2]*quat[2];
506 mat[9] = 2.0 * quat[1] * quat[2] + 2.0 * quat[3] * quat[0];
507 mat[13] = 0.0f;
509 mat[2] = 2.0 * quat[2] * quat[0] + 2.0 * quat[3] * quat[1];
510 mat[6] = 2.0 * quat[1] * quat[2] - 2.0 * quat[3] * quat[0];
511 mat[10] = 1.0 - 2.0 * quat[0]*quat[0] - 2.0 * quat[1]*quat[1];
512 mat[14] = 0.0f;
514 mat[3] = mat[7] = mat[11] = 0.0f;
515 mat[15] = 1.0f;
516 }
518 /* generate a chessboard texture with tiles colored (r0, g0, b0) and (r1, g1, b1) */
519 unsigned int gen_chess_tex(float r0, float g0, float b0, float r1, float g1, float b1)
520 {
521 int i, j;
522 unsigned int tex;
523 unsigned char img[8 * 8 * 3];
524 unsigned char *pix = img;
526 for(i=0; i<8; i++) {
527 for(j=0; j<8; j++) {
528 int black = (i & 1) == (j & 1);
529 pix[0] = (black ? r0 : r1) * 255;
530 pix[1] = (black ? g0 : g1) * 255;
531 pix[2] = (black ? b0 : b1) * 255;
532 pix += 3;
533 }
534 }
536 glGenTextures(1, &tex);
537 glBindTexture(GL_TEXTURE_2D, tex);
538 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
539 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
540 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
542 return tex;