qrhiimgui.cpp 14.6 KB
Newer Older
Laszlo Agocs's avatar
Laszlo Agocs committed
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
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt RHI module
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qrhiimgui_p.h"
#include <QFile>
Laszlo Agocs's avatar
Laszlo Agocs committed
39
40
#include <QMouseEvent>
#include <QKeyEvent>
Laszlo Agocs's avatar
Laszlo Agocs committed
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

QT_BEGIN_NAMESPACE

QRhiImgui::QRhiImgui()
    : d(new QRhiImguiPrivate)
{
}

QRhiImgui::~QRhiImgui()
{
    releaseResources();
    delete d;
}

void QRhiImgui::setFrameFunc(FrameFunc f)
{
    d->frame = f;
}

void QRhiImgui::demoWindow()
{
    ImGui::ShowDemoWindow(&d->showDemoWindow);
}

static QBakedShader getShader(const QString &name)
{
    QFile f(name);
    if (f.open(QIODevice::ReadOnly))
        return QBakedShader::fromSerialized(f.readAll());

    return QBakedShader();
}

bool QRhiImgui::imguiPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, QRhiRenderPassDescriptor *rp)
{
    ImGuiIO &io(ImGui::GetIO());

    if (d->textures.isEmpty()) {
        unsigned char *pixels;
        int w, h;
        io.Fonts->GetTexDataAsRGBA32(&pixels, &w, &h);
        const QImage wrapperImg((const uchar *) pixels, w, h, QImage::Format_RGBA8888);
        QRhiImguiPrivate::Texture t;
        t.image = wrapperImg.copy();
        d->textures.append(t);
        io.Fonts->SetTexID(reinterpret_cast<ImTextureID>(quintptr(d->textures.count() - 1)));
    }

    const QSize outputSize = rt->sizeInPixels();
    const float dpr = rt->devicePixelRatio();
    io.DisplaySize.x = outputSize.width() / dpr;
    io.DisplaySize.y = outputSize.height() / dpr;
    io.DisplayFramebufferScale = ImVec2(dpr, dpr);

Laszlo Agocs's avatar
Laszlo Agocs committed
95
96
    d->updateInput();

Laszlo Agocs's avatar
Laszlo Agocs committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    ImGui::NewFrame();
    if (d->frame)
        d->frame();
    ImGui::Render();

    ImDrawData *draw = ImGui::GetDrawData();
    draw->ScaleClipRects(ImVec2(dpr, dpr));

    QRhiResourceUpdateBatch *resUpd = d->rhi->nextResourceUpdateBatch();
    if (!d->ubuf) {
        d->ubuf = d->rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64 + 4);
        d->releasePool << d->ubuf;
        if (!d->ubuf->build())
            return false;

        float opacity = 1.0f;
        resUpd->updateDynamicBuffer(d->ubuf, 64, 4, &opacity);
    }

116
117
118
119
120
121
    if (d->lastOutputSize.width() != io.DisplaySize.x || d->lastOutputSize.height() != io.DisplaySize.y) {
        QMatrix4x4 mvp = d->rhi->clipSpaceCorrMatrix();
        mvp.ortho(0, io.DisplaySize.x, io.DisplaySize.y, 0, 1, -1);
        resUpd->updateDynamicBuffer(d->ubuf, 0, 64, mvp.constData());
        d->lastOutputSize = QSizeF(io.DisplaySize.x, io.DisplaySize.y);
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
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

    if (!d->sampler) {
        d->sampler = d->rhi->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
                                        QRhiSampler::Repeat, QRhiSampler::Repeat);
        d->releasePool << d->sampler;
        if (!d->sampler->build())
            return false;
    }

    for (QRhiImguiPrivate::Texture &t : d->textures) {
        if (!t.tex) {
            t.tex = d->rhi->newTexture(QRhiTexture::RGBA8, t.image.size());
            if (!t.tex->build())
                return false;
            resUpd->uploadTexture(t.tex, t.image);
        }
        if (!t.srb) {
            t.srb = d->rhi->newShaderResourceBindings();
            t.srb->setBindings({
                QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d->ubuf),
                QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, t.tex, d->sampler)
            });
            if (!t.srb->build())
                return false;
        }
    }

    if (!d->ps) {
        d->ps = d->rhi->newGraphicsPipeline();
        d->releasePool << d->ps;
        QRhiGraphicsPipeline::TargetBlend blend;
        blend.enable = true;
        blend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
        blend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
        blend.srcAlpha = QRhiGraphicsPipeline::One;
        blend.dstAlpha = QRhiGraphicsPipeline::Zero;
        blend.colorWrite = QRhiGraphicsPipeline::R | QRhiGraphicsPipeline::G | QRhiGraphicsPipeline::B;
        d->ps->setTargetBlends({ blend });
        d->ps->setCullMode(QRhiGraphicsPipeline::None);
        d->ps->setDepthTest(true);
        d->ps->setDepthOp(QRhiGraphicsPipeline::LessOrEqual);
        d->ps->setDepthWrite(false);
        d->ps->setFlags(QRhiGraphicsPipeline::UsesScissor);

        QBakedShader vs = getShader(QLatin1String(":/imgui.vert.qsb"));
        Q_ASSERT(vs.isValid());
        QBakedShader fs = getShader(QLatin1String(":/imgui.frag.qsb"));
        Q_ASSERT(fs.isValid());
        d->ps->setShaderStages({
            { QRhiGraphicsShaderStage::Vertex, vs },
            { QRhiGraphicsShaderStage::Fragment, fs }
        });

        QRhiVertexInputLayout inputLayout;
        inputLayout.bindings = {
            { 4 * sizeof(float) + sizeof(quint32) }
        };
        inputLayout.attributes = {
            { 0, 0, QRhiVertexInputLayout::Attribute::Float2, 0 },
            { 0, 1, QRhiVertexInputLayout::Attribute::Float2, 2 * sizeof(float) },
            { 0, 2, QRhiVertexInputLayout::Attribute::UNormByte4, 4 * sizeof(float) }
        };

        d->ps->setVertexInputLayout(inputLayout);
        d->ps->setShaderResourceBindings(d->textures[0].srb);
        d->ps->setRenderPassDescriptor(rp);

        if (!d->ps->build())
            return false;
    }

    // the imgui default
    Q_ASSERT(sizeof(ImDrawVert) == 20);
    // switched to uint in imconfig.h to avoid trouble with 4 byte offset alignment reqs
    Q_ASSERT(sizeof(ImDrawIdx) == 4);

    QVarLengthArray<quint32, 4> vbufOffsets(draw->CmdListsCount);
    QVarLengthArray<quint32, 4> ibufOffsets(draw->CmdListsCount);
    int totalVbufSize = 0;
    int totalIbufSize = 0;
    for (int n = 0; n < draw->CmdListsCount; ++n) {
        const ImDrawList *cmdList = draw->CmdLists[n];
        const int vbufSize = cmdList->VtxBuffer.Size * sizeof(ImDrawVert);
        vbufOffsets[n] = totalVbufSize;
        totalVbufSize += vbufSize;
        const int ibufSize = cmdList->IdxBuffer.Size * sizeof(ImDrawIdx);
        ibufOffsets[n] = totalIbufSize;
        totalIbufSize += ibufSize;
    }

    if (!d->vbuf) {
        d->vbuf = d->rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, totalVbufSize);
        d->releasePool << d->vbuf;
        if (!d->vbuf->build())
            return false;
    } else {
        if (totalVbufSize > d->vbuf->size()) {
            d->vbuf->setSize(totalVbufSize);
            if (!d->vbuf->build())
                return false;
        }
    }
    if (!d->ibuf) {
        d->ibuf = d->rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::IndexBuffer, totalIbufSize);
        d->releasePool << d->ibuf;
        if (!d->ibuf->build())
            return false;
    } else {
        if (totalIbufSize > d->ibuf->size()) {
            d->ibuf->setSize(totalIbufSize);
            if (!d->ibuf->build())
                return false;
        }
    }

    for (int n = 0; n < draw->CmdListsCount; ++n) {
        const ImDrawList *cmdList = draw->CmdLists[n];
        const int vbufSize = cmdList->VtxBuffer.Size * sizeof(ImDrawVert);
        resUpd->updateDynamicBuffer(d->vbuf, vbufOffsets[n], vbufSize, cmdList->VtxBuffer.Data);
        const int ibufSize = cmdList->IdxBuffer.Size * sizeof(ImDrawIdx);
        resUpd->updateDynamicBuffer(d->ibuf, ibufOffsets[n], ibufSize, cmdList->IdxBuffer.Data);
    }

    cb->beginPass(rt, { 0, 0, 0, 1 }, { 1, 0 }, resUpd);
    cb->setViewport({ 0, 0, float(outputSize.width()), float(outputSize.height()) });

    for (int n = 0; n < draw->CmdListsCount; ++n) {
        const ImDrawList *cmdList = draw->CmdLists[n];
        const ImDrawIdx *indexBufOffset = nullptr;

        for (int i = 0; i < cmdList->CmdBuffer.Size; ++i) {
            const ImDrawCmd *cmd = &cmdList->CmdBuffer[i];
            if (!cmd->UserCallback) {
                const QPointF scissorPixelBottomLeft = QPointF(cmd->ClipRect.x, outputSize.height() - cmd->ClipRect.w);
                const QSizeF scissorPixelSize = QSizeF(cmd->ClipRect.z - cmd->ClipRect.x, cmd->ClipRect.w - cmd->ClipRect.y);
                const int textureIndex = int(reinterpret_cast<qintptr>(cmd->TextureId));
                cb->setGraphicsPipeline(d->ps, d->textures[textureIndex].srb);
                cb->setScissor({ int(scissorPixelBottomLeft.x()), int(scissorPixelBottomLeft.y()),
                                 int(scissorPixelSize.width()), int(scissorPixelSize.height()) });
                cb->setVertexInput(0, { { d->vbuf, vbufOffsets[n] } },
                                   d->ibuf, ibufOffsets[n] + quintptr(indexBufOffset), QRhiCommandBuffer::IndexUInt32);
                cb->drawIndexed(cmd->ElemCount);
            } else {
                cmd->UserCallback(cmdList, cmd);
            }
            indexBufOffset += cmd->ElemCount;
        }
    }

    cb->endPass();

    return true;
}

