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

graphia-app / graphia / 41725894897

03 Nov 2026 09:48PM UTC coverage: 71.364% (-0.03%) from 71.391%
41725894897

push

github

timangus
CLAUDE: Vendor QCustomPlot's split sources with the update script

11762 of 18036 branches covered (65.21%)

Branch coverage included in aggregate %.

29960 of 40428 relevant lines covered (74.11%)

695585.54 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 <limits>
64
#include <utility>
65

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

205
    _FBOcomplete = false;
×
206
}
×
207

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

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

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

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

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

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

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

242
        glyphData._component = componentIndex;
×
243

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

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

254
        glyphData._basePosition[0] = elementPosition.x();
×
255
        glyphData._basePosition[1] = elementPosition.y();
×
256
        glyphData._basePosition[2] = elementPosition.z();
×
257

258
        glyphData._color[0] = textColor.redF();
×
259
        glyphData._color[1] = textColor.greenF();
×
260
        glyphData._color[2] = textColor.blueF();
×
261

262
        gpuGraphData->_glyphData.push_back(glyphData);
×
263
    }
×
264
}
×
265

266
void GraphRenderer::updateGPUDataIfRequired()
267
{
×
268
    if(!_gpuDataRequiresUpdate)
×
269
        return;
×
270

271
    _gpuDataRequiresUpdate = false;
×
272

273
    const std::unique_lock<std::recursive_mutex> glyphMapLock(_glyphMap->mutex());
×
274

275
    int componentIndex = 0;
×
276

277
    resetGPUGraphData();
×
278

279
    // Lock the positions for as short a time as possible
280
    NodeArray<QVector3D> scaledAndSmoothedNodePositions(_graphModel->graph());
×
281
    {
×
282
        auto& nodePositions = _graphModel->nodePositions();
×
283
        const std::unique_lock<NodePositions> nodePositionsLock(nodePositions);
×
284

285
        for(auto nodeId : _graphModel->graph().nodeIds())
×
286
            scaledAndSmoothedNodePositions[nodeId] = nodePositions.get(nodeId);
×
287
    }
×
288

289
    const float textScale = u::pref(u"visuals/textSize"_s).toFloat();
×
290
    auto textAlignment = normaliseQmlEnum<TextAlignment>(u::pref(u"visuals/textAlignment"_s).toInt());
×
291
    auto showNodeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showNodeText"_s).toInt());
×
292
    auto showEdgeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showEdgeText"_s).toInt());
×
293
    auto edgeVisualType = normaliseQmlEnum<EdgeVisualType>(u::pref(u"visuals/edgeVisualType"_s).toInt());
×
294

295
    // Ignore the setting if the graph is undirected
296
    if(!_graphModel->directed())
×
297
        edgeVisualType = EdgeVisualType::Cylinder;
×
298

299
    for(const auto& componentRendererRef : _componentRenderers)
×
300
    {
×
301
        GraphComponentRenderer* componentRenderer = componentRendererRef;
×
302
        if(!componentRenderer->visible())
×
303
            continue;
×
304

305
        const float UnhighlightedAlpha = 0.22f;
×
306

307
        for(auto nodeId : componentRenderer->nodeIds())
×
308
        {
×
309
            if(_hiddenNodes.get(nodeId))
×
310
                continue;
×
311

312
            const QVector3D nodePosition = scaledAndSmoothedNodePositions[nodeId];
×
313

314
            const auto& nodeVisual = _graphModel->nodeVisual(nodeId);
×
315

316
            // Create and add NodeData
317
            GPUGraphData::NodeData nodeData;
×
318
            nodeData._position[0] = nodePosition.x();
×
319
            nodeData._position[1] = nodePosition.y();
×
320
            nodeData._position[2] = nodePosition.z();
×
321
            nodeData._component = componentIndex;
×
322
            nodeData._size = nodeVisual._size;
×
323
            nodeData._outerColor[0] = nodeVisual._outerColor.redF();
×
324
            nodeData._outerColor[1] = nodeVisual._outerColor.greenF();
×
325
            nodeData._outerColor[2] = nodeVisual._outerColor.blueF();
×
326
            nodeData._innerColor[0] = nodeVisual._innerColor.redF();
×
327
            nodeData._innerColor[1] = nodeVisual._innerColor.greenF();
×
328
            nodeData._innerColor[2] = nodeVisual._innerColor.blueF();
×
329
            nodeData._selected = nodeVisual._state.test(VisualFlags::Selected) ? 1.0f : 0.0f;
×
330

331
            auto* gpuGraphData = gpuGraphDataForAlpha(componentRenderer->alpha(),
×
332
                nodeVisual._state.test(VisualFlags::Unhighlighted) ? UnhighlightedAlpha : 1.0f);
×
333

334
            if(gpuGraphData != nullptr)
×
335
            {
×
336
                gpuGraphData->_nodeData.push_back(nodeData);
×
337

338
                if(nodeData._selected != 0.0f)
×
339
                    gpuGraphData->_elementsSelected = true;
×
340

341
                if(nodeVisual._text.isEmpty())
×
342
                    continue;
×
343

344
                if(showNodeText == TextState::Off || nodeVisual._state.test(VisualFlags::Unhighlighted))
×
345
                    continue;
×
346

347
                if(showNodeText == TextState::Selected && !nodeVisual._state.test(VisualFlags::Selected))
×
348
                    continue;
×
349

350
                if(showNodeText == TextState::Focused && componentRenderer->focusNodeId() != nodeId)
×
351
                    continue;
×
352

353
                createGPUGlyphData(nodeVisual._text,
×
354
                    nodeVisual._textColor, textAlignment,
×
355
                    textScale * nodeVisual._textSize,
×
356
                    nodeVisual._size, nodePosition, componentIndex,
×
357
                    gpuGraphDataForOverlay(componentRenderer->alpha()));
×
358
            }
×
359
        }
×
360

361
        for(auto& edge : componentRenderer->edges())
×
362
        {
×
363
            if(_hiddenEdges.get(edge->id()) || _hiddenNodes.get(edge->sourceId()) || _hiddenNodes.get(edge->targetId()))
×
364
                continue;
×
365

366
            const QVector3D& sourcePosition = scaledAndSmoothedNodePositions[edge->sourceId()];
×
367
            const QVector3D& targetPosition = scaledAndSmoothedNodePositions[edge->targetId()];
×
368

369
            const auto& edgeVisual = _graphModel->edgeVisual(edge->id());
×
370
            const auto& sourceNodeVisual = _graphModel->nodeVisual(edge->sourceId());
×
371
            const auto& targetNodeVisual = _graphModel->nodeVisual(edge->targetId());
×
372

373
            auto nodeRadiusSumSq = sourceNodeVisual._size + targetNodeVisual._size;
×
374
            nodeRadiusSumSq *= nodeRadiusSumSq;
×
375
            const auto edgeLengthSq = (targetPosition - sourcePosition).lengthSquared();
×
376

377
            if(edgeLengthSq < nodeRadiusSumSq)
×
378
            {
×
379
                // The edge's nodes are intersecting. Their overlap defines a lens of a
380
                // certain radius. If this is greater than the edge radius, the edge is
381
                // entirely enclosed within the nodes and we can safely skip rendering
382
                // it altogether since it is entirely occluded.
383

384
                const auto sourceRadiusSq = sourceNodeVisual._size * sourceNodeVisual._size;
×
385
                const auto targetRadiusSq = targetNodeVisual._size * targetNodeVisual._size;
×
386

387
                const auto n = edgeLengthSq - sourceRadiusSq + targetRadiusSq;
×
388
                const auto d = 4.0f * edgeLengthSq;
×
389
                const auto intersectionLensRadiusSq = targetRadiusSq - ((n * n) / d);
×
390

391
                const auto edgeRadiusSq = edgeVisual._size * edgeVisual._size;
×
392

393
                if(edgeRadiusSq < intersectionLensRadiusSq)
×
394
                    continue;
×
395
            }
×
396

397
            GPUGraphData::EdgeData edgeData;
×
398
            edgeData._sourcePosition[0] = sourcePosition.x();
×
399
            edgeData._sourcePosition[1] = sourcePosition.y();
×
400
            edgeData._sourcePosition[2] = sourcePosition.z();
×
401
            edgeData._targetPosition[0] = targetPosition.x();
×
402
            edgeData._targetPosition[1] = targetPosition.y();
×
403
            edgeData._targetPosition[2] = targetPosition.z();
×
404
            edgeData._sourceSize = _graphModel->nodeVisual(edge->sourceId())._size;
×
405
            edgeData._targetSize = _graphModel->nodeVisual(edge->targetId())._size;
×
406
            edgeData._edgeType = static_cast<int>(edgeVisualType);
×
407
            edgeData._component = componentIndex;
×
408
            edgeData._size = edgeVisual._size;
×
409
            edgeData._outerColor[0] = edgeVisual._outerColor.redF();
×
410
            edgeData._outerColor[1] = edgeVisual._outerColor.greenF();
×
411
            edgeData._outerColor[2] = edgeVisual._outerColor.blueF();
×
412
            edgeData._innerColor[0] = edgeVisual._innerColor.redF();
×
413
            edgeData._innerColor[1] = edgeVisual._innerColor.greenF();
×
414
            edgeData._innerColor[2] = edgeVisual._innerColor.blueF();
×
415
            edgeData._selected = 0.0f;
×
416

417
            auto* gpuGraphData = gpuGraphDataForAlpha(componentRenderer->alpha(),
×
418
                edgeVisual._state.test(VisualFlags::Unhighlighted) ? UnhighlightedAlpha : 1.0f);
×
419

420
            if(gpuGraphData != nullptr)
×
421
            {
×
422
                gpuGraphData->_edgeData.push_back(edgeData);
×
423

424
                if(edgeData._selected != 0.0f)
×
425
                    gpuGraphData->_elementsSelected = true;
×
426

427
                if(edgeVisual._text.isEmpty())
×
428
                    continue;
×
429

430
                if(showEdgeText == TextState::Off || edgeVisual._state.test(VisualFlags::Unhighlighted))
×
431
                    continue;
×
432

433
                if(showEdgeText == TextState::Selected && !edgeVisual._state.test(VisualFlags::Selected))
×
434
                    continue;
×
435

436
                const QVector3D midPoint = (sourcePosition + targetPosition) * 0.5f;
×
437
                createGPUGlyphData(edgeVisual._text,
×
438
                    edgeVisual._textColor, textAlignment,
×
439
                    textScale * edgeVisual._textSize,
×
440
                    edgeVisual._size, midPoint, componentIndex,
×
441
                    gpuGraphDataForOverlay(componentRenderer->alpha()));
×
442
            }
×
443
        }
×
444

445
        _graphModel->forEachTextVisual(componentRenderer->componentId(),
×
446
        [&](const TextVisual& textVisual)
×
447
        {
×
448
            createGPUGlyphData(textVisual._text,
×
449
                textVisual._color, textAlignment,
×
450
                textScale * textVisual._size,
×
451
                textVisual._radius, textVisual._centre, componentIndex,
×
452
                gpuGraphDataForOverlay(componentRenderer->alpha()));
×
453
        });
×
454

455
        componentIndex++;
×
456
    }
×
457

458
    uploadGPUGraphData();
×
459
}
×
460

