summaryrefslogtreecommitdiffhomepage
path: root/dinput/dinput.cpp
blob: 7a0e9cab626618e47f129c7ee66b5490075dd25b (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
#undef NDEBUG

#include "dinput.hpp"
#include "compat/macros.hpp"

#include <cassert>
#include <cstdlib>
#include <dinput.h>

#include <QDebug>

diptr di_t::handle;
QMutex di_t::lock;

diptr di_t::init_di()
{
    QMutexLocker l(&lock);

    CoInitialize(nullptr);

    if (!handle)
        handle = init_di_();

    return handle;
}

diptr di_t::operator->() const
{
    return init_di();
}

di_t::operator bool() const
{
    return !!init_di();
}

di_t::operator diptr() const
{
    return init_di();
}

diptr di_t::init_di_()
{
    diptr di = nullptr;
    HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr),
                                    DIRECTINPUT_VERSION,
                                    IID_IDirectInput8,
                                    (void**)&di,
                                    nullptr);
    if (!SUCCEEDED(hr))
    {
        qDebug() << "can't make dinput:" << (void*)(LONG_PTR)hr;
        qDebug() << "crashing!";
        std::abort();
    }

    //qDebug() << "dinput: initialized";

    return di;
}

di_t::di_t() = default;

bool di_t::poll_device(IDirectInputDevice8A* dev)
{
    HRESULT hr;
    assert(handle);

    switch (dev->Poll())
    {
    case DI_OK:
    case DI_NOEFFECT:
        return true;
    default:
        break;
    }

    switch (hr = dev->Acquire())
    {
    default:
        break;
    case DI_OK:
    case S_FALSE:
        switch (hr = dev->Poll())
        {
        case DI_OK:
        case DI_NOEFFECT:
            return true;
        default:
            break;
        }
        break;
    }

    eval_once(qDebug() << "dinput: device poll failed:" << (void*)hr);

    return false;
}