OVR: Show mirror of single eye only
[mercenary-reloaded.git] / src / libovr / ovr.c
1 /* OVR handling
2  *
3  * (C) 2018 by Andreas Eversberg <jolly@eversberg.eu>
4  * All Rights Reserved
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  * Based on example code:
20  * Filename    :   main.cpp
21  * Content     :   Simple minimal VR demo
22  * Created     :   December 1, 2014
23  * Author      :   Tom Heath
24  * Copyright   :   Copyright 2012 Oculus, Inc. All Rights reserved.
25  *
26  * Licensed under the Apache License, Version 2.0 (the "License");
27  * you may not use this file except in compliance with the License.
28  * You may obtain a copy of the License at
29  *
30  * http://www.apache.org/licenses/LICENSE-2.0
31  *
32  * Unless required by applicable law or agreed to in writing, software
33  * distributed under the License is distributed on an "AS IS" BASIS,
34  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35  * See the License for the specific language governing permissions and
36  * limitations under the License.
37  */
38
39 #include <stdio.h>
40 #include <stdint.h>
41 #include <string.h>
42 #include <math.h>
43 #include <errno.h>
44 #include "../libsdl/print.h"
45 #include "ovr.h"
46
47 #include <OVR_CAPI.h>
48 #include <OVR_CAPI_GL.h>
49 #include "helper.h"
50
51 #define GL3_PROTOTYPES 1
52 #include <GL/glew.h>
53
54 #if 0
55 #if defined(_WIN32)
56     #include <dxgi.h> // for GetDefaultAdapterLuid
57     #pragma comment(lib, "dxgi.lib")
58 #endif
59
60 static ovrGraphicsLuid GetDefaultAdapterLuid()
61 {
62         ovrGraphicsLuid luid = ovrGraphicsLuid();
63
64 #if defined(_WIN32)
65         IDXGIFactory* factory = nullptr;
66
67         if (SUCCEEDED(CreateDXGIFactory(IID_PPV_ARGS(&factory)))) {
68                 IDXGIAdapter* adapter = nullptr;
69
70                 if (SUCCEEDED(factory->EnumAdapters(0, &adapter))) {
71                         DXGI_ADAPTER_DESC desc;
72
73                         adapter->GetDesc(&desc);
74                         memcpy(&luid, &desc.AdapterLuid, sizeof(luid));
75                         adapter->Release();
76                 }
77
78                 factory->Release();
79         }
80 #endif
81
82         return luid;
83 }
84
85 static int Compare(const ovrGraphicsLuid lhs, const ovrGraphicsLuid rhs)
86 {
87     return memcmp(&lhs, &rhs, sizeof(ovrGraphicsLuid));
88 }
89 #endif
90
91 static int ovr_initialized = 0;
92 static ovrSession session = NULL;
93 static ovrGraphicsLuid luid;
94 static ovrHmdDesc hmdDesc;
95 static ovrSizei TextureSize[2];
96 static ovrTextureSwapChain textureSwapChain[2] = { NULL, NULL };
97 static GLuint fboId[2] = { 0, 0 };
98 static GLuint mirrorFBO = 0;
99 static int mirror_width;
100 static int mirror_height;
101 static ovrEyeRenderDesc eyeRenderDesc[2];
102 static ovrPosef hmdToEyeViewPose[2];
103 static ovrPosef headPose;
104 static ovrPosef handPose;
105 static ovrInputState inputState;
106 static ovrLayerEyeFov layer;
107 static int multisampling;
108 static long long frameIndex = 0;
109 static double observer_x = 0.0;
110 static double observer_x_reset = 0.0;
111 static double hand_x_reset = 0.0;
112 static double observer_y = 0.0;
113 static double observer_y_reset = 0.0;
114 static double hand_y_reset = 0.0;
115 static double observer_z = 0.0;
116 static double observer_z_reset = 0.0;
117 static double hand_z_reset = 0.0;
118
119 int init_ovr(int _multisampling)
120 {
121         ovrResult result;
122         int eye;
123
124         multisampling = _multisampling;
125
126         glewExperimental = GL_TRUE;
127         if (glewInit() != GLEW_OK) {
128                 print_error("Failed to init GLEW\n");
129                 goto error;
130         }
131
132         result = ovr_Initialize(NULL);
133         if (OVR_FAILURE(result)) {
134                 print_error("Failed to init OVR (is Oculus Rift service running?)\n");
135                 goto error;
136         }
137         ovr_initialized = 1;
138
139         result = ovr_Create(&session, &luid);
140         if (OVR_FAILURE(result)) {
141                 print_error("Failed to create OVR session (is the HMD connected?)\n");
142                 goto error;
143         }
144
145 #if 0
146         if (Compare(luid, GetDefaultAdapterLuid())) { // If luid that the Rift is on is not the default adapter LUID...
147                 print_error("OpenGL supports only the default graphics adapter.\n");
148                 goto error;
149         }
150 #endif
151
152         hmdDesc = ovr_GetHmdDesc(session);
153
154         memset(&layer, 0, sizeof(layer));
155         layer.Header.Type      = ovrLayerType_EyeFov;
156         layer.Header.Flags     = 0;
157
158         /* do we need this??? seems to work without */
159         if (multisampling > 1)
160                 glEnable(GL_MULTISAMPLE);
161
162         /* create render buffers */
163         for (eye = 0; eye < 2; eye++) {
164                 TextureSize[eye] = ovr_GetFovTextureSize(session, (eye == 0) ? ovrEye_Left : ovrEye_Right, hmdDesc.DefaultEyeFov[eye], 1.0);
165                 ovrTextureSwapChainDesc desc;
166                 int length, i;
167                 GLuint chainTexId;
168
169                 memset(&desc, 0, sizeof(desc));
170                 desc.Type = ovrTexture_2D;
171                 desc.ArraySize = 1;
172                 desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
173                 desc.Width = TextureSize[eye].w;
174                 desc.Height = TextureSize[eye].h;
175                 desc.MipLevels = 1;
176                 desc.SampleCount = (multisampling > 1) ? multisampling : 1;
177                 desc.StaticImage = ovrFalse;
178
179                 result = ovr_CreateTextureSwapChainGL(session, &desc, &textureSwapChain[eye]);
180                 if (OVR_FAILURE(result)) {
181                         print_error("ovr_CreateTextureSwapChainGL() failed! (error %d)\n", result);
182                         goto error;
183                 }
184
185                 ovr_GetTextureSwapChainLength(session, textureSwapChain[eye], &length);
186                 for (i = 0; i < length; i++) {
187                         ovr_GetTextureSwapChainBufferGL(session, textureSwapChain[eye], i, &chainTexId);
188                         glBindTexture((multisampling > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, chainTexId);
189                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
190                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
191                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
192                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
193                 }
194
195                 glGenFramebuffers(1, &(fboId[eye]));
196
197                 eyeRenderDesc[eye] = ovr_GetRenderDesc(session, (eye == 0) ? ovrEye_Left : ovrEye_Right, hmdDesc.DefaultEyeFov[eye]);
198                 hmdToEyeViewPose[eye] = eyeRenderDesc[eye].HmdToEyePose;
199
200                 layer.ColorTexture[eye]  = textureSwapChain[eye];
201                 layer.Fov[eye]           = eyeRenderDesc[eye].Fov;
202                 layer.Viewport[eye].Pos.x = 0;
203                 layer.Viewport[eye].Pos.y = 0;
204                 layer.Viewport[eye].Size.w = TextureSize[eye].w;
205                 layer.Viewport[eye].Size.h = TextureSize[eye].h;
206         }
207
208         ovrMirrorTexture mirrorTexture = NULL;
209         ovrMirrorTextureDesc desc;
210         memset(&desc, 0, sizeof(desc));
211         desc.Width = mirror_width = TextureSize[0].w;
212         desc.Height = mirror_height = TextureSize[0].h;
213         desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
214         desc.MirrorOptions =
215 //              ovrMirrorOption_PostDistortion |
216                 ovrMirrorOption_LeftEyeOnly |
217                 ovrMirrorOption_IncludeGuardian |
218                 ovrMirrorOption_IncludeNotifications |
219                 ovrMirrorOption_IncludeSystemGui;
220
221         /* Create mirror texture and an FBO used to copy mirror texture to back buffer */
222         result = ovr_CreateMirrorTextureWithOptionsGL(session, &desc, &mirrorTexture);
223         if (!OVR_SUCCESS(result)) {
224                 print_error("ovr_CreateMirrorTextureWithOptionsGL() failed! (error %d)\n", result);
225                 goto error;
226         }
227
228         /* Configure the mirror read buffer */
229         GLuint texId;
230         ovr_GetMirrorTextureBufferGL(session, mirrorTexture, &texId);
231
232         glGenFramebuffers(1, &mirrorFBO);
233         glBindFramebuffer(GL_READ_FRAMEBUFFER, mirrorFBO);
234         glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);
235         glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
236
237         return 0;
238
239 error:
240         exit_ovr();
241         return -EINVAL;
242 }
243
244 void get_poses_ovr(int *button_a, int *button_b, int *button_x, int *button_y, int *button_menu, int *button_left_trigger, int *button_right_trigger, int *button_left_thumb, int *button_right_thumb, double *hand_right_x, double *hand_right_y, double *hand_right_z, double *hand_right_yaw, double *hand_right_pitch, double *hand_right_roll, double *stick_left_x, double *stick_left_y, double *stick_right_x, double *stick_right_y, double *head_yaw, double *head_pitch, double *head_roll)
245 {       
246         ovrResult result;
247         float yaw, pitch, roll;
248         double x, y, z;
249         unsigned int hand_mask = (ovrStatus_OrientationTracked | ovrStatus_PositionTracked);
250         unsigned int hand_flags = (ovrStatus_OrientationTracked | ovrStatus_PositionTracked);
251
252         /* Get both eye poses simultaneously, with IPD offset already included. */
253         double displayMidpointSeconds = ovr_GetPredictedDisplayTime(session, frameIndex);
254         ovrTrackingState hmdState = ovr_GetTrackingState(session, displayMidpointSeconds, ovrTrue);
255         ovr_CalcEyePoses(hmdState.HeadPose.ThePose, hmdToEyeViewPose, layer.RenderPose);
256         /* Grab hand poses useful for rendering head/hand or controller representation */
257         headPose = hmdState.HeadPose.ThePose;
258         handPose = headPose;
259 //      if ((hmdState.HandStatusFlags[ovrHand_Left] & hand_mask) == hand_flags)
260 //              handPose = hmdState.HandPoses[ovrHand_Left].ThePose;
261         if ((hmdState.HandStatusFlags[ovrHand_Right] & hand_mask) == hand_flags)
262                 handPose = hmdState.HandPoses[ovrHand_Right].ThePose;
263         x = handPose.Position.x;
264         y = handPose.Position.y;
265         z = handPose.Position.z;
266         x += hand_x_reset;
267         y += hand_y_reset;
268         z += hand_z_reset;
269         *hand_right_x = x / 0.0254;
270         *hand_right_y = y / 0.0254;
271         *hand_right_z = z / 0.0254;
272         ovrOrientation2yawpitchroll(headPose.Orientation, &yaw, &pitch, &roll);
273         *head_yaw = yaw;
274         *head_pitch = pitch;
275         *head_roll = roll;
276         ovrOrientation2yawpitchroll(handPose.Orientation, &yaw, &pitch, &roll);
277         *hand_right_yaw = yaw;
278         *hand_right_pitch = pitch;
279         *hand_right_roll = roll;
280
281         result = ovr_GetInputState(session, ovrControllerType_Active, &inputState);
282         if (OVR_SUCCESS(result)) {
283                 if (inputState.Buttons & ovrButton_A)
284                         *button_a = 1;
285                 else
286                         *button_a = 0;
287                 if (inputState.Buttons & ovrButton_B)
288                         *button_b = 1;
289                 else
290                         *button_b = 0;
291                 if (inputState.Buttons & ovrButton_X)
292                         *button_x = 1;
293                 else
294                         *button_x = 0;
295                 if (inputState.Buttons & ovrButton_Y)
296                         *button_y = 1;
297                 else
298                         *button_y = 0;
299                 if (inputState.Buttons & ovrButton_Enter)
300                         *button_menu = 1;
301                 else
302                         *button_menu = 0;
303                 if (inputState.Buttons & ovrButton_LThumb)
304                         *button_left_thumb = 1;
305                 else
306                         *button_left_thumb = 0;
307                 if (inputState.Buttons & ovrButton_RThumb)
308                         *button_right_thumb = 1;
309                 else
310                         *button_right_thumb = 0;
311                 if (inputState.IndexTrigger[ovrHand_Left] >= 0.8)
312                         *button_left_trigger = 1;
313                 else
314                         *button_left_trigger = 0;
315                 if (inputState.IndexTrigger[ovrHand_Right] >= 0.8)
316                         *button_right_trigger = 1;
317                 else
318                         *button_right_trigger = 0;
319                 *stick_left_x = inputState.ThumbstickNoDeadzone[ovrHand_Left].x;
320                 *stick_left_y = inputState.ThumbstickNoDeadzone[ovrHand_Left].y;
321                 *stick_right_x = inputState.ThumbstickNoDeadzone[ovrHand_Right].x;
322                 *stick_right_y = inputState.ThumbstickNoDeadzone[ovrHand_Right].y;
323         }
324 }
325
326 void begin_render_ovr(void)
327 {
328         ovrResult result;
329
330         result = ovr_WaitToBeginFrame(session, frameIndex);
331         if (!OVR_SUCCESS(result))
332                 print_info("Failed to wait to begin frame (error %d)\n", result);
333         result = ovr_BeginFrame(session, frameIndex);
334         if (!OVR_SUCCESS(result))
335                 print_info("Failed to begin frame (error %d)\n", result);
336 }
337
338 static int initial_observer_reset = 1;
339
340 void begin_render_ovr_eye(int eye, double *camera_x, double *camera_y, double *camera_z)
341 {
342         int curIndex;
343         GLuint chainTexId;
344         float yaw, pitch, roll;
345         double x, y, z;
346
347         /* set render surface */
348         ovr_GetTextureSwapChainCurrentIndex(session, textureSwapChain[eye], &curIndex);
349         ovr_GetTextureSwapChainBufferGL(session, textureSwapChain[eye], curIndex, &chainTexId);
350         glBindFramebuffer(GL_FRAMEBUFFER, fboId[eye]);
351         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, (multisampling > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, chainTexId, 0);
352
353         glViewport(0, 0, TextureSize[eye].w, TextureSize[eye].h);
354         glMatrixMode(GL_PROJECTION);
355         glLoadIdentity();
356         glFrustum(
357                 -layer.Fov[eye].LeftTan,
358                 layer.Fov[eye].RightTan,
359                 layer.Fov[eye].UpTan,
360                 -layer.Fov[eye].DownTan,
361                 1.0, 5000000000.0);
362
363         ovrOrientation2yawpitchroll(layer.RenderPose[eye].Orientation, &yaw, &pitch, &roll);
364         x = layer.RenderPose[eye].Position.x;
365         y = layer.RenderPose[eye].Position.y;
366         z = layer.RenderPose[eye].Position.z;
367
368         /* reset to game's observer, if requrested by user */
369         observer_x = x;
370         observer_y = y;
371         observer_z = z;
372         if (initial_observer_reset) {
373                 initial_observer_reset = 0;
374                 reset_observer_ovr();
375         }
376         x += observer_x_reset;
377         y += observer_y_reset;
378         z += observer_z_reset;
379
380         glRotatef(-roll / M_PI * 180.0,0,0,1);
381         glRotatef(-pitch / M_PI * 180.0,1,0,0);
382         glRotatef(-yaw / M_PI * 180.0,0,1,0);
383
384         *camera_x = x / 0.0254;
385         *camera_y = y / 0.0254;
386         *camera_z = z / 0.0254;
387         glTranslated(-(*camera_x), -(*camera_y), -(*camera_z)); /* convert to inch */
388
389         glMatrixMode(GL_MODELVIEW);
390
391         /* DO NOT ENABLE, since our mercenary-textures are not SRGB */
392         //glEnable(GL_FRAMEBUFFER_SRGB);
393
394 }
395
396 void end_render_ovr_eye(int eye)
397 {
398         // unset render surface
399         glBindFramebuffer(GL_FRAMEBUFFER, fboId[eye]);
400         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, (multisampling > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, 0, 0);
401         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, (multisampling > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, 0, 0);
402         glBindFramebuffer(GL_FRAMEBUFFER, 0);
403
404         // Commit the changes to the texture swap chain
405         ovr_CommitTextureSwapChain(session, textureSwapChain[eye]);
406 }
407
408 void end_render_ovr(void)
409 {
410         ovrResult result;
411
412         const ovrLayerHeader *layers[] = { &layer.Header };
413         result = ovr_EndFrame(session, frameIndex, NULL, layers, 1);
414         if (!OVR_SUCCESS(result))
415                 print_info("Failed to submit frame (error %d)\n", result);
416         frameIndex++;
417 }
418
419 void render_mirror_ovr(int view_width, int view_height)
420 {
421         int view_x = 0, view_y = 0;
422         int new_height; //, new_width;
423
424         /* avoid division by zero, if one dimension is too small */
425         if (view_width < 1 || view_height < 1)
426                 return;
427
428         /* calculate a viewport that has apect of TextureSize */
429 //      if (view_height * mirror_width > view_width * mirror_height) {
430                 new_height = view_width * mirror_height / mirror_width;
431                 view_y = view_y + view_height / 2 - new_height / 2;
432                 view_height = new_height;
433 //      } else if (view_height * mirror_width < view_width * mirror_height) {
434 //              new_width = view_height * mirror_width / mirror_height;
435 //              view_x = view_x + view_width / 2 - new_width / 2;
436 //              view_width = new_width;
437 //      }
438
439         /* avoid views that are too small */
440         if (view_width < 1 || view_height < 1)
441                 return;
442
443         glBindFramebuffer(GL_FRAMEBUFFER, 0);
444
445         glClearColor(0.0, 0.0, 0.0, 1.0);
446         glClear(GL_COLOR_BUFFER_BIT);
447
448         /* Blit mirror texture to back buffer */
449         glBindFramebuffer(GL_READ_FRAMEBUFFER, mirrorFBO);
450         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
451         glBlitFramebuffer(0, mirror_height, mirror_width, 0,
452                 view_x, view_y, view_x + view_width, view_y + view_height,
453                 GL_COLOR_BUFFER_BIT, GL_LINEAR);
454         glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
455 }
456
457 void reset_observer_ovr(void)
458 {
459         observer_x_reset = -observer_x;
460         observer_y_reset = -observer_y;
461         observer_z_reset = -observer_z;
462         hand_x_reset = -observer_x;
463         hand_y_reset = -observer_y;
464         hand_z_reset = -observer_z;
465 }
466
467 int should_quit_ovr(void)
468 {
469         ovrSessionStatus sessionStatus;
470         ovrResult result;
471
472         result = ovr_GetSessionStatus(session, &sessionStatus);
473
474         if (OVR_SUCCESS(result))
475                 return sessionStatus.ShouldQuit;
476         return 0;
477 }
478
479 void exit_ovr(void)
480 {
481         int eye;
482
483         /* destroy render buffers */
484         for (eye = 0; eye < 2; eye++) {
485                 if (textureSwapChain[eye]) {
486                         ovr_DestroyTextureSwapChain(session, textureSwapChain[eye]);
487                         textureSwapChain[eye] = NULL;
488                 }
489                 if (fboId[eye]) {
490                         glDeleteFramebuffers(1, &fboId[eye]);
491                         fboId[eye] = 0;
492                 }
493         }
494         if (mirrorFBO) {
495                 glDeleteFramebuffers(1, &mirrorFBO);
496                 mirrorFBO = 0;
497         }
498
499         if (session) {
500                 ovr_Destroy(session);
501                 session = NULL;
502         }
503         if (ovr_initialized) {
504                 ovr_Shutdown();
505                 ovr_initialized = 0;
506         }
507 }
508