461
void GraphRenderer::updateGPUData(GraphRenderer::When when)
462
{
×
463
    _gpuDataRequiresUpdate = true;
×
464

465
    if(when == When::Now)
×
466
        updateGPUDataIfRequired();
×
467
}
×
468

469
void GraphRenderer::onPreviewRequested(int width, int height, bool fillSize)
470
{
×
471
    makeContextCurrent();
×
472
    _screenshotRenderer->requestPreview(*this, width, height, fillSize);
×
473
}
×
474

475
void GraphRenderer::onScreenshotRequested(int width, int height, const QString& path, int dpi, bool fillSize)
476
{
×
477
    makeContextCurrent();
×
478
    _screenshotRenderer->requestScreenshot(*this, width, height, path, dpi, fillSize);
×
479
}
×
480

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

490
    for(const auto& componentRendererRef : _componentRenderers)
×
491
    {
×
492
        GraphComponentRenderer* componentRenderer = componentRendererRef;
×
493
        if(componentRenderer == nullptr)
×
494
        {
×
495
            qWarning() << "null component renderer";
×
496
            continue;
×
497
        }
×
498

499
        if(!componentRenderer->visible())
×
500
            continue;
×
501

502
        appendGPUComponentData(componentRenderer->modelViewMatrix(),
×
503
            componentRenderer->projectionMatrix(),
×
504
            componentRenderer->camera()->distance(),
×
505
            componentRenderer->lightScale());
×
506
    }
