• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

graphia-app / graphia / 43586110479

14 Nov 2026 10:32AM UTC coverage: 70.378%. First build
43586110479

push

github

timangus
Add a debug submenu to switch each detail level on and off

11927 of 18500 branches covered (64.47%)

Branch coverage included in aggregate %.

6 of 53 new or added lines in 7 files covered. (11.32%)

30542 of 41844 relevant lines covered (72.99%)

258965.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/source/app/rendering/graphrenderer.cpp
1
/* Copyright © 2013-2025 Tim Angus
2
 * Copyright © 2013-2025 Tom Freeman
3
 *
4
 * This file is part of Graphia.
5
 *
6
 * Graphia 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
 * Graphia 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 Graphia.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
#include "graphrenderer.h"
21

22
#include "graphcomponentscene.h"
23
#include "graphoverviewscene.h"
24

25
#include "app/layout/nodepositions.h"
26

27
#include "shared/utils/container.h"
28
#include "shared/utils/doasyncthen.h"
29

30
#include "app/graph/graph.h"
31
#include "shared/graph/igraphcomponent.h"
32
#include "app/maths/boundingsphere.h"
33
#include "app/graph/graphmodel.h"
34

35
#include "app/ui/graphcomponentinteractor.h"
36
#include "app/ui/graphoverviewinteractor.h"
37
#include "app/ui/selectionmanager.h"
38
#include "app/ui/visualisations/elementvisual.h"
39
#include "app/ui/visualisations/textvisual.h"
40
#include "app/ui/qml/Graphia/graphdisplay.h"
41

42
#include "shadertools.h"
43
#include "screenshotrenderer.h"
44

45
#include <QCoreApplication>
46
#include <QDebug>
47
#include <QOpenGLFramebufferObjectFormat>
48
#include <QQuickOpenGLUtils>
49
#include <QOpenGLDebugLogger>
50
#include <QQuickWindow>
51
#include <QNativeGestureEvent>
52
#include <QTextLayout>
53
#include <QBuffer>
54
#include <QFutureWatcher>
55
#include <QMouseEvent>
56
#include <QOpenGLFramebufferObject>
57
#include <QWheelEvent>
58
#include <QtGlobal>
59

60
#include <algorithm>
61
#include <array>
62
#include <chrono>
63
#include <functional>
64
#include <limits>
65
#include <utility>
66

67
using namespace Qt::Literals::StringLiterals;
68

69
template<typename Target>
70
void initialiseFromGraph(const Graph* graph, Target& target)
71
{
×
72
    for(auto componentId : graph->componentIds())
×
73
        target.onComponentAdded(graph, componentId, false);
×
74

75
    target.onGraphChanged(graph, true);
×
76
}
×
77

78
GraphRenderer::GraphRenderer(GraphModel* graphModel, CommandManager* commandManager, SelectionManager* selectionManager) :
79
    _graphModel(graphModel),
×
80
    _selectionManager(selectionManager),
×
81
    _componentRenderers(_graphModel->graph()),
×
82
    _graphOverviewScene(new GraphOverviewScene(commandManager, this)),
×
83
    _graphComponentScene(new GraphComponentScene(this)),
×
84
    _graphOverviewInteractor(new GraphOverviewInteractor(_graphModel, _graphOverviewScene, commandManager, _selectionManager, this)),
×
85
    _graphComponentInteractor(new GraphComponentInteractor(_graphModel, _graphComponentScene, commandManager, _selectionManager, this)),
×
86
    _hiddenNodes(_graphModel->graph()),
×
87
    _hiddenEdges(_graphModel->graph()),
×
88
    _layoutChanged(true),
×
89
    _performanceCounter(std::chrono::seconds(1))
×
90
{
×
91
    ShaderTools::loadShaderProgram(_debugLinesShader, u":/shaders/debuglines.vert"_s, u":/shaders/debuglines.frag"_s);
×
92

93
    _glyphMap = std::make_unique<GlyphMap>(u::pref(u"visuals/textFont"_s).toString());
×
94

95
    const auto* graph = &_graphModel->graph();
×
96

97
    connect(graph, &Graph::nodeAdded, this, &GraphRenderer::onNodeAdded, Qt::DirectConnection);
×
98
    connect(graph, &Graph::edgeAdded, this, &GraphRenderer::onEdgeAdded, Qt::DirectConnection);
×
99
    connect(graph, &Graph::nodeAddedToComponent, this, &GraphRenderer::onNodeAddedToComponent, Qt::DirectConnection);
×
100
    connect(graph, &Graph::edgeAddedToComponent, this, &GraphRenderer::onEdgeAddedToComponent, Qt::DirectConnection);
×
101
    connect(graph, &Graph::nodeMovedBetweenComponents, this, &GraphRenderer::onNodeMovedBetweenComponents, Qt::DirectConnection);
×
102
    connect(graph, &Graph::edgeMovedBetweenComponents, this, &GraphRenderer::onEdgeMovedBetweenComponents, Qt::DirectConnection);
×
103

104
    connect(graph, &Graph::graphWillChange, this, &GraphRenderer::onGraphWillChange, Qt::DirectConnection);
×
105
    connect(graph, &Graph::graphChanged, this, &GraphRenderer::onGraphChanged, Qt::DirectConnection);
×
106
    connect(graph, &Graph::componentAdded, this, &GraphRenderer::onComponentAdded, Qt::DirectConnection);
×
107

108
    connect(&_transition, &Transition::started, this, &GraphRenderer::rendererStartedTransition, Qt::DirectConnection);
×
109
    connect(&_transition, &Transition::finished, this, &GraphRenderer::rendererFinishedTransition, Qt::DirectConnection);
×
110

111
    connect(graph, &Graph::componentWillBeRemoved, this, &GraphRenderer::onComponentWillBeRemoved, Qt::DirectConnection);
×
112

113
    _screenshotRenderer = std::make_unique<ScreenshotRenderer>();
×
114
    connect(_screenshotRenderer.get(), &ScreenshotRenderer::screenshotComplete, this, &GraphRenderer::screenshotComplete);
×
115
    connect(_screenshotRenderer.get(), &ScreenshotRenderer::previewComplete, this, &GraphRenderer::previewComplete);
×
116

117
    connect(&_preferencesWatcher, &PreferencesWatcher::preferenceChanged,
×
118
        this, &GraphRenderer::onPreferenceChanged, Qt::DirectConnection);
×
119

120
    connect(_graphModel, &GraphModel::visualsWillChange, [this]
×
121
    {
×
122
        _visualsChanging = true;
×
123
        disableSceneUpdate();
×
124
    });
×
125

126
    connect(_graphModel, &GraphModel::visualsChanged, [this](
×
127
        VisualChangeFlags nodeChange, VisualChangeFlags edgeChange, VisualChangeFlags textChange)
×
128
    {
×
129
        auto textChanged = [](VisualChangeFlags change)
×
130
        {
×
131
            return Flags<VisualChangeFlags>(change).test(VisualChangeFlags::Text);
×
132
        };
×
133

134
        // Changing the font forces a visual update, and it is here that the glyphs are
135
        // rebuilt in the new font, since updateText reads every element's text, and so
136
        // must not happen alongside another visual update
137
        _glyphMap->setFontName(u::pref(u"visuals/textFont"_s).toString());
×
138

139
        if(textChanged(nodeChange) || textChanged(edgeChange) ||
×
140
            textChange != VisualChangeFlags::None || _glyphMap->updateRequired())
×
141
        {
×
142
            updateText();
×
143
        }
×
144

145
        executeOnRendererThread([this]
×
146
        {
×
147
            updateGPUData(When::Later);
×
148
            update(); // QQuickFramebufferObject::Renderer::update
×
149
        }, u"GraphRenderer::visualsChanged"_s);
×
150

151
        if(_visualsChanging.exchange(false))
×
152
            enableSceneUpdate();
×
153
    });
×
154

155
    _performanceCounter.setReportFn([this](float ticksPerSecond)
×
156
    {
×
157
        emit fpsChanged(ticksPerSecond);
×
158
    });
×
159

160
    u::doAsync([this, graph]
×
161
    {
×
162
        const std::unique_lock<std::mutex> lock(_initialisationMutex);
×
163

164
        // This reads the visuals, so it keeps visual updates out; not with the scene update
165
        // lock, as the frame takes that too, and it would wait here for the whole of this
166
        _graphModel->readVisuals([this, graph]
×
167
        {
×
168
            initialiseFromGraph(graph, *this);
×
169
            initialiseFromGraph(graph, *_graphOverviewScene);
×
170
            initialiseFromGraph(graph, *_graphComponentScene);
×
171

172
            // If the graph is a single component or empty, use component mode by default
173
            if(graph->numComponents() <= 1)
×
174
                switchToComponentMode("doTransition"_no);
×
175
            else
×
176
                switchToOverviewMode("doTransition"_no);
×
177

178
            updateText();
×
179
        });
×
180

181
        // Wait for the layout to have iterated at least once, so that what is
182
        // first displayed is a (partially) laid out graph, rather than every node
183
        // drawn on top of itself
184
        _layoutInitialised.wait(false);
×
185

186
    }).then([this]
×
187
    {
×
188
        emit initialised();
×
189

190
        // The initial state is disabled, so this has no complement disableSceneUpdate call
191
        enableSceneUpdate();
×
192
        update();
×
193
    });
×
194
}
×
195

196
GraphRenderer::~GraphRenderer()
197
{
×
198
    _layoutInitialised = true;
×
199
    _layoutInitialised.notify_all();
×
200

201
    const std::unique_lock<std::mutex> lock(_initialisationMutex);
×
202

203
    // Force event processing in case the above .then(...) is still to run (due to a slow init)
204
    QCoreApplication::processEvents();
×
205

206
    _FBOcomplete = false;
×
207
}
×
208

209
void GraphRenderer::createGPUGlyphData(const QString& text, const QColor& textColor, const TextAlignment& textAlignment,
210
                                    float textScale, float elementSize, const TextAnchor& anchor,
211
                                    int componentIndex, GPUGraphData* gpuGraphData)
212
{
×
213
    Q_ASSERT(gpuGraphData != nullptr);
×
214

215
    auto& textLayout = _textLayoutResults._layouts[text];
×
216
    Q_ASSERT(textLayout._initialised);
×
217

218
    const auto verticalCentre = -textLayout._xHeight * textScale * 0.5f;
×
219
    const auto top = elementSize;
×
220
    const auto bottom = (-elementSize) - (textLayout._xHeight * textScale);
×
221

222
    const auto horizontalCentre = -textLayout._width * textScale * 0.5f;
×
223
    const auto right = elementSize;
×
224
    const auto left = (-elementSize) - (textLayout._width * textScale);
×
225

226
    std::array<float, 2> baseOffset{{0.0f, 0.0f}};
×
227
    switch(textAlignment)
×
228
    {
×
229
    default:
×
230
    case TextAlignment::Right:  baseOffset = {{right,            verticalCentre}}; break;
×
231
    case TextAlignment::Left:   baseOffset = {{left,             verticalCentre}}; break;
×
232
    case TextAlignment::Centre: baseOffset = {{horizontalCentre, verticalCentre}}; break;
×
233
    case TextAlignment::Top:    baseOffset = {{horizontalCentre, top           }}; break;
×
234
    case TextAlignment::Bottom: baseOffset = {{horizontalCentre, bottom        }}; break;
×
235
    }
×
236

237
    for(const auto& glyph : textLayout._glyphs)
×
238
    {
×
239
        GPUGraphData::GlyphData glyphData;
×
240

241
        auto textureGlyph = _textLayoutResults._glyphs[glyph._index];
×
242

243
        glyphData._component = componentIndex;
×
244

245
        glyphData._glyphOffset[0] = baseOffset[0] + (static_cast<float>(glyph._advance) * textScale);
×
246
        glyphData._glyphOffset[1] = baseOffset[1] - ((textureGlyph._height + textureGlyph._ascent) * textScale);
×
247
        glyphData._glyphSize[0] = textureGlyph._width;
×
248
        glyphData._glyphSize[1] = textureGlyph._height;
×
249
        glyphData._glyphScale = textScale;
×
250
        glyphData._textHeight = textLayout._xHeight * textScale;
×
251

252
        glyphData._textureCoord[0] = textureGlyph._u;
×
253
        glyphData._textureCoord[1] = textureGlyph._v;
×
254
        glyphData._textureLayer = textureGlyph._layer;
×
255

256
        glyphData._anchorNodes[0] = static_cast<int>(anchor._nodeIds[0]);
×
257
        glyphData._anchorNodes[1] = static_cast<int>(anchor._nodeIds[1]);
×
258

259
        glyphData._basePosition[0] = anchor._position.x();
×
260
        glyphData._basePosition[1] = anchor._position.y();
×
261
        glyphData._basePosition[2] = anchor._position.z();
×
262

263
        glyphData._color[0] = textColor.redF();
×
264
        glyphData._color[1] = textColor.greenF();
×
265
        glyphData._color[2] = textColor.blueF();
×
266

267
        gpuGraphData->addGlyph(glyphData);
×
268
    }
×
269
}
×
270

271
void GraphRenderer::updateGPUNodePositions()
272
{
×
273
    auto& nodePositions = _graphModel->nodePositions();
×
274
    const std::unique_lock<NodePositions> nodePositionsLock(nodePositions);
×
275

276
    nodeGeometry().setPositions(_graphModel->graph().nodeIds(), nodePositions);
×
277
}
×
278

279
void GraphRenderer::updateGPUNodeSizes()
280
{
×
281
    auto& geometry = nodeGeometry();
×
282

283
    for(auto nodeId : _graphModel->graph().nodeIds())
×
284
        geometry.setSize(nodeId, _graphModel->nodeVisual(nodeId)._size);
×
285
}
×
286

287
void GraphRenderer::updateGPUDataIfRequired()
288
{
×
289
    const auto update = std::exchange(_pendingGPUDataUpdate, GPUDataUpdate::None);
×
290

291
    if(update == GPUDataUpdate::None)
×
292
        return;
×
293

294
    // Everything else follows the nodes, except shared text, which is placed
295
    // where it is created
296
    if(update == GPUDataUpdate::NodePositions && !_graphModel->hasTextVisuals())
×
297
    {
×
298
        updateGPUNodePositions();
×
299
        uploadNodeGeometry();
×
300
        return;
×
301
    }
×
302

303
    const std::unique_lock<std::recursive_mutex> glyphMapLock(_glyphMap->mutex());
×
304

305
    int componentIndex = 0;
×
306

307
    resetGPUGraphData();
×
308

309
    updateGPUNodePositions();
×
310
    updateGPUNodeSizes();
×
311

312
    const float textScale = u::pref(u"visuals/textSize"_s).toFloat();
×
313
    auto textAlignment = normaliseQmlEnum<TextAlignment>(u::pref(u"visuals/textAlignment"_s).toInt());
×
314
    auto showNodeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showNodeText"_s).toInt());
×
315
    auto showEdgeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showEdgeText"_s).toInt());
×
316
    auto edgeVisualType = normaliseQmlEnum<EdgeVisualType>(u::pref(u"visuals/edgeVisualType"_s).toInt());
×
317

318
    // Ignore the setting if the graph is undirected
319
    if(!_graphModel->directed())
×
320
        edgeVisualType = EdgeVisualType::Cylinder;
×
321

322
    class Layer
×
323
    {
×
324
    public:
×
325
        explicit Layer(std::function<GPUGraphData*()> claimFn) :
×
326
            _claimFn(std::move(claimFn))
×
327
        {}
×
328

329
        GPUGraphData* get()
×
330
        {
×
331
            if(_layer == nullptr)
×
332
                _layer = _claimFn();
×
333

334
            return _layer;
×
335
        }
×
336

337
    private:
×
338
        std::function<GPUGraphData*()> _claimFn;
×
339
        GPUGraphData* _layer = nullptr;
×
340
    };
×
341

342
    for(const auto& componentRendererRef : _componentRenderers)
×
343
    {
×
344
        GraphComponentRenderer* componentRenderer = componentRendererRef;
×
345
        if(!componentRenderer->visible())
×
346
            continue;
×
347

348
        const float UnhighlightedAlpha = 0.22f;
×
349
        const float componentAlpha = componentRenderer->alpha();
×
350

351
        Layer highlightedLayer([this, componentAlpha]
×
352
            { return gpuGraphDataForAlpha(componentAlpha, 1.0f); });
×
353
        Layer unhighlightedLayer([this, componentAlpha, UnhighlightedAlpha]
×
354
            { return gpuGraphDataForAlpha(componentAlpha, UnhighlightedAlpha); });
×
355
        Layer textLayer([this, componentAlpha]
×
356
            { return gpuGraphDataForOverlay(componentAlpha); });
×
357

358
        auto layerFor = [&](const ElementVisual& visual)
×
359
        {
×
360
            return visual._state.test(VisualFlags::Unhighlighted) ?
×
361
                unhighlightedLayer.get() : highlightedLayer.get();
×
362
        };
×
363

364
        for(auto nodeId : componentRenderer->nodeIds())
×
365
        {
×
366
            if(_hiddenNodes.get(nodeId))
×
367
                continue;
×
368

369
            const auto& nodeVisual = _graphModel->nodeVisual(nodeId);
×
370

371
            // Create and add NodeData
372
            GPUGraphData::NodeData nodeData;
×
373
            nodeData._nodeIndex = static_cast<int>(nodeId);
×
374
            nodeData._component = componentIndex;
×
375
            nodeData._outerColor = GPUGraphData::colorFrom(nodeVisual._outerColor);
×
376
            nodeData._innerColor = GPUGraphData::colorFrom(nodeVisual._innerColor);
×
377
            nodeData._selected = nodeVisual._state.test(VisualFlags::Selected) ? 1.0f : 0.0f;
×
378

379
            auto* gpuGraphData = layerFor(nodeVisual);
×
380

381
            if(gpuGraphData != nullptr)
×
382
            {
×
383
                gpuGraphData->addNode(nodeData, nodeVisual._size);
×
384

385
                if(nodeData._selected != 0.0f)
×
386
                    gpuGraphData->_elementsSelected = true;
×
387

388
                if(nodeVisual._text.isEmpty())
×
389
                    continue;
×
390

391
                if(showNodeText == TextState::Off || nodeVisual._state.test(VisualFlags::Unhighlighted))
×
392
                    continue;
×
393

394
                if(showNodeText == TextState::Selected && !nodeVisual._state.test(VisualFlags::Selected))
×
395
                    continue;
×
396

397
                if(showNodeText == TextState::Focused && componentRenderer->focusNodeId() != nodeId)
×
398
                    continue;
×
399

400
                createGPUGlyphData(nodeVisual._text,
×
401
                    nodeVisual._textColor, textAlignment,
×
402
                    textScale * nodeVisual._textSize,
×
403
                    nodeVisual._size, TextAnchor(nodeId), componentIndex,
×
404
                    textLayer.get());
×
405
            }
×
406
        }
×
407

408
        for(const auto& edge : componentRenderer->edges())
×
409
        {
×
410
            if(_hiddenEdges.get(edge->id()) || _hiddenNodes.get(edge->sourceId()) || _hiddenNodes.get(edge->targetId()))
×
411
                continue;
×
412

413
            const auto& edgeVisual = _graphModel->edgeVisual(edge->id());
×
414

415
            GPUGraphData::EdgeData edgeData;
×
416
            edgeData._sourceIndex = static_cast<int>(edge->sourceId());
×
417
            edgeData._targetIndex = static_cast<int>(edge->targetId());
×
418
            edgeData._edgeType = static_cast<int>(edgeVisualType);
×
419
            edgeData._component = componentIndex;
×
420
            edgeData._size = edgeVisual._size;
×
421
            edgeData._outerColor = GPUGraphData::colorFrom(edgeVisual._outerColor);
×
422
            edgeData._innerColor = GPUGraphData::colorFrom(edgeVisual._innerColor);
×
423
            edgeData._selected = 0.0f;
×
424

425
            auto* gpuGraphData = layerFor(edgeVisual);
×
426

427
            if(gpuGraphData != nullptr)
×
428
            {
×
429
                gpuGraphData->addEdge(edgeData);
×
430

431
                if(edgeData._selected != 0.0f)
×
432
                    gpuGraphData->_elementsSelected = true;
×
433

434
                if(edgeVisual._text.isEmpty())
×
435
                    continue;
×
436

437
                if(showEdgeText == TextState::Off || edgeVisual._state.test(VisualFlags::Unhighlighted))
×
438
                    continue;
×
439

440
                if(showEdgeText == TextState::Selected && !edgeVisual._state.test(VisualFlags::Selected))
×
441
                    continue;
×
442

443
                createGPUGlyphData(edgeVisual._text,
×
444
                    edgeVisual._textColor, textAlignment,
×
445
                    textScale * edgeVisual._textSize,
×
446
                    edgeVisual._size, TextAnchor(edge->sourceId(), edge->targetId()), componentIndex,
×
447
                    textLayer.get());
×
448
            }
×
449
        }
×
450

451
        _graphModel->forEachTextVisual(componentRenderer->componentId(),
×
452
        [&](const TextVisual& textVisual)
×
453
        {
×
454
            createGPUGlyphData(textVisual._text,
×
455
                textVisual._color, textAlignment,
×
456
                textScale * textVisual._size,
×
457
                textVisual._radius, TextAnchor(textVisual._centre), componentIndex,
×
458
                textLayer.get());
×
459
        });
×
460

461
        componentIndex++;
×
462
    }
×
463

464
    uploadNodeGeometry();
×
465
    uploadGPUGraphData();
×
466
}
×
467

468
void GraphRenderer::updateGPUData(GraphRenderer::When when, GPUDataUpdate update)
469
{
×
470
    _pendingGPUDataUpdate = std::max(_pendingGPUDataUpdate, update);
×
471

472
    if(when == When::Now)
×
473
        updateGPUDataIfRequired();
×
474
}
×
475

476
void GraphRenderer::onPreviewRequested(int width, int height, bool fillSize)
477
{
×
478
    makeContextCurrent();
×
479
    _screenshotRenderer->requestPreview(*this, width, height, fillSize);
×
480
}
×
481

482
void GraphRenderer::onScreenshotRequested(int width, int height, const QString& path, int dpi, bool fillSize)
483
{
×
484
    makeContextCurrent();
×
485
    _screenshotRenderer->requestScreenshot(*this, width, height, path, dpi, fillSize);
×
486
}
×
487

488
void GraphRenderer::updateComponentGPUData()
489
{
×
490
    //FIXME this doesn't necessarily need to be entirely regenerated and rebuffered
491
    // every frame, so it makes sense to do partial updates as and when required.
492
    // OTOH, it's probably not ever going to be masses of data, so maybe we should
493
    // just suck it up; need to get a profiler on it and see how long we're spending
494
    // here transfering the buffer, when there are lots of components
495
    resetGPUComponentData();
×
496

497
    for(const auto& componentRendererRef : _componentRenderers)
×
498
    {
×
499
        GraphComponentRenderer* componentRenderer = componentRendererRef;
×
500
        if(componentRenderer == nullptr)
×
501
        {
×
502
            qWarning() << "null component renderer";
×
503
            continue;
×
504
        }
×
505

506
        if(!componentRenderer->visible())
×
507
            continue;
×
508

509
        appendGPUComponentData(componentRenderer->modelViewMatrix(),
×
510
            componentRenderer->projectionMatrix(),
×
511
            componentRenderer->camera()->distance(),
×
512
            componentRenderer->lightScale(),
×
513
            componentRenderer->maxDistanceFromFocus());
×
514
    }
×
515

516
    uploadGPUComponentData();
×
517
}
×
518

519
// The selection rectangle is drawn into the gathered picture, so moving it restarts gathering
520
void GraphRenderer::setSelectionRect(const QRect& selectionRect)
521
{
×
522
    if(selectionRect == _selectionRect)
×
523
        return;
×
524

525
    _selectionRect = selectionRect;
×
526
    restartGathering();
×
527
}
×
528

529
void GraphRenderer::setScene(Scene* scene)
530
{
×
531
    if(_scene != nullptr)
×
532
    {
×
533
        _scene->setVisible(false);
×
534
        _scene->onHide();
×
535
    }
×
536

537
    _scene = scene;
×
538

539
    _scene->setViewportSize(width(), height());
×
540

541
    _scene->setProjection(_projection);
×
542
    _scene->setVisible(true);
×
543
    _scene->onShow();
×
544
}
×
545

546
GraphRenderer::Mode GraphRenderer::mode() const
547
{
×
548
    return _mode;
×
549
}
×
550

551
void GraphRenderer::setMode(Mode mode)
552
{
×
553
    if(mode != _mode)
×
554
    {
×
555
        _mode = mode;
×
556
        emit modeChanged();
×
557
    }
×
558
}
×
559

560
Projection GraphRenderer::projection() const
561
{
×
562
    return _projection;
×
563
}
×
564

565
void GraphRenderer::setProjection(Projection projection)
566
{
×
567
    if(projection != _projection)
×
568
    {
×
569
        _projection = projection;
×
570

571
        if(_scene != nullptr)
×
572
            _scene->setProjection(projection);
×
573
    }
×
574
}
×
575

576
void GraphRenderer::resetTime()
577
{
×
578
    _time.start();
×
579
    _lastTime = 0.0f;
×
580
}
×
581

582
float GraphRenderer::secondsElapsed()
583
{
×
584
    const float time = static_cast<float>(_time.elapsed()) / 1000.0f;
×
585
    const float dTime = time - _lastTime;
×
586
    _lastTime = time;
×
587

588
    return dTime;
×
589
}
×
590

591
bool GraphRenderer::transitionActive() const
592
{
×
593
    return _transition.active() || _scene->transitionActive();
×
594
}
×
595

596
void GraphRenderer::moveFocusToNode(NodeId nodeId, float radius)
597
{
×
598
    if(mode() == Mode::Component)
×
599
    {
×
600
        if(!_graphComponentScene->focusedOnNodeAtRadius(nodeId, radius))
×
601
            rendererStartedTransition();
×
602

603
        executeOnRendererThread([this, nodeId, radius]
×
604
        {
×
605
            _graphComponentScene->moveFocusToNode(nodeId, radius);
×
606
        }, u"GraphRenderer::moveFocusToNode"_s);
×
607
    }
×
608
    else if(mode() == Mode::Overview)
×
609
    {
×
610
        // To focus on a node, we need to be in component mode
611
        auto componentId = _graphModel->graph().componentIdOfNode(nodeId);
×
612
        switchToComponentMode("doTransition"_yes, componentId, nodeId, radius);
×
613
    }
×
614
}
×
615

616
void GraphRenderer::moveFocusToComponent(ComponentId componentId)
617
{
×
618
    if(mode() == Mode::Component)
×
619
    {
×
620
        if(componentId != _graphComponentScene->componentId())
×
621
            rendererStartedTransition();
×
622

623
        _graphComponentScene->setComponentId(componentId, "doTransition"_yes);
×
624
    }
×
625
}
×
626

627
void GraphRenderer::moveFocusToComponents(const std::vector<ComponentId>& componentIds)
628
{
×
629
    if(mode() == Mode::Overview)
×
630
        _graphOverviewScene->zoomTo(componentIds);
×
631
}
×
632

633
void GraphRenderer::rendererStartedTransition()
634
{
×
635
    if(!_transitionPotentiallyInProgress)
×
636
    {
×
637
        _transitionPotentiallyInProgress = true;
×
638

639
        emit transitionStarted();
×
640
        resetTime();
×
641
    }
×
642
}
×
643

644
void GraphRenderer::rendererFinishedTransition()
645
{
×
646
    if(transitionActive())
×
647
        return;
×
648

649
    // The transition may have been initiated by changes that
650
    // require the GPU data to be updated, so ensure this is done
651
    updateGPUData(When::Later);
×
652

653
    _transitionPotentiallyInProgress = false;
×
654
    emit transitionFinished();
×
655
}
×
656

657
void GraphRenderer::sceneFinishedTransition()
658
{
×
659
    clearHiddenElements();
×
660
    updateGPUData(When::Later);
×
661
}
×
662

663
void GraphRenderer::executeOnRendererThread(DeferredExecutor::TaskFn task, const QString& description)
664
{
×
665
    _preUpdateExecutor.enqueue(std::move(task), description);
×
666
    emit taskAddedToExecutor();
×
667
}
×
668

669
// Stop the renderer thread executing any tasks until...
670
void GraphRenderer::pauseRendererThreadExecution()
671
{
×
672
    _preUpdateExecutor.pause();
×
673
}
×
674

675
// ...this is called
676
void GraphRenderer::resumeRendererThreadExecution()
677
{
×
678
    _preUpdateExecutor.resume();
×
679
}
×
680

681
bool GraphRenderer::visible() const
682
{
×
683
    return _graphOverviewScene->visible() || _graphComponentScene->visible();
×
684
}
×
685

686
void GraphRenderer::onNodeAdded(const Graph*, NodeId nodeId)
687
{
×
688
    _hiddenNodes.set(nodeId, true);
×
689
}
×
690

691
void GraphRenderer::onEdgeAdded(const Graph*, EdgeId edgeId)
692
{
×
693
    _hiddenEdges.set(edgeId, true);
×
694
}
×
695

696
void GraphRenderer::onNodeAddedToComponent(const Graph*, NodeId nodeId, ComponentId)
697
{
×
698
    _hiddenNodes.set(nodeId, true);
×
699
}
×
700

701
void GraphRenderer::onEdgeAddedToComponent(const Graph*, EdgeId edgeId, ComponentId)
702
{
×
703
    _hiddenEdges.set(edgeId, true);
×
704
}
×
705

706
void GraphRenderer::onNodeMovedBetweenComponents(const Graph*, NodeId nodeId, ComponentId, ComponentId)
707
{
×
708
    _hiddenNodes.set(nodeId, true);
×
709
}
×
710

711
void GraphRenderer::onEdgeMovedBetweenComponents(const Graph*, EdgeId edgeId, ComponentId, ComponentId)
712
{
×
713
    _hiddenEdges.set(edgeId, true);
×
714
}
×
715

716
void GraphRenderer::finishTransitionToOverviewMode(NamedBool<"doTransition"> doTransition,
717
    const std::vector<ComponentId>& focusComponentIds)
718
{
×
719
    // If component mode has a queued transition nodeId, cancel the switch to overview
720
    if(_graphComponentScene->performQueuedTransition())
×
721
        return;
×
722

723
    setMode(GraphRenderer::Mode::Overview);
×
724
    setScene(_graphOverviewScene);
×
725
    setInteractor(_graphOverviewInteractor);
×
726

727
    _graphOverviewScene->resetView("doTransition"_no);
×
728

729
    if(doTransition)
×
730
    {
×
731
        // When we first change to overview mode we want all
732
        // the renderers to be in their reset state
733
        for(auto componentId : _graphModel->graph().componentIds())
×
734
        {
×
735
            auto* renderer = componentRendererForId(componentId);
×
736
            renderer->resetView();
×
737
        }
×
738

739
        _graphOverviewScene->startTransitionFromComponentMode(
×
740
            _graphComponentScene->componentId(), focusComponentIds);
×
741
    }
×
742

743
    updateGPUData(When::Later);
×
744
}
×
745

746
void GraphRenderer::finishTransitionToOverviewModeOnRendererThread(NamedBool<"doTransition"> doTransition,
747
    const std::vector<ComponentId>& focusComponentIds)
748
{
×
749
    executeOnRendererThread([this, doTransition, focusComponentIds]
×
750
    {
×
751
        finishTransitionToOverviewMode(doTransition, focusComponentIds);
×
752
    }, u"GraphRenderer::finishTransitionToOverviewMode"_s);
×
753
}
×
754

755
void GraphRenderer::finishTransitionToComponentMode(NamedBool<"doTransition"> doTransition)
756
{
×
757
    setMode(GraphRenderer::Mode::Component);
×
758
    setScene(_graphComponentScene);
×
759
    setInteractor(_graphComponentInteractor);
×
760

761
    if(doTransition)
×
762
    {
×
763
        // Go back to where we were before
764
        _graphComponentScene->startTransition().then([this] { _graphComponentScene->performQueuedTransition(); });
×
765
        _graphComponentScene->restoreViewData();
×
766
    }
×
767

768
    updateGPUData(When::Later);
×
769
}
×
770

771
void GraphRenderer::finishTransitionToComponentModeOnRendererThread(NamedBool<"doTransition"> doTransition)
772
{
×
773
    executeOnRendererThread([this, doTransition]
×
774
    {
×
775
        finishTransitionToComponentMode(doTransition);
×
776
    }, u"GraphRenderer::finishTransitionToComponentMode"_s);
×
777
}
×
778

779
void GraphRenderer::switchToOverviewMode(NamedBool<"doTransition"> doTransition, const std::vector<ComponentId>& focusComponentIds)
780
{
×
781
    // Refuse to switch to overview mode if there is nothing to display
782
    if(_graphModel->graph().numComponents() <= 1)
×
783
        return;
×
784

785
    doTransition = doTransition && mode() != GraphRenderer::Mode::Overview &&
×
786
        _graphComponentScene->componentRenderer() != nullptr;
×
787

788
    if(doTransition)
×
789
        rendererStartedTransition();
×
790

791
    executeOnRendererThread([this, doTransition, focusComponentIds]
×
792
    {
×
793
        // So that we can return to the current view parameters later
794
        _graphComponentScene->saveViewData();
×
795

796
        if(doTransition)
×
797
        {
×
798
            _graphComponentScene->clearQueuedTransition();;
×
799

800
            auto doPostViewResetTransition = [this, focusComponentIds]
×
801
            {
×
802
                sceneFinishedTransition();
×
803
                _transition.willBeImmediatelyReused();
×
804
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
×
805
            };
×
806

807
            if(!_graphComponentScene->viewIsReset())
×
808
            {
×
809
                _graphComponentScene->startTransition().then(doPostViewResetTransition);
×
810
                _graphComponentScene->resetView("doTransition"_no);
×
811
            }
×
812
            else if(_graphComponentScene->transitionActive())
×
813
            {
×
814
                // The view reset transition is still in progress but our ultimate
815
                // target has (potentially) changed
816
                _transition.alternativeThen(doPostViewResetTransition);
×
817
            }
×
818
            else
×
819
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
×
820
        }
×
821
        else
×
822
            finishTransitionToOverviewMode("doTransition"_no, focusComponentIds);
×
823

824
    }, u"GraphRenderer::switchToOverviewMode"_s);
×
825
}
×
826

827
void GraphRenderer::switchToComponentMode(NamedBool<"doTransition"> doTransition, ComponentId componentId, NodeId nodeId, float radius)
828
{
×
829
    doTransition = doTransition && mode() != GraphRenderer::Mode::Component;
×
830

831
    if(doTransition)
×
832
        rendererStartedTransition();
×
833

834
    executeOnRendererThread([this, componentId, nodeId, radius, doTransition]
×
835
    {
×
836
        _graphComponentScene->setComponentId(componentId);
×
837

838
        if(doTransition)
×
839
        {
×
840
            _graphOverviewScene->startTransitionToComponentMode(_graphComponentScene->componentId()).then(
×
841
            [this, componentId, nodeId, radius]
×
842
            {
×
843
                if(!nodeId.isNull())
×
844
                {
×
845
                    Q_ASSERT(_graphModel->graph().componentIdOfNode(nodeId) == componentId);
×
846
                    componentRendererForId(componentId)->moveSavedFocusToNode(nodeId, radius);
×
847
                }
×
848

849
                if(!_graphComponentScene->savedViewIsReset())
×
850
                {
×
851
                    _transition.willBeImmediatelyReused();
×
852
                    finishTransitionToComponentModeOnRendererThread("doTransition"_yes);
×
853
                }
×
854
                else
×
855
                    finishTransitionToComponentModeOnRendererThread("doTransition"_no);
×
856
            });
×
857
        }
×
858
        else
×
859
            finishTransitionToComponentMode("doTransition"_no);
×
860

861
    }, u"GraphRenderer::switchToComponentMode"_s);
×
862
}
×
863

864
void GraphRenderer::onGraphWillChange(const Graph* graph)
865
{
×
866
    pauseRendererThreadExecution();
×
867

868
    // Hide any graph elements that are merged; they aren't displayed normally,
869
    // but during scene transitions they may become unmerged, and we don't want
870
    // to show them until the scene transition is over
871
    for(const NodeId nodeId : graph->nodeIds())
×
872
    {
×
873
        if(graph->typeOf(nodeId) == MultiElementType::Tail)
×
874
            _hiddenNodes.set(nodeId, true);
×
875
    }
×
876

877
    for(const EdgeId edgeId : graph->edgeIds())
×
878
    {
×
879
        if(graph->typeOf(edgeId) == MultiElementType::Tail)
×
880
            _hiddenEdges.set(edgeId, true);
×
881
    }
×
882
}
×
883

884
void GraphRenderer::onGraphChanged(const Graph* graph, bool changed)
885
{
×
886
    if(!changed)
×
887
        return;
×
888

889
    _numComponents = graph->numComponents();
×
890

891
    // We may not, in fact, subsequently actually start a transition here, but we
892
    // speculatively pretend we do so that if a command is currently in progress
893
    // there is some overlap between it and the renderer transition. This ensures
894
    // that Document::busy() returns true for the duration of the transaction.
895
    if(visible())
×
896
        rendererStartedTransition();
×
897

898
    executeOnRendererThread([this]
×
899
    {
×
900
        for(const ComponentId componentId : _graphModel->graph().componentIds())
×
901
        {
×
902
            componentRendererForId(componentId)->initialise(_graphModel, componentId,
×
903
                                                            _selectionManager, this);
×
904
        }
×
905
        updateGPUData(When::Later);
×
906
    }, u"GraphRenderer::onGraphChanged update"_s);
×
907
}
×
908

909
void GraphRenderer::onComponentAdded(const Graph*, ComponentId componentId, bool)
910
{
×
911
    Q_ASSERT(!componentId.isNull());
×
912

913
    // If the component is entirely new, we shouldn't be hiding any of it
914
    const auto* component = _graphModel->graph().componentById(componentId);
×
915
    for(const NodeId nodeId : component->nodeIds())
×
916
        _hiddenNodes.set(nodeId, false);
×
917
    for(const EdgeId edgeId : component->edgeIds())
×
918
        _hiddenEdges.set(edgeId, false);
×
919

920
    executeOnRendererThread([this, componentId]
×
921
    {
×
922
        componentRendererForId(componentId)->initialise(_graphModel, componentId,
×
923
                                                        _selectionManager, this);
×
924
    }, u"GraphRenderer::onComponentAdded"_s);
×
925
}
×
926

927
void GraphRenderer::onComponentWillBeRemoved(const Graph*, ComponentId componentId, bool)
928
{
×
929
    executeOnRendererThread([this, componentId]
×
930
    {
×
931
        componentRendererForId(componentId)->cleanup();
×
932
    }, u"GraphRenderer::onComponentWillBeRemoved (cleanup) component %1"_s.arg(static_cast<int>(componentId)));
×
933
}
×
934

935
void GraphRenderer::onPreferenceChanged(const QString& key, const QVariant&)
936
{
×
937
    if(key == u"visuals/backgroundColor"_s || key == u"visuals/enableAntialiasing"_s ||
×
NEW
938
        key == u"visuals/improveStaticImages"_s || key == u"visuals/ambientOcclusion"_s ||
×
NEW
939
        key.startsWith(u"debug/"_s))
×
NEW
940
    {
×
941
        update();
×
NEW
942
    }
×
943
}
×
944

945
void GraphRenderer::onCommandsStarted()
946
{
×
947
    disableSceneUpdate();
×
948
}
×
949

950
void GraphRenderer::onCommandsFinished()
951
{
×
952
    enableSceneUpdate();
×
953
    update();
×
954
}
×
955

956
void GraphRenderer::onLayoutInitialised()
957
{
×
958
    _layoutInitialised = true;
×
959
    _layoutInitialised.notify_one();
×
960
}
×
961

962
void GraphRenderer::onLayoutChanged()
963
{
×
964
    _layoutChanged = true;
×
965
}
×
966

967
void GraphRenderer::onComponentAlphaChanged(ComponentId)
968
{
×
969
    updateGPUData(When::Later);
×
970
}
×
971

972
void GraphRenderer::onComponentCleanup(ComponentId)
973
{
×
974
    updateGPUData(When::Later);
×
975
}
×
976

977
void GraphRenderer::onVisibilityChanged()
978
{
×
979
    updateGPUData(When::Later);
×
980
}
×
981

982
GLuint GraphRenderer::sdfTexture() const
983
{
×
984
    return _sdfTexture.front();
×
985
}
×
986

987
QSize GraphRenderer::sdfTextureSize() const
988
{
×
989
    return _sdfTextureSize;
×
990
}
×
991

992
void GraphRenderer::updateText()
993
{
×
994
    const std::unique_lock<std::recursive_mutex> lock(_glyphMap->mutex());
×
995

996
    for(auto nodeId : _graphModel->graph().nodeIds())
×
997
        _glyphMap->addText(_graphModel->nodeVisual(nodeId)._text);
×
998

999
    for(auto edgeId : _graphModel->graph().edgeIds())
×
1000
        _glyphMap->addText(_graphModel->edgeVisual(edgeId)._text);
×
1001

1002
    _graphModel->forEachTextVisual([this](const TextVisual& textVisual)
×
1003
    {
×
1004
        _glyphMap->addText(textVisual._text);
×
1005
    });
×
1006

1007
    if(_glyphMap->updateRequired())
×
1008
    {
×
1009
        _glyphMap->update();
×
1010

1011
        executeOnRendererThread([this]
×
1012
        {
×
1013
            _sdfTextureSize = renderSdfTexture(*_glyphMap, _sdfTexture.back());
×
1014
            _sdfTexture.swap();
×
1015
            _textLayoutResults = _glyphMap->results();
×
1016

1017
            updateGPUData(When::Later);
×
1018
            update(); // QQuickFramebufferObject::Renderer::update
×
1019
        }, u"GraphRenderer::updateText"_s);
×
1020
    }
×
1021
}
×
1022

1023
void GraphRenderer::resetView()
1024
{
×
1025
    if(_scene != nullptr)
×
1026
        _scene->resetView();
×
1027
}
×
1028

1029
bool GraphRenderer::viewIsReset() const
1030
{
×
1031
    if(_scene != nullptr)
×
1032
        return _scene->viewIsReset();
×
1033

1034
    return true;
×
1035
}
×
1036

1037
void GraphRenderer::processEventQueue()
1038
{
×
1039
    while(!_eventQueue.empty())
×
1040
    {
×
1041
        auto e = std::move(_eventQueue.front());
×
1042
        _eventQueue.pop();
×
1043

1044
        // You might expect mouse button events to be delivered as QMouseEvents,
1045
        // and for the most part they are, except when a touchscreen device is
1046
        // used to generate them, specifically a touchscreen laptop. Under this
1047
        // regime, we seem to only get QSinglePointEvents. This is a base for
1048
        // QMouseEvent, so we get the same information we need for both cases.
1049
        auto* singlePointEvent = dynamic_cast<QSinglePointEvent*>(e.get());
×
1050
        auto* wheelEvent = dynamic_cast<QWheelEvent*>(e.get());
×
1051
        auto* nativeEvent = dynamic_cast<QNativeGestureEvent*>(e.get());
×
1052

1053
        switch(e->type())
×
1054
        {
×
1055
        case QEvent::Type::MouseButtonPress:
×
1056
            Q_ASSERT(singlePointEvent != nullptr);
×
1057
            _interactor->mousePressEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1058
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1059

1060
            break;
×
1061

1062
        case QEvent::Type::MouseButtonRelease:
×
1063
            Q_ASSERT(singlePointEvent != nullptr);
×
1064
            _interactor->mouseReleaseEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1065
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1066

1067
            break;
×
1068

1069
        case QEvent::Type::MouseMove:
×
1070
            Q_ASSERT(singlePointEvent != nullptr);
×
1071
            _interactor->mouseMoveEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1072
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1073

1074
            break;
×
1075

1076
        case QEvent::Type::MouseButtonDblClick:
×
1077
            Q_ASSERT(singlePointEvent != nullptr);
×
1078
            _interactor->mouseDoubleClickEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1079
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1080

1081
            break;
×
1082

1083
        case QEvent::Type::Wheel:
×
1084
            Q_ASSERT(wheelEvent != nullptr);
×
1085
            switch(wheelEvent->deviceType())
×
1086
            {
×
1087
            case QInputDevice::DeviceType::Mouse:
×
1088
                _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1089
                    wheelEvent->angleDelta().y());
×
1090
                break;
×
1091

1092
            case QInputDevice::DeviceType::TouchScreen:
×
1093
            case QInputDevice::DeviceType::TouchPad:
×
1094
            {
×
1095
                if(u::pref(u"misc/panGestureZooms"_s).toBool())
×
1096
                {
×
1097
                    _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1098
                        wheelEvent->angleDelta().y());
×
1099
                }
×
1100
                else
×
1101
                {
×
1102
                    _interactor->panGestureEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1103
                        -wheelEvent->pixelDelta() * _devicePixelRatio);
×
1104
                }
×
1105

1106
                break;
×
1107
            }
×
1108

1109
            default: break;
×
1110
            }
×
1111

1112
            break;
×
1113

1114
        case QEvent::Type::NativeGesture:
×
1115
            Q_ASSERT(nativeEvent != nullptr);
×
1116
            if(nativeEvent->gestureType() == Qt::ZoomNativeGesture)
×
1117
            {
×
1118
                _interactor->zoomGestureEvent(
×
1119
                    nativeEvent->position().toPoint() * _devicePixelRatio,
×
1120
                    static_cast<float>(nativeEvent->value()));
×
1121
            }
×
1122

1123
            break;
×
1124

1125
        default: break;
×
1126
        }
×
1127
    }
×
1128
}
×
1129

1130
void GraphRenderer::updateScene()
1131
{
×
1132
    ifSceneUpdateEnabled([this]
×
1133
    {
×
1134
        _preUpdateExecutor.execute();
×
1135
    });
×
1136

1137
    if(_scene == nullptr)
×
1138
        return;
×
1139

1140
    if(_resized)
×
1141
    {
×
1142
        _scene->setViewportSize(width(), height());
×
1143
        _resized = false;
×
1144
    }
×
1145

1146
    ifSceneUpdateEnabled([this]
×
1147
    {
×
1148
        processEventQueue();
×
1149

1150
        // _synchronousLayoutChanged can only ever be (atomically) true in this scope
1151
        _synchronousLayoutChanged = _layoutChanged.exchange(false);
×
1152

1153
        // If there is a transition active then we'll need another
1154
        // frame once we're finished with this one
1155
        if(transitionActive())
×
1156
            update(); // QQuickFramebufferObject::Renderer::update
×
1157

1158
        const float dTime = secondsElapsed();
×
1159
        _transition.update(dTime);
×
1160
        _scene->update(dTime);
×
1161

1162
        if(layoutChanged())
×
1163
            updateGPUData(When::Later, GPUDataUpdate::NodePositions);
×
1164

1165
        updateGPUDataIfRequired();
×
1166
        updateComponentGPUData();
×
1167

1168
        _synchronousLayoutChanged = false;
×
1169
    });
×
1170

1171
    if(!_FBOcomplete)
×
1172
    {
×
1173
        qWarning() << "Attempting to render without a complete FBO";
×
1174
        return;
×
1175
    }
×
1176
}
×
1177

1178
GraphRenderer::Mode GraphRenderer::bestFocusParameters(GraphDisplay* graphDisplay,
1179
    ComponentIdSet& componentIds, NodeId& focusNodeId, float& radius) const
1180
{
×
1181
    radius = 0.0f;
×
1182
    focusNodeId = {};
×
1183

1184
    auto nodeIds = graphDisplay->desiredFocusNodeIds();
×
1185

1186
    // Tail nodes aren't visible, so they can't be focused
1187
    std::erase_if(nodeIds, [this](auto nodeId)
×
1188
    {
×
1189
        return _graphModel->graph().typeOf(nodeId) == MultiElementType::Tail;
×
1190
    });
×
1191

1192
    if(nodeIds.empty())
×
1193
        return mode();
×
1194

1195
    if(nodeIds.size() == 1)
×
1196
    {
×
1197
        radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
×
1198
        focusNodeId = nodeIds.front();
×
1199
        return Mode::Component;
×
1200
    }
×
1201

1202
    for(auto nodeId : nodeIds)
×
1203
        componentIds.insert(_graphModel->graph().componentIdOfNode(nodeId));
×
1204

1205
    if(componentIds.size() > 1)
×
1206
    {
×
1207
        // We want to focus on multiple nodes, but they span multiple components
1208
        if(mode() == Mode::Component && u::pref(u"misc/stayInComponentMode"_s).toBool())
×
1209
        {
×
1210
            // Prune the nodeIds we consider for focus down to only those in the focused component
1211
            auto focusedComponentId = _graphComponentScene->componentId();
×
1212

1213
            std::erase_if(nodeIds, [this, focusedComponentId](auto nodeId)
×
1214
            {
×
1215
                return _graphModel->graph().componentIdOfNode(nodeId) != focusedComponentId;
×
1216
            });
×
1217
        }
×
1218
        else
×
1219
            return Mode::Overview;
×
1220
    }
×
1221

1222
    // None of the nodes are in the currently focused component
1223
    if(nodeIds.empty())
×
1224
        return Mode::Overview;
×
1225

1226
    // If the request is for more than 1 node, then find their barycentre and
1227
    // pick the closest node to where ever this happens to be
1228
    std::vector<QVector3D> points;
×
1229
    points.reserve(nodeIds.size());
×
1230
    for(auto nodeId : nodeIds)
×
1231
    {
×
1232
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1233
        points.push_back(nodePosition);
×
1234
    }
×
1235

1236
    const BoundingSphere boundingSphere(points);
×
1237
    const QVector3D centre = boundingSphere.centre();
×
1238
    float minDistance = std::numeric_limits<float>::max();
×
1239
    NodeId closestToCentreNodeId;
×
1240
    for(auto nodeId : nodeIds)
×
1241
    {
×
1242
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1243
        const float distance = (centre - nodePosition).length();
×
1244

1245
        if(distance < minDistance)
×
1246
        {
×
1247
            minDistance = distance;
×
1248
            closestToCentreNodeId = nodeId;
×
1249
        }
×
1250
    }
×
1251

1252
    radius = GraphComponentRenderer::maxNodeDistanceFromPoint(*_graphModel,
×
1253
        _graphModel->nodePositions().get(closestToCentreNodeId), nodeIds);
×
1254
    focusNodeId = closestToCentreNodeId;
×
1255

1256
    return mode();
×
1257
}
×
1258

1259
QOpenGLFramebufferObject* GraphRenderer::createFramebufferObject(const QSize& size)
1260
{
×
1261
    // Piggy back our FBO resize on to Qt's
1262
    _FBOcomplete = resize(size.width(), size.height());
×
1263
    _resized = true;
×
1264

1265
    return new QOpenGLFramebufferObject(size);
×
1266
}
×
1267

1268
void GraphRenderer::render()
1269
{
×
1270
    if(!_FBOcomplete)
×
1271
    {
×
1272
        qWarning() << "Attempting to render incomplete FBO";
×
1273
        return;
×
1274
    }
×
1275

1276
    // Read each frame, so that changing them takes effect at once
1277
    const bool antialiasing = u::pref(u"visuals/enableAntialiasing"_s).toBool();
×
1278
    setAntialiasing(antialiasing);
×
1279
    // The selection rectangle is drawn into each frame, so nothing is gathered under it
1280
    setGatherWhenStill(antialiasing && u::pref(u"visuals/improveStaticImages"_s).toBool() && _selectionRect.isNull());
×
1281
    setAmbientOcclusionMode(normaliseQmlEnum<AmbientOcclusionMode>(u::pref(u"visuals/ambientOcclusion"_s).toInt()));
×
NEW
1282
    setDetailLevels({
×
NEW
1283
        ._tracedNodes = u::pref(u"debug/tracedNodes"_s).toBool(),
×
NEW
1284
        ._splattedNodes = u::pref(u"debug/splattedNodes"_s).toBool(),
×
NEW
1285
        ._tracedEdges = u::pref(u"debug/tracedEdges"_s).toBool(),
×
NEW
1286
        ._approximateTracedEdges = u::pref(u"debug/approximateTracedEdges"_s).toBool(),
×
NEW
1287
        ._splattedEdges = u::pref(u"debug/splattedEdges"_s).toBool(),
×
NEW
1288
        ._fastSplattedEdges = u::pref(u"debug/fastSplattedEdges"_s).toBool(),
×
NEW
1289
    });
×
1290

1291
    updateScene();
×
1292

1293
    QQuickOpenGLUtils::resetOpenGLState();
×
1294
    glViewport(0, 0, width(), height());
×
1295

1296
    auto renderFrame = [this]
×
1297
    {
×
1298
        renderGraph();
×
1299
        render2D(_selectionRect);
×
1300
        compositeInto(framebufferObject()->handle());
×
1301
    };
×
1302

1303
    if(nextFrameIsSample())
×
1304
    {
×
1305
        // Gather several frames at once
1306
        // cppcheck-suppress knownConditionTrueFalse
1307
        for(int i = 0; i < 4 && nextFrameIsSample(); i++)
×
1308
            renderFrame();
×
1309
    }
×
1310
    else
×
1311
        renderFrame();
×
1312

1313
    // Nothing asks for a frame once the image is static, so force an update if necessary
1314
    if(gathering() || handingOver())
×
1315
        update(); // QQuickFramebufferObject::Renderer::update
×
1316

1317
    QQuickOpenGLUtils::resetOpenGLState();
×
1318

1319
    _performanceCounter.tick();
×
1320
}
×
1321

1322
void GraphRenderer::synchronize(QQuickFramebufferObject* item)
1323
{
×
1324
    _devicePixelRatio = item->window()->devicePixelRatio();
×
1325
    setOutlineScale(static_cast<float>(_devicePixelRatio));
×
1326

1327
    auto* graphDisplay = qobject_cast<GraphDisplay*>(item);
×
1328

1329
    if(graphDisplay->viewResetPending())
×
1330
        resetView();
×
1331

1332
    if(graphDisplay->overviewModeSwitchPending())
×
1333
        switchToOverviewMode();
×
1334

1335
    setProjection(graphDisplay->projection());
×
1336
    setShading(graphDisplay->projection() == Projection::TwoDee ?
×
1337
        graphDisplay->shading2D() : graphDisplay->shading3D());
×
1338

1339
    ComponentIdSet componentIds;
×
1340
    NodeId focusNodeId;
×
1341
    float radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
×
1342
    auto targetMode = bestFocusParameters(graphDisplay, componentIds, focusNodeId, radius);
×
1343
    const ComponentId focusComponentId = graphDisplay->desiredFocusComponentId();
×
1344

1345
    if(mode() == Mode::Component && targetMode == Mode::Overview)
×
1346
        switchToOverviewMode("doTransition"_yes, u::vectorFrom(componentIds));
×
1347
    else if(!focusNodeId.isNull())
×
1348
        moveFocusToNode(focusNodeId, radius);
×
1349
    else if(!focusComponentId.isNull())
×
1350
    {
×
1351
        if(mode() == Mode::Overview)
×
1352
            switchToComponentMode("doTransition"_yes, focusComponentId);
×
1353
        else
×
1354
            moveFocusToComponent(focusComponentId);
×
1355
    }
×
1356
    else if(mode() == Mode::Overview && !componentIds.empty())
×
1357
        moveFocusToComponents(u::vectorFrom(componentIds));
×
1358

1359
    ifSceneUpdateEnabled([this, &graphDisplay]
×
1360
    {
×
1361
        auto& newEvents = graphDisplay->events();
×
1362
        while(!newEvents.empty())
×
1363
        {
×
1364
            _eventQueue.push(std::move(newEvents.front()));
×
1365
            newEvents.pop();
×
1366
        }
×
1367
    });
×
1368

1369
    // Tell the QuickItem what we're doing
1370
    graphDisplay->setViewIsReset(viewIsReset());
×
1371
    graphDisplay->setCanEnterOverviewMode(mode() != Mode::Overview && _numComponents > 1);
×
1372
    graphDisplay->setInOverviewMode(mode() == Mode::Overview);
×
1373

1374
    const ComponentId focusedComponentId = mode() != Mode::Overview ? _graphComponentScene->componentId() : ComponentId();
×
1375
    graphDisplay->setFocusedComponentId(focusedComponentId);
×
1376

1377
    emit synchronizeComplete();
×
1378
}
×
1379

1380
GraphComponentRenderer* GraphRenderer::componentRendererForId(ComponentId componentId) const
1381
{
×
1382
    if(componentId.isNull())
×
1383
        return nullptr;
×
1384

1385
    GraphComponentRenderer* renderer = _componentRenderers.at(componentId);
×
1386
    Q_ASSERT(renderer != nullptr);
×
1387
    return renderer;
×
1388
}
×
1389

1390
void GraphRenderer::enableSceneUpdate()
1391
{
×
1392
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1393
    Q_ASSERT(_sceneUpdateDisabled > 0);
×
1394
    _sceneUpdateDisabled--;
×
1395
    resetTime();
×
1396
}
×
1397

1398
void GraphRenderer::disableSceneUpdate()
1399
{
×
1400
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1401
    _sceneUpdateDisabled++;
×
1402
}
×
1403

1404
void GraphRenderer::ifSceneUpdateEnabled(const std::function<void()>& f) const
1405
{
×
1406
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1407
    if(_sceneUpdateDisabled == 0)
×
1408
        f();
×
1409
}
×
1410

1411
void GraphRenderer::clearHiddenElements()
1412
{
×
1413
    _hiddenNodes.resetElements();
×
1414
    _hiddenEdges.resetElements();
×
1415
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc