summaryrefslogtreecommitdiffhomepage
path: root/dinput/dinput.cpp
blob: 75f398ad7c66cfb48c13ecc60cc49552f1753b64 (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
#include "dinput.hpp"
#include "compat/spinlock.hpp"
#include <QDebug>

int di_t::refcnt{0};
std::atomic_flag di_t::lock = ATOMIC_FLAG_INIT;
diptr di_t::handle;

diptr di_t::init_di_()
{
    CoInitialize(nullptr);

    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();
    }

    return di;
}

di_t::di_t()
{
    ref_di();
}

void di_t::ref_di()
{
    spinlock_guard l(lock);

    if (!handle)
        handle = init_di_();

    ++refcnt;
}

void di_t::unref_di()
{
    spinlock_guard l(lock);

    const int refcnt_ = --refcnt;

    if (refcnt_ == 0)
    {
        qDebug() << "exit: di handle";
        handle->Release();
    }
}

di_t::~di_t()
{
    unref_di();
}