×
507

508
    uploadGPUComponentData();
×
509
}
×
510

511
void GraphRenderer::setScene(Scene* scene)
512
{
×
513
    if(_scene != nullptr)
×
514
    {
×
515
        _scene->setVisible(false);
×
516
        _scene->onHide();
×
517
    }
×
518

519
    _scene = scene;
×
520

521
    _scene->setViewportSize(width(), height());
×
522

523
    _scene->setProjection(_projection);
×
524
    _scene->setVisible(true);
×
525
    _scene->onShow();
×
526
}
×
527

528
GraphRenderer::Mode GraphRenderer::mode() const
529
{
×
530
    return _mode;
×
531
}
×
532

533
void GraphRenderer::setMode(Mode mode)
534
{
×
535
    if(mode != _mode)
×
536
    {
×
537
        _mode = mode;
×
538
        emit modeChanged();
×
539
    }
×
540
}
×
541

542
Projection GraphRenderer::projection() const
543
{
×
544
    return _projection;
×
545
}
×
546

547
void GraphRenderer::setProjection(Projection projection)
548
{
×
549
    if(projection != _projection)
×
550
    {
×
551
        _projection = projection;
×
552

553
        if(_scene != nullptr)
×
554
            _scene->setProjection(projection);
×
555
    }
×
556
}
×
557

558
void GraphRenderer::resetTime()
559
{
×
560
    _time.start();
×
561
    _lastTime = 0.0f;
×
562
}
×
563

564
float GraphRenderer::secondsElapsed()
565
{
×
566
    const float time = static_cast<float>(_time.elapsed()) / 1000.0f;
×
567
    const float dTime = time - _lastTime;
×
568
    _lastTime = time;
×
569

570
    return dTime;
×
571
}
×
572

573
bool GraphRenderer::transitionActive() const
574
{
×
575
    return _transition.active() || _scene->transitionActive();
×
576
}
×
577

578
void GraphRenderer::moveFocusToNode(NodeId nodeId, float radius)
579
{
×
580
    if(mode() == Mode::Component)
×
581
    {
×
582
        if(!_graphComponentScene->focusedOnNodeAtRadius(nodeId, radius))
×
583
            rendererStartedTransition();
×
584

585
        executeOnRendererThread([this, nodeId, radius]
×
586
        {
×
587
            _graphComponentScene->moveFocusToNode(nodeId, radius);
×
588
        }, u"GraphRenderer::moveFocusToNode"_s);
×
589
    }
×
590
    else if(mode() == Mode::Overview)
×
591
    {
×
592
        // To focus on a node, we need to be in component mode
593
        auto componentId = _graphModel->graph().componentIdOfNode(nodeId);
×
594
        switchToComponentMode("doTransition"_yes, componentId, nodeId, radius);
×
595
    }
×
596
}
×
597

598
void GraphRenderer::moveFocusToComponent(ComponentId componentId)
599
{
×
600
    if(mode() == Mode::Component)
×
601
    {
×
602
        if(componentId != _graphComponentScene->componentId())
×
603
            rendererStartedTransition();
×
604

605
        _graphComponentScene->setComponentId(componentId, "doTransition"_yes);
×
606
    }
×
607
}
×
608

609
void GraphRenderer::moveFocusToComponents(const std::vector<ComponentId>& componentIds)
610
{
×
611
    if(mode() == Mode::Overview)
×
612
        _graphOverviewScene->zoomTo(componentIds);
×
613
}
×
614

615
void GraphRenderer::rendererStartedTransition()
616
{
×
617
    if(!_transitionPotentiallyInProgress)
×
618
    {
×
619
        _transitionPotentiallyInProgress = true;
×
620

621
        emit transitionStarted();
×
622
        resetTime();
×
623
    }
×
624
}
×
625

626
void GraphRenderer::rendererFinishedTransition()
627
{
×
628
    if(transitionActive())
×
629
        return;
×
630

631
    // The transition may have been initiated by changes that
632
    // require the GPU data to be updated, so ensure this is done
633
    updateGPUData(When::Later);
×
634

635
    _transitionPotentiallyInProgress = false;
×
636
    emit transitionFinished();
×
637
}
×
638

639
void GraphRenderer::sceneFinishedTransition()
640
{
×
641
    clearHiddenElements();
×
642
    updateGPUData(When::Later);
×
643
}
×
644

