summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/Displays/OVR_Linux_SDKWindow.cpp
blob: aa9acfcfe8d6bbba4db0eb1c2f30a28a12add75d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/*******************************************************************************

Filename    :   OVR_Linux_SDKWindow.cpp
Content     :   SDK generated Linux window.
Created     :   October 1, 2014
Authors     :   James Hughes

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

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

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

#include "OVR_Linux_SDKWindow.h"
#include "Kernel/OVR_Log.h"
#include "Kernel/OVR_Log.h"
#include "../../../3rdParty/EDID/edid.h"

namespace OVR {

// Forward declarations
static Window       constructWindow(struct _XDisplay* display, int xscreen,
                                    XVisualInfo* xvisual,
                                    const LinuxDeviceScreen& screen);

static XRRModeInfo* findModeByXID(XRRScreenResources* screen, RRMode xid)
{
  for (int m = 0; m < screen->nmode; ++m)
  {
    XRRModeInfo* mode = &screen->modes[m];
    if (xid == mode->id)
    {
      return mode;
    }
  }
  return NULL;
}

/// Retrieves a list of available device screens on which we can build
/// SDK windows. Returns number of devices found.
///   screens        Array which this function will populate.
///   maxNumScreens  Maximum number of screens to store in screens.
static int getDeviceScreens(LinuxDeviceScreen* screens, int maxNumDevices)
{
    struct _XDisplay* disp = XOpenDisplay(NULL);
    if (!disp)
    {
        OVR::LogError("[SDKWindow] Unable to open X Display.");
        return 0;
    }

    int numDevices = 0;
    int numScreens = XScreenCount(disp);
    for (int i = 0; i < numScreens; ++i)
    {
        // Screen root is used to detect what video output the crtc is using.
        Window sr                  = XRootWindow(disp, i);
        XRRScreenResources* screen = XRRGetScreenResources(disp, sr);

        for (int ii = 0; ii < screen->ncrtc; ++ii)
        {
            XRRCrtcInfo* crtcInfo = XRRGetCrtcInfo(disp, screen, screen->crtcs[ii]);

            if (0 == crtcInfo->noutput)
            {
                XRRFreeCrtcInfo(crtcInfo);
                continue;
            }

            bool foundOutput = false;
            RROutput output = crtcInfo->outputs[0];
            for (int k = 0; k < crtcInfo->noutput; ++k)
            {
                XRROutputInfo* outputInfo =
                    XRRGetOutputInfo(disp, screen, crtcInfo->outputs[k]);
                for (int kk = 0 ; kk < outputInfo->nmode; ++kk)
                {
                    if (outputInfo->modes[kk] == crtcInfo->mode)
                    {
                        output = crtcInfo->outputs[k];
                        foundOutput = true;
                        break;
                    }
                }
                XRRFreeOutputInfo(outputInfo);
                if (foundOutput) { break; }
            }

            if (!foundOutput)
            {
                XRRFreeCrtcInfo(crtcInfo);
                continue;
            }

            XRROutputInfo* outputInfo = XRRGetOutputInfo(disp, screen, output);
            if (RR_Connected != outputInfo->connection)
            {
                XRRFreeOutputInfo(outputInfo);
                XRRFreeCrtcInfo(crtcInfo);
                continue;
            }

            // Read EDID associated with crtc.
            MonitorInfo* mi = read_edid_data(disp, output);
            if (mi == NULL)
            {
                XRRFreeOutputInfo(outputInfo);
                XRRFreeCrtcInfo(crtcInfo);
                continue;
            }

            if (strcmp(mi->manufacturer_code, "OVR") == 0)
            {
                XRRModeInfo* modeInfo = findModeByXID(screen, crtcInfo->mode);

                DistortionRotation desiredRot = DistRotateNone;
                if (mi->product_code == 3)
                {
                    // This is a DK2, we may have to rotate our output.
                    // If we don't have to, we should alert the user that
                    // rotating the display using the DM or graphics
                    // card settings is highly non-optimal.
                    desiredRot = DistRotateCCW90;
                    if (crtcInfo->rotation != RR_Rotate_0)
                    {
                        OVR::LogError("Please do not rotate your rift's screen.");

                        if (crtcInfo->rotation == RR_Rotate_90)
                        {
                            // The user has manually rotated the screen.
                            // So apply no rotation on our end.
                            desiredRot = DistRotateNone;
                        }
                    }
                }
                else
                {
                    if (crtcInfo->rotation != RR_Rotate_0)
                    {
                        OVR::LogError("Please do not rotate your rift's screen.");
                    }
                }

                int width = modeInfo->width;
                int height = modeInfo->height;

                // Swap width / height if display is rotated (shouldn't be on linux).
                if (   crtcInfo->rotation == RR_Rotate_90
                    || crtcInfo->rotation == RR_Rotate_270)
                {
                    width  = modeInfo->height;
                    height = modeInfo->width;
                }

                // Push detected monitor.
                screens[numDevices].set(i, screen->crtcs[ii], desiredRot,
                                        mi->product_code, width, height,
                                        crtcInfo->x, crtcInfo->y);
                ++numDevices;
            }

            delete mi;

            if (numDevices == maxNumDevices)
            {
                XRRFreeOutputInfo(outputInfo);
                XRRFreeCrtcInfo(crtcInfo);
                XRRFreeScreenResources(screen);
                OVR::LogError("[SDKWindow] Maxed out number of devices..");
                XCloseDisplay(disp);
                return numDevices;
            }

            XRRFreeOutputInfo(outputInfo);
            XRRFreeCrtcInfo(crtcInfo);
        }

        XRRFreeScreenResources(screen);
    }
    XCloseDisplay(disp);
    return numDevices;
}


LinuxDeviceScreen SDKWindow::findDevScreenForHMD(const ovrHmd& hmd)
{
    return findDevScreenForDevID(hmd->DisplayDeviceName);
}

LinuxDeviceScreen SDKWindow::findDevScreenForDevID(const char* deviceIDIn)
{
    const int maxNumDevices = 5;
    LinuxDeviceScreen screens[maxNumDevices];
    int numDevices = getDeviceScreens(screens, maxNumDevices);

    if (numDevices > 0)
    {
        // Identify target for SDK window via hmd info.
        for (int i = 0; i < numDevices; ++i)
        {
            LinuxDeviceScreen& screen = screens[i];

            char deviceID[32];
            OVR_sprintf(deviceID, 32, "OVR%04d-%d",
                        screen.productCode, screen.crtcid);

            if (strcmp(deviceIDIn, deviceID) == 0)
            {
                return screen;
            }
        }
    }

    return LinuxDeviceScreen();
}

DistortionRotation SDKWindow::getRotation(const ovrHmd& hmd)
{
    LinuxDeviceScreen screen = findDevScreenForHMD(hmd);
    if (screen.isValid())
    {
        return screen.rotation;
    }
    else
    {
        return DistRotateNone;
    }
}


bool SDKWindow::getVisualFromDrawable(GLXDrawable drawable, XVisualInfo* vinfoOut)
{
    struct _XDisplay* display = glXGetCurrentDisplay();

    unsigned int value;
    glXQueryDrawable(display, drawable, GLX_FBCONFIG_ID, &value);
    const int attribs[] = {GLX_FBCONFIG_ID, (int)value, None};
    int screen;
    glXQueryContext(display, glXGetCurrentContext(), GLX_SCREEN, &screen);
    int numElems;
    GLXFBConfig* config = glXChooseFBConfig(display, screen, attribs, &numElems);
    if (numElems > 0)
    {
        XVisualInfo* chosen = glXGetVisualFromFBConfig(display, *config);
        *vinfoOut = *chosen;
        XFree(config);
        XFree(chosen);
        return true;
    }
    return false;
}

SDKWindow::SDKWindow(const ovrHmd& hmd) :
    mXDisplay(NULL),
    mXScreen(-1),
    mXVisual(NULL),
    mXUniqueContext(-1),
    mXWindow(0),
    mFBConfigID(0)
{
    OVR_UNUSED(hmd);
}

SDKWindow::~SDKWindow()
{
    if (mXWindow)
    {
        XDeleteContext(mXDisplay, mXWindow, mXUniqueContext);
        XUnmapWindow(mXDisplay, mXWindow);
        XDestroyWindow(mXDisplay, mXWindow);
        mXWindow = static_cast<Window>(0);
    }

    if (mXVisual)
    {
        XFree(mXVisual);
        mXVisual = NULL;
    }

    if (mXDisplay)
    {
        XCloseDisplay(mXDisplay);
    }
}

void SDKWindow::buildVisualAndWindow(const LinuxDeviceScreen& devScreen)
{
    mXDisplay       = XOpenDisplay(NULL);
    mXUniqueContext = XUniqueContext();
    mXScreen        = devScreen.screen;
    mFBConfigID     = chooseFBConfigID(mXDisplay, mXScreen);

    mXVisual = getVisual(mXDisplay, mFBConfigID, mXScreen);
    if (mXVisual != NULL)
    {
        mXWindow = constructWindow(mXDisplay, mXScreen, mXVisual, devScreen);
        mDeviceScreen = devScreen;
    }
}

// Used in chooseVisual. May need to expose this to the end use so they can
// choose an appropriate framebuffer configuration.
struct FBConfig
{
  FBConfig() :
      redBits(8),
      greenBits(8),
      blueBits(8),
      alphaBits(8),
      depthBits(8),
      stencilBits(-1),
      doubleBuffer(true),
      auxBuffers(-1)
  {}

  int  redBits;
  int  greenBits;
  int  blueBits;
  int  alphaBits;
  int  depthBits;
  int  stencilBits;
  bool doubleBuffer;
  int  auxBuffers;

  int xcfg;
};

static int fbCalcContrib(int desired, int current)
{
    int diff = desired - current;
    if (current != -1) { return diff * diff; }
    else               { return 0; }
}

// Choose frame buffer configuration and return fbConfigID.
int SDKWindow::chooseFBConfigID(struct _XDisplay* display, int xscreen)
{
    int nativeCount = 0;
    GLXFBConfig* nativeConfigs =
        glXGetFBConfigs(display, xscreen, &nativeCount);
    if (!nativeCount)
    {
        OVR::LogError("[SDKWindow] No valid frame buffer configurations found.");
        return 0;
    }

    FBConfig* usables = static_cast<FBConfig*>(calloc(nativeCount, sizeof(FBConfig)));
    int numUsables = 0;

    for (int i = 0; i < nativeCount; ++i)
    {
        GLXFBConfig native = nativeConfigs[i];
        FBConfig* usable   = &usables[numUsables];
        int v              = 0;

        // Only frame buffer configcs with attached visuals.
        glXGetFBConfigAttrib(display, native, GLX_VISUAL_ID, &v);
        if (!v) { continue; }

        // Only RGBA frame buffers.
        glXGetFBConfigAttrib(display, native, GLX_RENDER_TYPE, &v);
        if (!(v & GLX_RGBA_BIT)) { continue; }

        glXGetFBConfigAttrib(display, native, GLX_DRAWABLE_TYPE, &v);
        if (!(v & GLX_WINDOW_BIT)) { continue; }

        glXGetFBConfigAttrib(display, native, GLX_DEPTH_SIZE,   &usable->depthBits);
        glXGetFBConfigAttrib(display, native, GLX_STENCIL_SIZE, &usable->stencilBits);

        glXGetFBConfigAttrib(display, native, GLX_RED_SIZE,     &usable->redBits);
        glXGetFBConfigAttrib(display, native, GLX_GREEN_SIZE,   &usable->greenBits);
        glXGetFBConfigAttrib(display, native, GLX_BLUE_SIZE,    &usable->blueBits);
        glXGetFBConfigAttrib(display, native, GLX_ALPHA_SIZE,   &usable->alphaBits);

        glXGetFBConfigAttrib(display, native, GLX_ALPHA_SIZE,   &usable->auxBuffers);

        glXGetFBConfigAttrib(display, native, GLX_DOUBLEBUFFER, &v);
        usable->doubleBuffer = v ? true : false;

        glXGetFBConfigAttrib(display, native, GLX_FBCONFIG_ID, &usable->xcfg);

        ++numUsables;
    }

    // We really want std::numeric_limits<int>::max() instead of hardcoded vals.
    const int MostMissing = 100;
    int leastMissing      = MostMissing;
    int leastBias         = MostMissing;

    const FBConfig* closest = NULL;
    
    // Desired is currently the default config built by constructor.
    FBConfig desired;

    for (int i = 0; i < numUsables; ++i)
    {
        const FBConfig* cur = &usables[i];

        if (desired.doubleBuffer != cur->doubleBuffer) { continue; }

        int missing = 0;
        if (desired.alphaBits > 0 && cur->alphaBits == 0) { ++missing; }
        if (desired.depthBits > 0 && cur->depthBits == 0) { ++missing; }
        if (desired.stencilBits > 0 && cur->stencilBits == 0) { ++missing; }
        if (desired.redBits > 0 && desired.redBits != cur->redBits) { ++missing; }
        if (desired.greenBits > 0 && desired.greenBits != cur->greenBits) { ++missing; }
        if (desired.blueBits > 0 && desired.blueBits != cur->blueBits) { ++missing; }

        int bias = fbCalcContrib(desired.redBits,     cur->redBits)
                 + fbCalcContrib(desired.greenBits,   cur->greenBits)
                 + fbCalcContrib(desired.blueBits,    cur->blueBits)
                 + fbCalcContrib(desired.alphaBits,   cur->alphaBits)
                 + fbCalcContrib(desired.depthBits,   cur->depthBits)
                 + fbCalcContrib(desired.stencilBits, cur->stencilBits);

        if (missing < leastMissing)
        {
            closest = cur;
        }
        else if (missing == leastMissing)
        {
            // Now select against squared differences.
            if (bias < leastBias)
            {
                closest = cur;
            }
        }

        if (closest == cur)
        {
            leastMissing = missing;
            leastBias    = bias;
        }
    }

    if (closest == NULL)
    {
        OVR::LogError("[SDKWindow] Failed to select appropriate frame buffer.");
        XFree(nativeConfigs);
        free(usables);
        return 0;
    }

    int retVal = closest->xcfg;

    XFree(nativeConfigs);
    free(usables);

    return retVal;
}

// Obtain visual from frame buffer configuration ID.
XVisualInfo* SDKWindow::getVisual(struct _XDisplay* display,
                                  int fbConfigID, int xscreen)
{
    GLXFBConfig* cfg = getGLXFBConfig(display, fbConfigID, xscreen);
    XVisualInfo* viOut = NULL;
    if (cfg != NULL)
    {
        viOut = glXGetVisualFromFBConfig(display, *cfg);
        XFree(cfg);
        cfg = NULL;
    }
    else
    {
        OVR::LogError("Unable to find fb config ID.");
    }
    return viOut;
}

// GLXFBConfig pointer from frame buffer configuration ID. You must call
// XFree on the GLXFBConfig pointer.
GLXFBConfig* SDKWindow::getGLXFBConfig(struct _XDisplay* display,
                                       int fbConfigID, int xscreen)
{
    const int attribs[] = {GLX_FBCONFIG_ID, (int)fbConfigID, None};
    int numElems;

    GLXFBConfig* config = glXChooseFBConfig(display, xscreen, attribs, &numElems);
    if (numElems > 0)
    {
        return config;
    }
    else
    {
        return NULL;
    }
}


static int gXLastError = -1;
static int handleXError(struct _XDisplay* display, XErrorEvent* event)
{
  OVR_UNUSED(display);
  gXLastError = event->error_code;
  return 0;
}

static void obtainXErrorHandler()
{
  gXLastError = Success;
  XSetErrorHandler(handleXError);
}

static void releaseXErrorHandler(struct _XDisplay* display)
{
  XSync(display, False);
  XSetErrorHandler(NULL);
}

// Returns 0 on error, otherwise a valid X window is returned.
static Window constructWindow(struct _XDisplay* xDisp, int xScreen,
                              XVisualInfo* xVisual,
                              const LinuxDeviceScreen& devScreen)
{
    XSetWindowAttributes wa;

    Window root       = XRootWindow(xDisp, xScreen);
    Window xWindowOut = 0;

    // Create Window
    {
        Colormap xWinColorMapOut = XCreateColormap(
            xDisp, root, xVisual->visual, AllocNone);
        unsigned long wamask = CWBorderPixel | CWColormap | CWEventMask;

        wa.colormap = xWinColorMapOut;
        wa.border_pixel = 0;
        wa.event_mask = StructureNotifyMask  | ExposureMask    | FocusChangeMask
                      | VisibilityChangeMask | EnterWindowMask | LeaveWindowMask
                      | PropertyChangeMask;

        obtainXErrorHandler();

        xWindowOut = XCreateWindow(xDisp, root,
                                   0, 0,
                                   devScreen.width, devScreen.height,
                                   0,
                                   xVisual->depth,
                                   InputOutput,
                                   xVisual->visual,
                                   wamask,
                                   &wa);

        releaseXErrorHandler(xDisp);

        if (!xWindowOut)
        {
            OVR::LogError("[SDKWindow] Failed to create SDK window.");
            return 0;
        }

        XFreeColormap(xDisp, xWinColorMapOut);
    }

    // OVERRIDE REDIRECT.
    XSetWindowAttributes attributes;
    attributes.override_redirect = True;
    XChangeWindowAttributes(xDisp, xWindowOut,
                            CWOverrideRedirect, &attributes);

    // Show the window (do this in full screen or windowed).
    XMapRaised(xDisp, xWindowOut);
    XFlush(xDisp);

    // Position ourselves manually since there should be no WM managing us.
    XRaiseWindow(xDisp, xWindowOut);
    XMoveWindow(xDisp, xWindowOut, devScreen.offsetX, devScreen.offsetY);
    XResizeWindow(xDisp, xWindowOut, devScreen.width, devScreen.height);

    XFlush(xDisp);

    // WM Backup in case there still exists a WM managing us...
    Atom NET_WM_BYPASS_COMPOSITOR = 
        XInternAtom(xDisp, "_NET_WM_BYPASS_COMPOSITOR", False);
    Atom NET_WM_STATE =
        XInternAtom(xDisp, "_NET_WM_STATE", False);
    Atom NET_WM_STATE_FULLSCREEN =
        XInternAtom(xDisp, "_NET_WM_STATE_FULLSCREEN", False);
    Atom NET_ACTIVE_WINDOW =
        XInternAtom(xDisp, "_NET_ACTIVE_WINDOW", False);

    // Bypass compositor if we are under a compositing WM.
    // Just in case a WM ignores our override_redirect.
    if (NET_WM_BYPASS_COMPOSITOR)
    {
        const unsigned long bypass = 1;
        XChangeProperty(xDisp, xWindowOut,
                        NET_WM_BYPASS_COMPOSITOR,
                        XA_CARDINAL, 32, PropModeReplace,
                        (unsigned char*)&bypass, 1);
    }

    if (NET_WM_STATE && NET_WM_STATE_FULLSCREEN)
    {
        // BACKUP: If we are still managed by a WM we want fullscreen.
        const int EWMH_STATE_ADD    = 1;

        if (NET_ACTIVE_WINDOW)
        {
            XEvent event;
            memset(&event, 0, sizeof(event));

            event.type = ClientMessage;
            event.xclient.window = xWindowOut;
            event.xclient.format = 32;
            event.xclient.message_type = NET_ACTIVE_WINDOW;
            event.xclient.data.l[0] = 1;
            event.xclient.data.l[1] = 0;

            XSendEvent(xDisp, root, False,
                       SubstructureNotifyMask | SubstructureRedirectMask,
                       &event);
        }

        XEvent event;
        memset(&event, 0, sizeof(event));

        event.type = ClientMessage;
        event.xclient.window = xWindowOut;
        event.xclient.format = 32;
        event.xclient.message_type = NET_WM_STATE;
        event.xclient.data.l[0] = EWMH_STATE_ADD;
        event.xclient.data.l[1] = NET_WM_STATE_FULLSCREEN;
        event.xclient.data.l[2] = 0;
        event.xclient.data.l[3] = 1;

        XSendEvent(xDisp, root, False,
                   SubstructureNotifyMask | SubstructureRedirectMask,
                   &event);
    }

    return xWindowOut;
}

} // namespace OVR