void QRhiImgui::initialize(QRhi *rhi)
{
    d->rhi = rhi;
279
    d->lastOutputSize = QSizeF();
Laszlo Agocs's avatar
Laszlo Agocs committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
}

void QRhiImgui::releaseResources()
{
    for (QRhiImguiPrivate::Texture &t : d->textures) {
        if (t.tex)
            t.tex->releaseAndDestroy();
        if (t.srb)
            t.srb->releaseAndDestroy();
    }
    d->textures.clear();

    for (QRhiResource *r : d->releasePool)
        r->releaseAndDestroy();
    d->releasePool.clear();

    d->vbuf = d->ibuf = d->ubuf = nullptr;
    d->ps = nullptr;
    d->sampler = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
299
300
301

    delete d->inputEventFilter;
    d->inputEventFilter = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
302
303
304
305
306
307
308
}

QRhiImgui::FrameFunc QRhiImgui::frameFunc() const
{
    return d->frame;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
void QRhiImgui::setInputEventSource(QObject *src)
{
    if (d->inputEventSource && d->inputEventFilter)
        d->inputEventSource->removeEventFilter(d->inputEventFilter);

    d->inputEventSource = src;

    if (!d->inputEventFilter) {
        d->inputEventFilter = new QRhiImGuiInputEventFilter;
        d->inputInitialized = false;
    }

    d->inputEventSource->installEventFilter(d->inputEventFilter);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
324
325
326
327
328
329
330
331
332
333
QRhiImguiPrivate::QRhiImguiPrivate()
{
    ImGui::CreateContext();
}

QRhiImguiPrivate::~QRhiImguiPrivate()
{
    ImGui::DestroyContext();
}

Laszlo Agocs's avatar
Laszlo Agocs committed
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
bool QRhiImGuiInputEventFilter::eventFilter(QObject *, QEvent *event)
{
    switch (event->type()) {
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(event);
        mousePos = me->pos();
        mouseButtonsDown = me->buttons();
        modifiers = me->modifiers();
    }
        break;

    case QEvent::Wheel:
    {
        QWheelEvent *we = static_cast<QWheelEvent *>(event);
        mouseWheel += we->angleDelta().y() / 120.0f;
    }
        break;

    case QEvent::KeyPress:
    case QEvent::KeyRelease:
    {
        const bool down = event->type() == QEvent::KeyPress;
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        modifiers = ke->modifiers();
        if (down)
            keyText.append(ke->text());
        int k = ke->key();
        if (k <= 0xFF)
            keyDown[k] = down;
        else if (k >= FIRSTSPECKEY && k <= LASTSPECKEY)
            keyDown[MAPSPECKEY(k)] = down;
    }
        break;

    default:
        break;
    }

    return false;
}

void QRhiImguiPrivate::updateInput()
{
    if (!inputEventFilter)
        return;

    ImGuiIO &io = ImGui::GetIO();

    if (!inputInitialized) {
        inputInitialized = true;

        io.KeyMap[ImGuiKey_Tab] = MAPSPECKEY(Qt::Key_Tab);
        io.KeyMap[ImGuiKey_LeftArrow] = MAPSPECKEY(Qt::Key_Left);
        io.KeyMap[ImGuiKey_RightArrow] = MAPSPECKEY(Qt::Key_Right);
        io.KeyMap[ImGuiKey_UpArrow] = MAPSPECKEY(Qt::Key_Up);
        io.KeyMap[ImGuiKey_DownArrow] = MAPSPECKEY(Qt::Key_Down);
        io.KeyMap[ImGuiKey_PageUp] = MAPSPECKEY(Qt::Key_PageUp);
        io.KeyMap[ImGuiKey_PageDown] = MAPSPECKEY(Qt::Key_PageDown);
        io.KeyMap[ImGuiKey_Home] = MAPSPECKEY(Qt::Key_Home);
        io.KeyMap[ImGuiKey_End] = MAPSPECKEY(Qt::Key_End);
        io.KeyMap[ImGuiKey_Delete] = MAPSPECKEY(Qt::Key_Delete);
        io.KeyMap[ImGuiKey_Backspace] = MAPSPECKEY(Qt::Key_Backspace);
        io.KeyMap[ImGuiKey_Enter] = MAPSPECKEY(Qt::Key_Return);
        io.KeyMap[ImGuiKey_Escape] = MAPSPECKEY(Qt::Key_Escape);

        io.KeyMap[ImGuiKey_A] = Qt::Key_A;
        io.KeyMap[ImGuiKey_C] = Qt::Key_C;
        io.KeyMap[ImGuiKey_V] = Qt::Key_V;
        io.KeyMap[ImGuiKey_X] = Qt::Key_X;
        io.KeyMap[ImGuiKey_Y] = Qt::Key_Y;
        io.KeyMap[ImGuiKey_Z] = Qt::Key_Z;
    }

    QRhiImGuiInputEventFilter *w = inputEventFilter;

    io.MousePos = ImVec2(w->mousePos.x(), w->mousePos.y());

    io.MouseDown[0] = w->mouseButtonsDown.testFlag(Qt::LeftButton);
    io.MouseDown[1] = w->mouseButtonsDown.testFlag(Qt::RightButton);
    io.MouseDown[2] = w->mouseButtonsDown.testFlag(Qt::MiddleButton);

    io.MouseWheel = w->mouseWheel;
    w->mouseWheel = 0;

    io.KeyCtrl = w->modifiers.testFlag(Qt::ControlModifier);
    io.KeyShift = w->modifiers.testFlag(Qt::ShiftModifier);
    io.KeyAlt = w->modifiers.testFlag(Qt::AltModifier);
    io.KeySuper = w->modifiers.testFlag(Qt::MetaModifier);

    memcpy(io.KeysDown, w->keyDown, sizeof(w->keyDown));

    if (!w->keyText.isEmpty()) {
        for (const QChar &c : w->keyText) {
            ImWchar u = c.unicode();
            if (u)
                io.AddInputCharacter(u);
        }
        w->keyText.clear();
    }
}

Laszlo Agocs's avatar
Laszlo Agocs committed
438
QT_END_NAMESPACE