645
void GraphRenderer::executeOnRendererThread(DeferredExecutor::TaskFn task, const QString& description)
646
{
×
647
    _preUpdateExecutor.enqueue(std::move(task), description);
×
648
    emit taskAddedToExecutor();
×
649
}
×
650

651
// Stop the renderer thread executing any tasks until...
652
void GraphRenderer::pauseRendererThreadExecution()
653
{
×
654
    _preUpdateExecutor.pause();
×
655
}
×
656

657
// ...this is called
658
void GraphRenderer::resumeRendererThreadExecution()
659
{
×
660
    _preUpdateExecutor.resume();
×
661
}
×
662

663
bool GraphRenderer::visible() const
664
{
×
665
    return _graphOverviewScene->visible() || _graphComponentScene->visible();
×
666
}
×
667

668
void GraphRenderer::onNodeAdded(const Graph*, NodeId nodeId)
669
{
×
670
    _hiddenNodes.set(nodeId, true);
×
671
}
×
672

673
void GraphRenderer::onEdgeAdded(const Graph*, EdgeId edgeId)
674
{
×
675
    _hiddenEdges.set(edgeId, true);
×
676
}
×
677

678
void GraphRenderer::onNodeAddedToComponent(const Graph*, NodeId nodeId, ComponentId)
679
{
×
680
    _hiddenNodes.set(nodeId, true);
×
681
}
×
682

683
void GraphRenderer::onEdgeAddedToComponent(const Graph*, EdgeId edgeId, ComponentId)
684
{
×
685
    _hiddenEdges.set(edgeId, true);
×
686
}
×
687

688
void GraphRenderer::onNodeMovedBetweenComponents(const Graph*, NodeId nodeId, ComponentId, ComponentId)
689
{
×
690
    _hiddenNodes.set(nodeId, true);
×
691
}
×
692

693
void GraphRenderer::onEdgeMovedBetweenComponents(const Graph*, EdgeId edgeId, ComponentId, ComponentId)
694
{
×
695
    _hiddenEdges.set(edgeId, true);
×
696
}
×
697

698
void GraphRenderer::finishTransitionToOverviewMode(NamedBool<"doTransition"> doTransition,
699
    const std::vector<ComponentId>& focusComponentIds)
700
{
×
701
    // If component mode has a queued transition nodeId, cancel the switch to overview
702
    if(_graphComponentScene->performQueuedTransition())
×
703
        return;
×
704

705
    setMode(GraphRenderer::Mode::Overview);
×
706
    setScene(_graphOverviewScene);
×
707
    setInteractor(_graphOverviewInteractor);
×
708

709
    _graphOverviewScene->resetView("doTransition"_no);
×
710

711
    if(doTransition)
×
712
    {
×
713
        // When we first change to overview mode we want all
714
        // the renderers to be in their reset state
715
        for(auto componentId : _graphModel->graph().componentIds())
×
716
        {
×
717
            auto* renderer = componentRendererForId(componentId);
×
718
            renderer->resetView();
×
719
        }
×
720

721
        _graphOverviewScene->startTransitionFromComponentMode(
×
722
            _graphComponentScene->componentId(), focusComponentIds);
×
723
    }
×
724

725
    updateGPUData(When::Later);
×
726
}
×
727

728
void GraphRenderer::finishTransitionToOverviewModeOnRendererThread(NamedBool<"doTransition"> doTransition,
729
    const std::vector<ComponentId>& focusComponentIds)
730
{
×
731
    executeOnRendererThread([this, doTransition, focusComponentIds]
×
732
    {
×
733
        finishTransitionToOverviewMode(doTransition, focusComponentIds);
×
734
    }, u"GraphRenderer::finishTransitionToOverviewMode"_s);
×
735
}
×
736

737
void GraphRenderer::finishTransitionToComponentMode(NamedBool<"doTransition"> doTransition)
738
{
×
739
    setMode(GraphRenderer::Mode::Component);
×
740
    setScene(_graphComponentScene);
×
741
    setInteractor(_graphComponentInteractor);
×
742

743
    if(doTransition)
×
744
    {
×
745
        // Go back to where we were before
746
        _graphComponentScene->startTransition().then([this] { _graphComponentScene->performQueuedTransition(); });
×
747
        _graphComponentScene->restoreViewData();
×
748
    }
×
749

750
    updateGPUData(When::Later);
×
751
}
×
752

753
void GraphRenderer::finishTransitionToComponentModeOnRendererThread(NamedBool<"doTransition"> doTransition)
754
{
×
755
    executeOnRendererThread([this, doTransition]
×
756
    {
×
757
        finishTransitionToComponentMode(doTransition);
×
758
    }, u"GraphRenderer::finishTransitionToComponentMode"_s);
×
759
}
×
760

761
void GraphRenderer::switchToOverviewMode(NamedBool<"doTransition"> doTransition, const std::vector<ComponentId>& focusComponentIds)
762
{
×
763
    // Refuse to switch to overview mode if there is nothing to display
764
    if(_graphModel->graph().numComponents() <= 1)
×
765
        return;
×
766

767
    doTransition = doTransition && mode() != GraphRenderer::Mode::Overview &&
×
768
        _graphComponentScene->componentRenderer() != nullptr;
×
769

770
    if(doTransition)
×
771
        rendererStartedTransition();
×
772

773
    executeOnRendererThread([this, doTransition, focusComponentIds]
×
774
    {
×
775
        // So that we can return to the current view parameters later
776
        _graphComponentScene->saveViewData();
×
777

778
        if(doTransition)
×
779
        {
×
780
            _graphComponentScene->clearQueuedTransition();;
×
781

782
            auto doPostViewResetTransition = [this, focusComponentIds]
×
783
            {
×
784
                sceneFinishedTransition();
×
785
                _transition.willBeImmediatelyReused();
×
786
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
×
787
            };
×
788

789
            if(!_graphComponentScene->viewIsReset())
×
790
            {
×
791
                _graphComponentScene->startTransition().then(doPostViewResetTransition);
×
792
                _graphComponentScene->resetView("doTransition"_no);
×
793
            }
×
794
            else if(_graphComponentScene->transitionActive())
×
795
            {
×
796
                // The view reset transition is still in progress but our ultimate
797
                // target has (potentially) changed
798
                _transition.alternativeThen(doPostViewResetTransition);
×
799
            }
×
800
            else
×
801
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
×
802
        }
×
803
        else
×
804
            finishTransitionToOverviewMode("doTransition"_no, focusComponentIds);
×
805

806
    }, u"GraphRenderer::switchToOverviewMode"_s);
×
807
}
×
808

809
void GraphRenderer::switchToComponentMode(NamedBool<"doTransition"> doTransition, ComponentId componentId, NodeId nodeId, float radius)
810
{
×
811
    doTransition = doTransition && mode() != GraphRenderer::Mode::Component;
×
812

813
    if(doTransition)
×
814
        rendererStartedTransition();
×
815

816
    executeOnRendererThread([this, componentId, nodeId, radius, doTransition]
×
817
    {
×
818
        _graphComponentScene->setComponentId(componentId);
×
819

820
        if(doTransition)
×
821
        {
×
822
            _graphOverviewScene->startTransitionToComponentMode(_graphComponentScene->componentId()).then(
×
823
            [this, componentId, nodeId, radius]
×
824
            {
×
825
                if(!nodeId.isNull())
×
826
                {
×
827
                    Q_ASSERT(_graphModel->graph().componentIdOfNode(nodeId) == componentId);
×
828
                    componentRendererForId(componentId)->moveSavedFocusToNode(nodeId, radius);
×
829
                }
×
830

831
                if(!_graphComponentScene->savedViewIsReset())
×
832
                {
×
833
                    _transition.willBeImmediatelyReused();
×
834
                    finishTransitionToComponentModeOnRendererThread("doTransition"_yes);
×
835
                }
×
836
                else
×
837
                    finishTransitionToComponentModeOnRendererThread("doTransition"_no);
×
838
            });
×
839
        }
×
840
        else
×
841
            finishTransitionToComponentMode("doTransition"_no);
×
842

843
    }, u"GraphRenderer::switchToComponentMode"_s);
×
844
}
×
845

846
void GraphRenderer::onGraphWillChange(const Graph* graph)
847
{
×
848
    pauseRendererThreadExecution();
×
849

850
    // Hide any graph elements that are merged; they aren't displayed normally,
851
    // but during scene transitions they may become unmerged, and we don't want
852
    // to show them until the scene transition is over
853
    for(const NodeId nodeId : graph->nodeIds())
×
854
    {
×
855
        if(graph->typeOf(nodeId) == MultiElementType::Tail)
×
856
            _hiddenNodes.set(nodeId, true);
×
857
    }
×
858

859
    for(const EdgeId edgeId : graph->edgeIds())
×
860
    {
×
861
        if(graph->typeOf(edgeId) == MultiElementType::Tail)
×
862
            _hiddenEdges.set(edgeId, true);
×
863
    }
×
864
}
×
865

866
void GraphRenderer::onGraphChanged(const Graph* graph, bool changed)
867
{
×
868
    if(!changed)
×
869
        return;
×
870

871
    _numComponents = graph->numComponents();
×
872

873
    // We may not, in fact, subsequently actually start a transition here, but we
874
    // speculatively pretend we do so that if a command is currently in progress
875
    // there is some overlap between it and the renderer transition. This ensures
876
    // that Document::busy() returns true for the duration of the transaction.
877
    if(visible())
×
878
        rendererStartedTransition();
×
879

880
    executeOnRendererThread([this]
×
881
    {
×
882
        for(const ComponentId componentId : _graphModel->graph().componentIds())
×
883
        {
×
884
            componentRendererForId(componentId)->initialise(_graphModel, componentId,
×
885
                                                            _selectionManager, this);
×
886
        }
×
887
        updateGPUData(When::Later);
×
888
    }, u"GraphRenderer::onGraphChanged update"_s);
×
889
}
×
890

891
void GraphRenderer::onComponentAdded(const Graph*, ComponentId componentId, bool)
892
{
×
893
    Q_ASSERT(!componentId.isNull());
×
894

895
    // If the component is entirely new, we shouldn't be hiding any of it
896
    const auto* component = _graphModel->graph().componentById(componentId);
×
897
    for(const NodeId nodeId : component->nodeIds())
×
898
        _hiddenNodes.set(nodeId, false);
×
899
    for(const EdgeId edgeId : component->edgeIds())
×
900
        _hiddenEdges.set(edgeId, false);
×
901

902
    executeOnRendererThread([this, componentId]
×
903
    {
×
904
        componentRendererForId(componentId)->initialise(_graphModel, componentId,
×
905
                                                        _selectionManager, this);
×
906
    }, u"GraphRenderer::onComponentAdded"_s);
×
907
}
×
908

909
void GraphRenderer::onComponentWillBeRemoved(const Graph*, ComponentId componentId, bool)
910
{
×
911
    executeOnRendererThread([this, componentId]
×
912
    {
×
913
        componentRendererForId(componentId)->cleanup();
×
914
    }, u"GraphRenderer::onComponentWillBeRemoved (cleanup) component %1"_s.arg(static_cast<int>(componentId)));
×
915
}
×
916

917
void GraphRenderer::onPreferenceChanged(const QString& key, const QVariant&)
918
{
×
919
    if(key == u"visuals/backgroundColor"_s)
×
920
        update();
×
921
}
×
922

923
void GraphRenderer::onCommandsStarted()
924
{
×
925
    disableSceneUpdate();
×
926
}
×
927

928
void GraphRenderer::onCommandsFinished()
929
{
×
930
    enableSceneUpdate();
×
931
    update();
×
932
}
×
933

934
void GraphRenderer::onLayoutInitialised()
935
{
×
936
    _layoutInitialised = true;
×
937
    _layoutInitialised.notify_one();
×
938
}
×
939

940
void GraphRenderer::onLayoutChanged()
941
{
×
942
    _layoutChanged = true;
×
943
}
×
944

945
void GraphRenderer::onComponentAlphaChanged(ComponentId)
946
{
×
947
    updateGPUData(When::Later);
×
948
}
×
949

950
void GraphRenderer::onComponentCleanup(ComponentId)
951
{
×
952
    updateGPUData(When::Later);
×
953
}
×
954

955
void GraphRenderer::onVisibilityChanged()
956
{
×
957
    updateGPUData(When::Later);
×
958
}
×
959

960
GLuint GraphRenderer::sdfTexture() const
961
{
×
962
    return _sdfTexture.front();
×
963
}
×
964

965
QSize GraphRenderer::sdfTextureSize() const
966
{
×
967
    return _sdfTextureSize;
×
968
}
×
969

970
void GraphRenderer::updateText()
971
{
×
972
    const std::unique_lock<std::recursive_mutex> lock(_glyphMap->mutex());
×
973

974
    for(auto nodeId : _graphModel->graph().nodeIds())
×
975
        _glyphMap->addText(_graphModel->nodeVisual(nodeId)._text);
×
976

977
    for(auto edgeId : _graphModel->graph().edgeIds())
×
978
        _glyphMap->addText(_graphModel->edgeVisual(edgeId)._text);
×
979

980
    _graphModel->forEachTextVisual([this](const TextVisual& textVisual)
×
981
    {
×
982
        _glyphMap->addText(textVisual._text);
×
983
    });
×
984

985
    if(_glyphMap->updateRequired())
×
986
    {
×
987
        _glyphMap->update();
×
988

989
        executeOnRendererThread([this]
×
990
        {
×
991
            _sdfTextureSize = renderSdfTexture(*_glyphMap, _sdfTexture.back());
×
992
            _sdfTexture.swap();
×
993
            _textLayoutResults = _glyphMap->results();
×
994

995
            updateGPUData(When::Later);
×
996
            update(); // QQuickFramebufferObject::Renderer::update
×
997
        }, u"GraphRenderer::updateText"_s);
×
998
    }
×
999
}
×
1000

1001
void GraphRenderer::resetView()
1002
{
×
1003
    if(_scene != nullptr)
×
1004
        _scene->resetView();
×
1005
}
×
1006

1007
bool GraphRenderer::viewIsReset() const
1008
{
×
1009
    if(_scene != nullptr)
×
1010
        return _scene->viewIsReset();
×
1011

1012
    return true;
×
1013
}
×
1014

1015
void GraphRenderer::processEventQueue()
1016
{
×
1017
    while(!_eventQueue.empty())
×
1018
    {
×
1019
        auto e = std::move(_eventQueue.front());
×
1020
        _eventQueue.pop();
×
1021

1022
        // You might expect mouse button events to be delivered as QMouseEvents,
1023
        // and for the most part they are, except when a touchscreen device is
1024
        // used to generate them, specifically a touchscreen laptop. Under this
1025
        // regime, we seem to only get QSinglePointEvents. This is a base for
1026
        // QMouseEvent, so we get the same information we need for both cases.
1027
        auto* singlePointEvent = dynamic_cast<QSinglePointEvent*>(e.get());
×
1028
        auto* wheelEvent = dynamic_cast<QWheelEvent*>(e.get());
×
1029
        auto* nativeEvent = dynamic_cast<QNativeGestureEvent*>(e.get());
×
1030

1031
        switch(e->type())
×
1032
        {
×
1033
        case QEvent::Type::MouseButtonPress:
×
1034
            Q_ASSERT(singlePointEvent != nullptr);
×
1035
            _interactor->mousePressEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1036
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1037

1038
            break;
×
1039

1040
        case QEvent::Type::MouseButtonRelease:
×
1041
            Q_ASSERT(singlePointEvent != nullptr);
×
1042
            _interactor->mouseReleaseEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1043
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1044

1045
            break;
×
1046

1047
        case QEvent::Type::MouseMove:
×
1048
            Q_ASSERT(singlePointEvent != nullptr);
×
1049
            _interactor->mouseMoveEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1050
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1051

1052
            break;
×
1053

1054
        case QEvent::Type::MouseButtonDblClick:
×
1055
            Q_ASSERT(singlePointEvent != nullptr);
×
1056
            _interactor->mouseDoubleClickEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
×
1057
                singlePointEvent->modifiers(), singlePointEvent->button());
×
1058

1059
            break;
×
1060

1061
        case QEvent::Type::Wheel:
×
1062
            Q_ASSERT(wheelEvent != nullptr);
×
1063
            switch(wheelEvent->deviceType())
×
1064
            {
×
1065
            case QInputDevice::DeviceType::Mouse:
×
1066
                _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1067
                    wheelEvent->angleDelta().y());
×
1068
                break;
×
1069

1070
            case QInputDevice::DeviceType::TouchScreen:
×
1071
            case QInputDevice::DeviceType::TouchPad:
×
1072
            {
×
1073
                if(u::pref(u"misc/panGestureZooms"_s).toBool())
×
1074
                {
×
1075
                    _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1076
                        wheelEvent->angleDelta().y());
×
1077
                }
×
1078
                else
×
1079
                {
×
1080
                    _interactor->panGestureEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1081
                        -wheelEvent->pixelDelta() * _devicePixelRatio);
×
1082
                }
×
1083

1084
                break;
×
1085
            }
×
1086

1087
            default: break;
×
1088
            }
×
1089

1090
            break;
×
1091

1092
        case QEvent::Type::NativeGesture:
×
1093
            Q_ASSERT(nativeEvent != nullptr);
×
1094
            if(nativeEvent->gestureType() == Qt::ZoomNativeGesture)
×
1095
            {
×
1096
                _interactor->zoomGestureEvent(
×
1097
                    nativeEvent->position().toPoint() * _devicePixelRatio,
×
1098
                    static_cast<float>(nativeEvent->value()));
×
1099
            }
×
1100

1101
            break;
×
1102

1103
        default: break;
×
1104
        }
×
1105
    }
×
1106
}
×
1107

1108
void GraphRenderer::updateScene()
1109
{
×
1110
    ifSceneUpdateEnabled([this]
×
1111
    {
×
1112
        _preUpdateExecutor.execute();
×
1113
    });
×
1114

1115
    if(_scene == nullptr)
×
1116
        return;
×
1117

1118
    if(_resized)
×
1119
    {
×
1120
        _scene->setViewportSize(width(), height());
×
1121
        _resized = false;
×
1122
    }
×
1123

1124
    ifSceneUpdateEnabled([this]
×
1125
    {
×
1126
        processEventQueue();
×
1127

1128
        // _synchronousLayoutChanged can only ever be (atomically) true in this scope
1129
        _synchronousLayoutChanged = _layoutChanged.exchange(false);
×
1130

1131
        // If there is a transition active then we'll need another
1132
        // frame once we're finished with this one
1133
        if(transitionActive())
×
1134
            update(); // QQuickFramebufferObject::Renderer::update
×
1135

1136
        const float dTime = secondsElapsed();
×
1137
        _transition.update(dTime);
×
1138
        _scene->update(dTime);
×
1139

1140
        if(layoutChanged())
×
1141
            updateGPUData(When::Later);
×
1142

1143
        updateGPUDataIfRequired();
×
1144
        updateComponentGPUData();
×
1145

1146
        _synchronousLayoutChanged = false;
×
1147
    });
×
1148

1149
    if(!_FBOcomplete)
×
1150
    {
×
1151
        qWarning() << "Attempting to render without a complete FBO";
×
1152
        return;
×
1153
    }
×
1154
}
×
1155

1156
GraphRenderer::Mode GraphRenderer::bestFocusParameters(GraphDisplay* graphDisplay,
1157
    ComponentIdSet& componentIds, NodeId& focusNodeId, float& radius) const
1158
{
×
1159
    radius = 0.0f;
×
1160
    focusNodeId = {};
×
1161

1162
    auto nodeIds = graphDisplay->desiredFocusNodeIds();
×
1163

1164
    // Tail nodes aren't visible, so they can't be focused
1165
    nodeIds.erase(std::ranges::remove_if(nodeIds,
×
1166
    [this](auto nodeId)
×
1167
    {
×
1168
        return _graphModel->graph().typeOf(nodeId) == MultiElementType::Tail;
×
1169
    }).begin(), nodeIds.end());
×
1170

1171
    if(nodeIds.empty())
×
1172
        return mode();
×
1173

1174
    if(nodeIds.size() == 1)
×
1175
    {
×
1176
        radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
×
1177
        focusNodeId = nodeIds.front();
×
1178
        return Mode::Component;
×
1179
    }
×
1180

1181
    for(auto nodeId : nodeIds)
×
1182
        componentIds.insert(_graphModel->graph().componentIdOfNode(nodeId));
×
1183

1184
    if(componentIds.size() > 1)
×
1185
    {
×
1186
        // We want to focus on multiple nodes, but they span multiple components
1187
        if(mode() == Mode::Component && u::pref(u"misc/stayInComponentMode"_s).toBool())
×
1188
        {
×
1189
            // Prune the nodeIds we consider for focus down to only those in the focused component
1190
            auto focusedComponentId = _graphComponentScene->componentId();
×
1191

1192
            nodeIds.erase(std::ranges::remove_if(nodeIds,
×
1193
            [this, focusedComponentId](auto nodeId)
×
1194
            {
×
1195
                return _graphModel->graph().componentIdOfNode(nodeId) != focusedComponentId;
×
1196
            }).begin(), nodeIds.end());
×
1197
        }
×
1198
        else
×
1199
            return Mode::Overview;
×
1200
    }
×
1201

1202
    // None of the nodes are in the currently focused component
1203
    if(nodeIds.empty())
×
1204
        return Mode::Overview;
×
1205

1206
    // If the request is for more than 1 node, then find their barycentre and
1207
    // pick the closest node to where ever this happens to be
1208
    std::vector<QVector3D> points;
×
1209
    points.reserve(nodeIds.size());
×
1210
    for(auto nodeId : nodeIds)
×
1211
    {
×
1212
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1213
        points.push_back(nodePosition);
×
1214
    }
×
1215

1216
    const BoundingSphere boundingSphere(points);
×
1217
    const QVector3D centre = boundingSphere.centre();
×
1218
    float minDistance = std::numeric_limits<float>::max();
×
1219
    NodeId closestToCentreNodeId;
×
1220
    for(auto nodeId : nodeIds)
×
1221
    {
×
1222
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1223
        const float distance = (centre - nodePosition).length();
×
1224

1225
        if(distance < minDistance)
×
1226
        {
×
1227
            minDistance = distance;
×
1228
            closestToCentreNodeId = nodeId;
×
1229
        }
×
1230
    }
×
1231

1232
    radius = GraphComponentRenderer::maxNodeDistanceFromPoint(*_graphModel,
×
1233
        _graphModel->nodePositions().get(closestToCentreNodeId), nodeIds);
×
1234
    focusNodeId = closestToCentreNodeId;
×
1235

1236
    return mode();
×
1237
}
×
1238

1239
QOpenGLFramebufferObject* GraphRenderer::createFramebufferObject(const QSize& size)
1240
{
×
1241
    // Piggy back our FBO resize on to Qt's
1242
    _FBOcomplete = resize(size.width(), size.height());
×
1243
    _resized = true;
×
1244

1245
    return new QOpenGLFramebufferObject(size);
×
1246
}
×
1247

1248
void GraphRenderer::render()
1249
{
×
1250
    if(!_FBOcomplete)
×
1251
    {
×
1252
        qWarning() << "Attempting to render incomplete FBO";
×
1253
        return;
×
1254
    }
×
1255

1256
    updateScene();
×
1257

1258
    QQuickOpenGLUtils::resetOpenGLState();
×
1259
    glViewport(0, 0, width(), height());
×
1260

1261
    renderGraph();
×
1262
    render2D(_selectionRect);
×
1263

1264
    // Check the normal FBO
1265
    if(!framebufferObject()->bind())
×
1266
        qWarning() << "QQuickFrameBufferobject::Renderer FBO not bound";
×
1267

1268
    renderToScreen();
×
1269

1270
    QQuickOpenGLUtils::resetOpenGLState();
×
1271

1272
    _performanceCounter.tick();
×
1273
}
×
1274

1275
void GraphRenderer::synchronize(QQuickFramebufferObject* item)
1276
{
×
1277
    _devicePixelRatio = item->window()->devicePixelRatio();
×
1278

1279
    auto* graphDisplay = qobject_cast<GraphDisplay*>(item);
×
1280

1281
    if(graphDisplay->viewResetPending())
×
1282
        resetView();
×
1283

1284
    if(graphDisplay->overviewModeSwitchPending())
×
1285
        switchToOverviewMode();
×
1286

1287
    setProjection(graphDisplay->projection());
×
1288
    setShading(graphDisplay->projection() == Projection::TwoDee ?
×
1289
        graphDisplay->shading2D() : graphDisplay->shading3D());
×
1290

1291
    ComponentIdSet componentIds;
×
1292
    NodeId focusNodeId;
×
1293
    float radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
×
1294
    auto targetMode = bestFocusParameters(graphDisplay, componentIds, focusNodeId, radius);
×
1295
    const ComponentId focusComponentId = graphDisplay->desiredFocusComponentId();
×
1296

1297
    if(mode() == Mode::Component && targetMode == Mode::Overview)
×
1298
        switchToOverviewMode("doTransition"_yes, u::vectorFrom(componentIds));
×
1299
    else if(!focusNodeId.isNull())
×
1300
        moveFocusToNode(focusNodeId, radius);
×
1301
    else if(!focusComponentId.isNull())
×
1302
    {
×
1303
        if(mode() == Mode::Overview)
×
1304
            switchToComponentMode("doTransition"_yes, focusComponentId);
×
1305
        else
×
1306
            moveFocusToComponent(focusComponentId);
×
1307
    }
×
1308
    else if(mode() == Mode::Overview && !componentIds.empty())
×
1309
        moveFocusToComponents(u::vectorFrom(componentIds));
×
1310

1311
    ifSceneUpdateEnabled([this, &graphDisplay]
×
1312
    {
×
1313
        auto& newEvents = graphDisplay->events();
×
1314
        while(!newEvents.empty())
×
1315
        {
×
1316
            _eventQueue.push(std::move(newEvents.front()));
×
1317
            newEvents.pop();
×
1318
        }
×
1319
    });
×
1320

1321
    // Tell the QuickItem what we're doing
1322
    graphDisplay->setViewIsReset(viewIsReset());
×
1323
    graphDisplay->setCanEnterOverviewMode(mode() != Mode::Overview && _numComponents > 1);
×
1324
    graphDisplay->setInOverviewMode(mode() == Mode::Overview);
×
1325

1326
    const ComponentId focusedComponentId = mode() != Mode::Overview ? _graphComponentScene->componentId() : ComponentId();
×
1327
    graphDisplay->setFocusedComponentId(focusedComponentId);
×
1328

1329
    emit synchronizeComplete();
×
1330
}
×
1331

1332
GraphComponentRenderer* GraphRenderer::componentRendererForId(ComponentId componentId) const
1333
{
×
1334
    if(componentId.isNull())
×
1335
        return nullptr;
×
1336

1337
    GraphComponentRenderer* renderer = _componentRenderers.at(componentId);
×
1338
    Q_ASSERT(renderer != nullptr);
×
1339
    return renderer;
×
1340
}
×
1341

1342
void GraphRenderer::enableSceneUpdate()
1343
{
×
1344
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1345
    Q_ASSERT(_sceneUpdateDisabled > 0);
×
1346
    _sceneUpdateDisabled--;
×
1347
    resetTime();
×
1348
}
×
1349

1350
void GraphRenderer::disableSceneUpdate()
1351
{
×
1352
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1353
    _sceneUpdateDisabled++;
×
1354
}
×
1355

1356
void GraphRenderer::ifSceneUpdateEnabled(const std::function<void()>& f) const
1357
{
×
1358
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
×
1359
    if(_sceneUpdateDisabled == 0)
×
1360
        f();
×
1361
}
×
1362

1363
void GraphRenderer::clearHiddenElements()
1364
{
×
1365
    _hiddenNodes.resetElements();
×
1366
    _hiddenEdges.resetElements();
×
1367
}
×
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