Krita Source Code Documentation
Loading...
Searching...
No Matches
KisOpenGLCanvasRenderer.cpp
Go to the documentation of this file.
1/* This file is part of the KDE project
2 * SPDX-FileCopyrightText: 2006-2013 Boudewijn Rempt <boud@valdyas.org>
3 * SPDX-FileCopyrightText: 2015 Michael Abrahams <miabraha@gmail.com>
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8#define GL_GLEXT_PROTOTYPES
9
11
12#include "kis_algebra_2d.h"
14#include "canvas/kis_canvas2.h"
18#include "KisOpenGLModeProber.h"
20#include "kis_config.h"
21#include "kis_debug.h"
22
23#include <QPainter>
24#include <QPainterPath>
25#include <QOpenGLPaintDevice>
26#include <QPointF>
27#include <QTransform>
28#include <QThread>
29#include <QFile>
30#include <QOpenGLShaderProgram>
31#include <QOpenGLVertexArrayObject>
32#include <QOpenGLBuffer>
33#include <QOpenGLFramebufferObject>
34#include <QOpenGLFramebufferObjectFormat>
35#include <QMessageBox>
36#include <QVector3D>
40#include "kis_painting_tweaks.h"
42#include <KisDisplayConfig.h>
43
44#include <config-ocio.h>
45
46#define NEAR_VAL -1000.0
47#define FAR_VAL 1000.0
48
49#ifndef GL_CLAMP_TO_EDGE
50#define GL_CLAMP_TO_EDGE 0x812F
51#endif
52
53#define PROGRAM_VERTEX_ATTRIBUTE 0
54#define PROGRAM_TEXCOORD_ATTRIBUTE 1
55
56// These buffers are used only for painting checkers,
57// so we can keep the number really low
58static constexpr int NumberOfBuffers = 2;
59
61{
62public:
64 delete displayShader;
65 delete checkerShader;
66 delete solidColorShader;
67
68 delete canvasBridge;
69 }
70
71 bool canvasInitialized{false};
72
74
79
80 QScopedPointer<QOpenGLFramebufferObject> canvasFBO;
81
83
86
90
91 bool wrapAroundMode{false};
93
94 // Stores a quad for drawing the canvas
95 QOpenGLVertexArrayObject quadVAO;
96
99
100 // Stores data for drawing tool outlines
101 QOpenGLVertexArrayObject outlineVAO;
102 QOpenGLBuffer lineVertexBuffer;
103
104 QVector3D vertices[6];
105 QVector2D texCoords[6];
106
109 QColor gridColor;
111
113
117
118 int xToColWithWrapCompensation(int x, const QRect &imageRect) {
119 int firstImageColumn = openGLImageTextures->xToCol(imageRect.left());
120 int lastImageColumn = openGLImageTextures->xToCol(imageRect.right());
121
122 int colsPerImage = lastImageColumn - firstImageColumn + 1;
123 int numWraps = floor(qreal(x) / imageRect.width());
124 int remainder = x - imageRect.width() * numWraps;
125
126 return colsPerImage * numWraps + openGLImageTextures->xToCol(remainder);
127 }
128
129 int yToRowWithWrapCompensation(int y, const QRect &imageRect) {
130 int firstImageRow = openGLImageTextures->yToRow(imageRect.top());
131 int lastImageRow = openGLImageTextures->yToRow(imageRect.bottom());
132
133 int rowsPerImage = lastImageRow - firstImageRow + 1;
134 int numWraps = floor(qreal(y) / imageRect.height());
135 int remainder = y - imageRect.height() * numWraps;
136
137 return rowsPerImage * numWraps + openGLImageTextures->yToRow(remainder);
138 }
139
140};
141
143 KisImageWSP image,
144 const KisDisplayConfig &displayConfig,
146 : d(new Private())
147{
148 d->canvasBridge = canvasBridge;
149
150 const KisDisplayConfig &config = displayConfig;
151
154 config.profile,
155 config.intent,
156 config.conversionFlags);
157
158
159 setDisplayFilterImpl(displayFilter, true);
160}
161
166
171
172QOpenGLContext *KisOpenGLCanvasRenderer::context() const
173{
174 return d->canvasBridge->openglContext();
175}
176
181
186
188{
189 return d->canvasBridge->borderColor();
190}
191
196
198{
199 bool needsInternalColorManagement =
200 !displayFilter || displayFilter->useInternalColorManagement();
201
202 bool needsFullRefresh = d->openGLImageTextures->setInternalColorManagementActive(needsInternalColorManagement);
203
204 d->displayFilter = displayFilter;
205
206 if (!initializing && needsFullRefresh) {
207 canvas()->startUpdateInPatches(canvas()->image()->bounds());
208 }
209 else if (!initializing) {
210 canvas()->updateCanvas();
211 }
212}
213
215{
216 // FIXME: on color space change the data is refetched multiple
217 // times by different actors!
218
220 canvas()->startUpdateInPatches(canvas()->image()->bounds());
221 }
222}
223
228
233
238
243
245{
247 initializeOpenGLFunctions();
248
249 KisConfig cfg(true);
250 d->openGLImageTextures->setProofingConfig(canvas()->proofingConfiguration());
251 d->openGLImageTextures->initGL(context()->functions());
253
255
256 // If we support OpenGL 3.0, then prepare our VAOs and VBOs for drawing
258 d->quadVAO.create();
259 d->quadVAO.bind();
260
261 glEnableVertexAttribArray(PROGRAM_VERTEX_ATTRIBUTE);
262 glEnableVertexAttribArray(PROGRAM_TEXCOORD_ATTRIBUTE);
263
264 d->checkersVertexBuffer.allocate(NumberOfBuffers, 6 * 3 * sizeof(float));
265 d->checkersTextureVertexBuffer.allocate(NumberOfBuffers, 6 * 2 * sizeof(float));
266
267 // Create the outline buffer, this buffer will store the outlines of
268 // tools and will frequently change data
269 d->outlineVAO.create();
270 d->outlineVAO.bind();
271
272 glEnableVertexAttribArray(PROGRAM_VERTEX_ATTRIBUTE);
273
274 // The outline buffer has a StreamDraw usage pattern, because it changes constantly
275 d->lineVertexBuffer.create();
276 d->lineVertexBuffer.setUsagePattern(QOpenGLBuffer::StreamDraw);
277 d->lineVertexBuffer.bind();
278 glVertexAttribPointer(PROGRAM_VERTEX_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, 0);
279 }
280
281 d->canvasInitialized = true;
282}
283
305
307{
309
310 bool useHiQualityFiltering = d->filterMode == KisOpenGL::HighQualityFiltering;
311
312 delete d->displayShader;
313 d->displayShader = 0;
314
315 try {
316 d->displayShader = d->shaderLoader.loadDisplayShader(d->displayFilter, useHiQualityFiltering);
318 } catch (const ShaderLoaderException &e) {
320 }
321}
322
328{
329 KisConfig cfg(false);
330
331 qDebug() << "Shader Compilation Failure: " << context;
332 // TODO: Should do something else when using QtQuick2
333 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"),
334 i18n("Krita could not initialize the OpenGL canvas:\n\n%1\n\n Krita will disable OpenGL and close now.", context),
335 QMessageBox::Close);
336
337 cfg.disableOpenGL();
338 cfg.setCanvasState("OPENGL_FAILED");
339}
340
341void KisOpenGLCanvasRenderer::resizeGL(int width, int height)
342{
343 {
344 // just a sanity check!
345 //
346 // This is how QOpenGLCanvas sets the FBO and the viewport size. If
347 // devicePixelRatioF() is non-integral, the result is truncated.
348 // *Correction*: The FBO size is actually rounded, but the glViewport call
349 // uses integer truncation and that's what really matters.
350 int viewportWidth = static_cast<int>(width * devicePixelRatioF());
351 int viewportHeight = static_cast<int>(height * devicePixelRatioF());
352
353 // we expect the size to be adjusted in the converter at the higher
354 // level of hierarchy
355 KIS_SAFE_ASSERT_RECOVER_NOOP(QSize(viewportWidth, viewportHeight) == coordinatesConverter()->viewportDevicePixelSize());
356 }
357
360
362 QOpenGLFramebufferObjectFormat format;
363 format.setInternalTextureFormat(d->canvasBridge->internalTextureFormat());
364 d->canvasFBO.reset(new QOpenGLFramebufferObject(d->viewportDevicePixelSize, format));
365 }
366}
367
368void KisOpenGLCanvasRenderer::paintCanvasOnly(const QRect &canvasImageDirtyRect, const QRect &viewportUpdateRect)
369{
370 if (d->canvasFBO) {
371 if (!canvasImageDirtyRect.isEmpty()) {
372 d->canvasFBO->bind();
373 renderCanvasGL(canvasImageDirtyRect);
374 d->canvasFBO->release();
375 }
376 QRect blitRect;
377 if (viewportUpdateRect.isEmpty()) {
378 blitRect = QRect(QPoint(), d->viewportDevicePixelSize);
379 } else {
380 const QTransform scale = QTransform::fromScale(1.0, -1.0) * QTransform::fromTranslate(0, d->pixelAlignedWidgetSize.height()) * QTransform::fromScale(devicePixelRatioF(), devicePixelRatioF());
381 blitRect = scale.mapRect(QRectF(viewportUpdateRect)).toAlignedRect();
382 }
383 QOpenGLFramebufferObject::blitFramebuffer(nullptr, blitRect, d->canvasFBO.data(), blitRect, GL_COLOR_BUFFER_BIT, GL_NEAREST);
384 QOpenGLFramebufferObject::bindDefault();
385 } else {
386 QRect fullUpdateRect = canvasImageDirtyRect | viewportUpdateRect;
387 if (fullUpdateRect.isEmpty()) {
388 fullUpdateRect = QRect(QPoint(), d->viewportDevicePixelSize);
389 }
390 renderCanvasGL(fullUpdateRect);
391 }
392}
393
394void KisOpenGLCanvasRenderer::paintToolOutline(const KisOptimizedBrushOutline &path, const QRect &viewportUpdateRect, const int thickness)
395{
396 if (!d->solidColorShader->bind()) {
397 return;
398 }
399
400 const QSizeF &widgetSize = d->pixelAlignedWidgetSize;
401
402 // setup the mvp transformation
403 QMatrix4x4 projectionMatrix;
404 projectionMatrix.setToIdentity();
405 // FIXME: It may be better to have the projection in device pixel, but
406 // this requires introducing a new coordinate system.
407 projectionMatrix.ortho(0, widgetSize.width(), widgetSize.height(), 0, NEAR_VAL, FAR_VAL);
408
409 // Set view/projection matrices
410 QMatrix4x4 modelMatrix(coordinatesConverter()->flakeToWidgetTransform());
411 modelMatrix.optimize();
412 modelMatrix = projectionMatrix * modelMatrix;
414
415 d->solidColorShader->setUniformValue(
417 QVector4D(d->cursorColor.redF(), d->cursorColor.greenF(), d->cursorColor.blueF(), 1.0f));
418
419 glEnable(GL_BLEND);
420 glBlendFuncSeparate(GL_ONE, GL_SRC_COLOR, GL_ONE, GL_ONE);
421 glBlendEquationSeparate(GL_FUNC_SUBTRACT, GL_FUNC_ADD);
422
423
424 if (!viewportUpdateRect.isEmpty()) {
425 const QRect deviceUpdateRect = widgetToSurface(viewportUpdateRect).toAlignedRect();
426 glScissor(deviceUpdateRect.x(), deviceUpdateRect.y(), deviceUpdateRect.width(), deviceUpdateRect.height());
427 glEnable(GL_SCISSOR_TEST);
428 }
429
430 // Paint the tool outline
432 d->outlineVAO.bind();
433 d->lineVertexBuffer.bind();
434 }
435
436 QVector<QVector3D> verticesBuffer;
437
438 if (thickness > 1) {
439 // Because glLineWidth is not supported on all versions of OpenGL (or rather,
440 // is limited to 1, as returned by GL_ALIASED_LINE_WIDTH_RANGE),
441 // we'll instead generate mitered-triangles.
442
443 const qreal halfWidth = (thickness * 0.5) / devicePixelRatioF();
444 const qreal miterLimit = (5 * thickness) / devicePixelRatioF();
445
446 for (auto it = path.begin(); it != path.end(); ++it) {
447 const QPolygonF& polygon = *it;
448
449 if (KisAlgebra2D::maxDimension(polygon.boundingRect()) < 0.5 * thickness) {
450 continue;
451 }
452
453 int triangleCount = 0;
454 verticesBuffer.clear();
455 const bool closed = polygon.isClosed();
456
457 for( int i = 1; i < polygon.count(); i++) {
458 bool adjustFirst = closed? true: i > 1;
459 bool adjustSecond = closed? true: i + 1 < polygon.count();
460
461 QPointF p1 = polygon.at(i - 1);
462 QPointF p2 = polygon.at(i);
463 QPointF normal = p2 - p1;
464 normal = KisAlgebra2D::normalize(QPointF(-normal.y(), normal.x()));
465
466 QPointF c1 = p1 - (normal * halfWidth);
467 QPointF c2 = p1 + (normal * halfWidth);
468 QPointF c3 = p2 - (normal * halfWidth);
469 QPointF c4 = p2 + (normal * halfWidth);
470
471 // Add miter
472 if (adjustFirst) {
473 QPointF pPrev = i >= 2 ?
474 QPointF(polygon.at(i-2)) :
475 QPointF(polygon.at(qMax(polygon.count() - 2, 0)));
476
477 pPrev = p1 - pPrev;
478
479 QPointF miter =
482 QPointF(-pPrev.y(), pPrev.x())));
483
484 const qreal dot = KisAlgebra2D::dotProduct(miter, normal);
485
486 if (KisAlgebra2D::norm((miter * halfWidth) / dot) < miterLimit) {
487 c1 = p1 + ((miter * -halfWidth) / dot);
488 c2 = p1 + ((miter * halfWidth) / dot);
489 }
490 }
491
492 if (adjustSecond) {
493 QPointF pNext = i + 1 < polygon.count()? QPointF(polygon.at(i+1))
494 : QPointF(polygon.at(qMin(polygon.count(), 1)));
495 pNext = pNext - p2;
496 QPointF miter =
498 normal + KisAlgebra2D::normalize(QPointF(-pNext.y(), pNext.x())));
499 const qreal dot = KisAlgebra2D::dotProduct(miter, normal);
500
501 if (KisAlgebra2D::norm((miter * halfWidth) / dot) < miterLimit) {
502 c3 = p2 + ((miter * -halfWidth) / dot);
503 c4 = p2 + (miter * halfWidth) / dot;
504 }
505 }
506
507 verticesBuffer.append(QVector3D(c1));
508 verticesBuffer.append(QVector3D(c3));
509 verticesBuffer.append(QVector3D(c2));
510 verticesBuffer.append(QVector3D(c4));
511 verticesBuffer.append(QVector3D(c2));
512 verticesBuffer.append(QVector3D(c3));
513 triangleCount += 2;
514 }
515
517 d->lineVertexBuffer.bind();
518 d->lineVertexBuffer.allocate(verticesBuffer.constData(), 3 * verticesBuffer.size() * sizeof(float));
519 }
520 else {
521 d->solidColorShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
522 d->solidColorShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, verticesBuffer.constData());
523 }
524
525 glDrawArrays(GL_TRIANGLES, 0, triangleCount * 3);
526 }
527 } else {
528 // Convert every disjointed subpath to a polygon and draw that polygon
529 for (auto it = path.begin(); it != path.end(); ++it) {
530 const QPolygonF& polygon = *it;
531
532 if (KisAlgebra2D::maxDimension(polygon.boundingRect()) < 0.5) {
533 continue;
534 }
535
536 const int verticesCount = polygon.count();
537
538 if (verticesBuffer.size() < verticesCount) {
539 verticesBuffer.resize(verticesCount);
540 }
541
542 for (int vertIndex = 0; vertIndex < verticesCount; vertIndex++) {
543 QPointF point = polygon.at(vertIndex);
544 verticesBuffer[vertIndex].setX(point.x());
545 verticesBuffer[vertIndex].setY(point.y());
546 }
548 d->lineVertexBuffer.bind();
549 d->lineVertexBuffer.allocate(verticesBuffer.constData(), 3 * verticesCount * sizeof(float));
550 }
551 else {
552 d->solidColorShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
553 d->solidColorShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, verticesBuffer.constData());
554 }
555
556
557
558 glDrawArrays(GL_LINE_STRIP, 0, verticesCount);
559 }
560 }
561
563 d->lineVertexBuffer.release();
564 d->outlineVAO.release();
565 }
566
567 if (!viewportUpdateRect.isEmpty()) {
568 glDisable(GL_SCISSOR_TEST);
569 }
570
571 glBlendEquation(GL_FUNC_ADD);
572 glBlendFunc(GL_ONE, GL_ZERO);
573 glDisable(GL_BLEND);
574
575 d->solidColorShader->release();
576}
577
582
583void KisOpenGLCanvasRenderer::drawBackground(const QRect &updateRect)
584{
585 Q_UNUSED(updateRect);
586
587 // Draw the border (that is, clear the whole widget to the border color)
588 QColor widgetBackgroundColor = borderColor();
589
590 const KoColorSpace *finalColorSpace =
594
595 KoColor convertedBackgroundColor = KoColor(widgetBackgroundColor, KoColorSpaceRegistry::instance()->rgb8());
596 convertedBackgroundColor.convertTo(finalColorSpace);
597
598 QVector<float> channels = QVector<float>(4);
599 convertedBackgroundColor.colorSpace()->normalisedChannelsValue(convertedBackgroundColor.data(), channels);
600
601
602 // Data returned by KoRgbU8ColorSpace comes in the order: blue, green, red.
603 glClearColor(channels[2], channels[1], channels[0], 1.0);
604 glClear(GL_COLOR_BUFFER_BIT);
605}
606
607void KisOpenGLCanvasRenderer::drawCheckers(const QRect &updateRect)
608{
609 Q_UNUSED(updateRect);
610
611 if (!d->checkerShader) {
612 return;
613 }
614
616 QTransform textureTransform;
617 QTransform modelTransform;
618 QRectF textureRect;
619 QRectF modelRect;
620
621 const QSizeF &widgetSize = d->pixelAlignedWidgetSize;
622 QRectF viewportRect;
623 if (!d->wrapAroundMode) {
624 viewportRect = converter->imageRectInViewportPixels();
625 }
626 else {
627 const QRectF ir = converter->imageRectInViewportPixels();
628 viewportRect = converter->widgetToViewport(QRectF(0, 0, widgetSize.width(), widgetSize.height()));
630 viewportRect.setTop(ir.top());
631 viewportRect.setBottom(ir.bottom());
632 }
634 viewportRect.setLeft(ir.left());
635 viewportRect.setRight(ir.right());
636 }
637 }
638
639 // TODO: check if it works correctly
640 if (!canvas()->renderingLimit().isEmpty()) {
641 const QRect vrect = converter->imageToViewport(canvas()->renderingLimit()).toAlignedRect();
642 viewportRect &= vrect;
643 }
644
645 converter->getOpenGLCheckersInfo(viewportRect,
646 &textureTransform, &modelTransform, &textureRect, &modelRect, d->scrollCheckers);
647
648 textureTransform *= QTransform::fromScale(d->checkSizeScale / KisOpenGLImageTextures::BACKGROUND_TEXTURE_SIZE,
650
651 if (!d->checkerShader->bind()) {
652 qWarning() << "Could not bind checker shader";
653 return;
654 }
655
656 QMatrix4x4 projectionMatrix;
657 projectionMatrix.setToIdentity();
658 // FIXME: It may be better to have the projection in device pixel, but
659 // this requires introducing a new coordinate system.
660 projectionMatrix.ortho(0, widgetSize.width(), widgetSize.height(), 0, NEAR_VAL, FAR_VAL);
661
662 // Set view/projection matrices
663 QMatrix4x4 modelMatrix(modelTransform);
664 modelMatrix.optimize();
665 modelMatrix = projectionMatrix * modelMatrix;
666 d->checkerShader->setUniformValue(d->checkerShader->location(Uniform::ModelViewProjection), modelMatrix);
667
668 QMatrix4x4 textureMatrix(textureTransform);
669 d->checkerShader->setUniformValue(d->checkerShader->location(Uniform::TextureMatrix), textureMatrix);
670
671 //Setup the geometry for rendering
674 QOpenGLBuffer *vertexBuf = d->checkersVertexBuffer.getNextBuffer();
675
676 vertexBuf->bind();
677 vertexBuf->write(0, d->vertices, 3 * 6 * sizeof(float));
678 glVertexAttribPointer(PROGRAM_VERTEX_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, 0);
679
680
682 QOpenGLBuffer *vertexTextureBuf = d->checkersTextureVertexBuffer.getNextBuffer();
683
684 vertexTextureBuf->bind();
685 vertexTextureBuf->write(0, d->texCoords, 2 * 6 * sizeof(float));
686 glVertexAttribPointer(PROGRAM_TEXCOORD_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, 0);
687 }
688 else {
690 d->checkerShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
691 d->checkerShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, d->vertices);
692
694 d->checkerShader->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
696 }
697
698 // render checkers
699 glActiveTexture(GL_TEXTURE0);
700 glBindTexture(GL_TEXTURE_2D, d->openGLImageTextures->checkerTexture());
701
702 glDrawArrays(GL_TRIANGLES, 0, 6);
703
704 glBindTexture(GL_TEXTURE_2D, 0);
705 d->checkerShader->release();
706 glBindBuffer(GL_ARRAY_BUFFER, 0);
707}
708
709void KisOpenGLCanvasRenderer::drawGrid(const QRect &updateRect)
710{
711 if (!d->solidColorShader->bind()) {
712 return;
713 }
714
715 const QSizeF &widgetSize = d->pixelAlignedWidgetSize;
716
717 QMatrix4x4 projectionMatrix;
718 projectionMatrix.setToIdentity();
719 // FIXME: It may be better to have the projection in device pixel, but
720 // this requires introducing a new coordinate system.
721 projectionMatrix.ortho(0, widgetSize.width(), widgetSize.height(), 0, NEAR_VAL, FAR_VAL);
722
723 // Set view/projection matrices
724 QMatrix4x4 modelMatrix(coordinatesConverter()->imageToWidgetTransform());
725 modelMatrix.optimize();
726 modelMatrix = projectionMatrix * modelMatrix;
728
729 glEnable(GL_BLEND);
730 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
731
732 d->solidColorShader->setUniformValue(
734 QVector4D(d->gridColor.redF(), d->gridColor.greenF(), d->gridColor.blueF(), 0.5f));
735
736 QRectF widgetRect(0,0, widgetSize.width(), widgetSize.height());
737 QRectF widgetRectInImagePixels = coordinatesConverter()->documentToImage(coordinatesConverter()->widgetToDocument(widgetRect));
738 QRect wr = widgetRectInImagePixels.toAlignedRect();
739
740 if (!d->wrapAroundMode) {
742 }
743
744 if (!updateRect.isEmpty()) {
745 const QRect updateRectInImagePixels = coordinatesConverter()->widgetToImage(updateRect).toAlignedRect();
746 wr &= updateRectInImagePixels;
747 }
748
749 QPoint topLeftCorner = wr.topLeft();
750 QPoint bottomRightCorner = wr.bottomRight() + QPoint(1, 1);
752
753 for (int i = topLeftCorner.x(); i <= bottomRightCorner.x(); ++i) {
754 grid.append(QVector3D(i, topLeftCorner.y(), 0));
755 grid.append(QVector3D(i, bottomRightCorner.y(), 0));
756 }
757 for (int i = topLeftCorner.y(); i <= bottomRightCorner.y(); ++i) {
758 grid.append(QVector3D(topLeftCorner.x(), i, 0));
759 grid.append(QVector3D(bottomRightCorner.x(), i, 0));
760 }
761
763 d->outlineVAO.bind();
764 d->lineVertexBuffer.bind();
765 d->lineVertexBuffer.allocate(grid.constData(), 3 * grid.size() * sizeof(float));
766 }
767 else {
768 d->solidColorShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
769 d->solidColorShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, grid.constData());
770 }
771
772 glDrawArrays(GL_LINES, 0, grid.size());
773
775 d->lineVertexBuffer.release();
776 d->outlineVAO.release();
777 }
778
779 d->solidColorShader->release();
780 glDisable(GL_BLEND);
781}
782
783void KisOpenGLCanvasRenderer::drawImage(const QRect &updateRect)
784{
785 if (!d->displayShader) {
786 return;
787 }
788
789 glEnable(GL_BLEND);
790 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
791
793
794 d->displayShader->bind();
795
796 const QSizeF &widgetSize = d->pixelAlignedWidgetSize;
797
798 QMatrix4x4 textureMatrix;
799 textureMatrix.setToIdentity();
800 d->displayShader->setUniformValue(d->displayShader->location(Uniform::TextureMatrix), textureMatrix);
801
802 QRectF widgetRect(0,0, widgetSize.width(), widgetSize.height());
803
804 if (!updateRect.isEmpty()) {
805 widgetRect &= updateRect;
806 }
807
808 QRectF widgetRectInImagePixels = converter->documentToImage(converter->widgetToDocument(widgetRect));
809
810 const QRect renderingLimit = canvas()->renderingLimit();
811
812 if (!renderingLimit.isEmpty()) {
813 widgetRectInImagePixels &= renderingLimit;
814 }
815
816 qreal scaleX, scaleY;
817 converter->imagePhysicalScale(&scaleX, &scaleY);
818
819 d->displayShader->setUniformValue(d->displayShader->location(Uniform::ViewportScale), (GLfloat) scaleX);
821
823 QRect wr = widgetRectInImagePixels.toAlignedRect();
824
825 if (!d->wrapAroundMode) {
826 // if we don't want to paint wrapping images, just limit the
827 // processing area, and the code will handle all the rest
828 wr &= ir;
829 }
831 wr.setTop(ir.top());
832 wr.setBottom(ir.bottom());
833 }
835 wr.setLeft(ir.left());
836 wr.setRight(ir.right());
837 }
838
839 const int firstColumn = d->xToColWithWrapCompensation(wr.left(), ir);
840 const int lastColumn = d->xToColWithWrapCompensation(wr.right(), ir);
841 const int firstRow = d->yToRowWithWrapCompensation(wr.top(), ir);
842 const int lastRow = d->yToRowWithWrapCompensation(wr.bottom(), ir);
843
844 const int minColumn = d->openGLImageTextures->xToCol(ir.left());
845 const int maxColumn = d->openGLImageTextures->xToCol(ir.right());
846 const int minRow = d->openGLImageTextures->yToRow(ir.top());
847 const int maxRow = d->openGLImageTextures->yToRow(ir.bottom());
848
849 const int imageColumns = maxColumn - minColumn + 1;
850 const int imageRows = maxRow - minRow + 1;
851
852 if (d->displayFilter) {
853 d->displayFilter->setupTextures(this, d->displayShader);
854 }
855
856 const int firstCloneX = qFloor(qreal(firstColumn) / imageColumns);
857 const int lastCloneX = qFloor(qreal(lastColumn) / imageColumns);
858 const int firstCloneY = qFloor(qreal(firstRow) / imageRows);
859 const int lastCloneY = qFloor(qreal(lastRow) / imageRows);
860
861 for (int cloneY = firstCloneY; cloneY <= lastCloneY; cloneY++) {
862 for (int cloneX = firstCloneX; cloneX <= lastCloneX; cloneX++) {
863
864 const int localFirstCol = cloneX == firstCloneX ? KisAlgebra2D::wrapValue(firstColumn, imageColumns) : 0;
865 const int localLastCol = cloneX == lastCloneX ? KisAlgebra2D::wrapValue(lastColumn, imageColumns) : imageColumns - 1;
866
867 const int localFirstRow = cloneY == firstCloneY ? KisAlgebra2D::wrapValue(firstRow, imageRows) : 0;
868 const int localLastRow = cloneY == lastCloneY ? KisAlgebra2D::wrapValue(lastRow, imageRows) : imageRows - 1;
869
870 drawImageTiles(localFirstCol, localLastCol,
871 localFirstRow, localLastRow,
872 scaleX, scaleY, QPoint(cloneX, cloneY));
873 }
874 }
875
876 d->displayShader->release();
877
878 glDisable(GL_BLEND);
879}
880
881void KisOpenGLCanvasRenderer::drawImageTiles(int firstCol, int lastCol, int firstRow, int lastRow, qreal scaleX, qreal scaleY, const QPoint &wrapAroundOffset)
882{
884 const QSizeF &widgetSize = d->pixelAlignedWidgetSize;
885
886 QMatrix4x4 projectionMatrix;
887 projectionMatrix.setToIdentity();
888 // FIXME: It may be better to have the projection in device pixel, but
889 // this requires introducing a new coordinate system.
890 projectionMatrix.ortho(0, widgetSize.width(), widgetSize.height(), 0, NEAR_VAL, FAR_VAL);
891
892 QTransform modelTransform = converter->imageToWidgetTransform();
893
894 if (!wrapAroundOffset.isNull()) {
895 const QRect ir = d->openGLImageTextures->storedImageBounds();
896
897 const QTransform wrapAroundTranslate = QTransform::fromTranslate(ir.width() * wrapAroundOffset.x(),
898 ir.height() * wrapAroundOffset.y());
899 modelTransform = wrapAroundTranslate * modelTransform;
900 }
901
902 // Set view/projection matrices
903 QMatrix4x4 modelMatrix(modelTransform);
904 modelMatrix.optimize();
905 modelMatrix = projectionMatrix * modelMatrix;
906 d->displayShader->setUniformValue(d->displayShader->location(Uniform::ModelViewProjection), modelMatrix);
907
908 int lastTileLodPlane = -1;
909
910 for (int col = firstCol; col <= lastCol; col++) {
911 for (int row = firstRow; row <= lastRow; row++) {
912
913 KisTextureTile *tile =
915
916 if (!tile) {
917 warnUI << "OpenGL: Trying to paint texture tile but it has not been created yet.";
918 continue;
919 }
920
921 //Setup the geometry for rendering
923 const int tileIndex = d->openGLImageTextures->getTextureBufferIndexCR(col, row);
924
925 const int vertexRectSize = 6 * 3 * sizeof(float);
927 glVertexAttribPointer(PROGRAM_VERTEX_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(tileIndex * vertexRectSize));
928
929 const int textureRectSize = 6 * 2 * sizeof(float);
931 glVertexAttribPointer(PROGRAM_TEXCOORD_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(tileIndex * textureRectSize));
932
933 } else {
934
935 const QRectF textureRect = tile->tileRectInTexturePixels();
936 const QRectF modelRect = tile->tileRectInImagePixels();
937
939 d->checkerShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
940 d->checkerShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, d->vertices);
941
943 d->checkerShader->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
945 }
946
947 glActiveTexture(GL_TEXTURE0);
948
949 // switching uniform is a rather expensive operation on macOS, so we change it only
950 // when it is really needed
951 const int currentLodPlane = tile->bindToActiveTexture(d->lodSwitchInProgress);
953 (lastTileLodPlane < 0 || lastTileLodPlane != currentLodPlane)) {
954
956 (GLfloat) currentLodPlane);
957 lastTileLodPlane = currentLodPlane;
958 }
959
960 if (currentLodPlane > 0) {
961 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
962 } else if (SCALE_MORE_OR_EQUAL_TO(scaleX, scaleY, 2.0)) {
963 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
964 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
965 } else {
966 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
967
968 switch(d->filterMode) {
970 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
971 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
972 break;
974 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
975 break;
977 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
978 break;
980 if (SCALE_LESS_THAN(scaleX, scaleY, 0.5)) {
981 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
982 } else {
983 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
984 }
985 break;
986 }
987 }
988
989 glDrawArrays(GL_TRIANGLES, 0, 6);
990 }
991 }
992
993 glBindTexture(GL_TEXTURE_2D, 0);
994 glBindBuffer(GL_ARRAY_BUFFER, 0);
995}
996
1009
1011{
1012 KisConfig cfg(true);
1013 bool useSeparateEraserCursor = cfg.separateEraserCursor() &&
1015
1016 d->cursorColor = (!useSeparateEraserCursor) ? cfg.getCursorMainColor() : cfg.getEraserCursorMainColor();
1017}
1018
1027
1029{
1030 const qreal ratio = devicePixelRatioF();
1031
1032 return QRectF(rc.x() * ratio,
1033 (d->pixelAlignedWidgetSize.height() - rc.y() - rc.height()) * ratio,
1034 rc.width() * ratio,
1035 rc.height() * ratio);
1036}
1037
1039{
1040 const qreal ratio = devicePixelRatioF();
1041
1042 return QRectF(rc.x() / ratio,
1043 d->pixelAlignedWidgetSize.height() - (rc.y() + rc.height()) / ratio,
1044 rc.width() / ratio,
1045 rc.height() / ratio);
1046}
1047
1048
1049void KisOpenGLCanvasRenderer::renderCanvasGL(const QRect &updateRect)
1050{
1051 if ((d->displayFilter && d->displayFilter->updateShader()) ||
1053
1055
1056 d->canvasInitialized = false; // TODO: check if actually needed?
1058 d->canvasInitialized = true;
1059 }
1060
1061 if (KisOpenGL::supportsVAO()) {
1062 d->quadVAO.bind();
1063 }
1064
1065 QRect alignedUpdateRect = updateRect;
1066
1067 if (!updateRect.isEmpty()) {
1068 const QRect deviceUpdateRect = widgetToSurface(updateRect).toAlignedRect();
1069 alignedUpdateRect = surfaceToWidget(deviceUpdateRect).toAlignedRect();
1070
1071 glScissor(deviceUpdateRect.x(), deviceUpdateRect.y(), deviceUpdateRect.width(), deviceUpdateRect.height());
1072 glEnable(GL_SCISSOR_TEST);
1073 }
1074
1075 drawBackground(alignedUpdateRect);
1076 drawCheckers(alignedUpdateRect);
1077 drawImage(alignedUpdateRect);
1078
1079 if ((coordinatesConverter()->effectivePhysicalZoom() > d->pixelGridDrawingThreshold - 0.00001) && d->pixelGridEnabled) {
1080 drawGrid(alignedUpdateRect);
1081 }
1082
1083 if (!updateRect.isEmpty()) {
1084 glDisable(GL_SCISSOR_TEST);
1085 }
1086
1087 if (KisOpenGL::supportsVAO()) {
1088 d->quadVAO.release();
1089 }
1090}
1091
1098
1099void KisOpenGLCanvasRenderer::channelSelectionChanged(const QBitArray &channelFlags)
1100{
1101 d->openGLImageTextures->setChannelFlags(channelFlags);
1102}
1103
1104
1106{
1107 if (d->canvasInitialized) {
1109 }
1110}
1111
1113{
1114 if (canvas()->proofingConfigUpdated()) {
1115 d->openGLImageTextures->setProofingConfig(canvas()->proofingConfiguration());
1117 }
1119}
1120
1121
1123{
1124 // See KisQPainterCanvas::updateCanvasProjection for more info
1125 bool isOpenGLUpdateInfo = dynamic_cast<KisOpenGLUpdateInfo*>(info.data());
1126 if (isOpenGLUpdateInfo) {
1128 }
1129
1130 const QRect dirty = kisGrowRect(coordinatesConverter()->imageToWidget(info->dirtyImageRect()).toAlignedRect(), 2);
1131 return dirty;
1132}
1133
float value(const T *src, size_t ch)
QPointF p2
QPointF p1
#define NEAR_VAL
static constexpr int NumberOfBuffers
#define FAR_VAL
WrapAroundAxis
@ WRAPAROUND_HORIZONTAL
@ WRAPAROUND_BOTH
@ WRAPAROUND_VERTICAL
const KoID RGBAColorModelID("RGBA", ki18n("RGB/Alpha"))
const QString COMPOSITE_ERASE
void startUpdateInPatches(const QRect &imageRect)
QRect renderingLimit
void setProofingConfigUpdated(bool updated)
setProofingConfigUpdated This function is to set whether the proofing config is updated,...
void updateCanvas(const QRectF &rc) override
static QImage createCheckersImage(qint32 checkSize=-1)
int openGLFilteringMode(bool defaultValue=false) const
void setCanvasState(const QString &state) const
qreal getPixelGridDrawingThreshold(bool defaultValue=false) const
int numMipmapLevels(bool defaultValue=false) const
void disableOpenGL() const
QColor getPixelGridColor(bool defaultValue=false) const
bool pixelGridEnabled(bool defaultValue=false) const
bool useOpenGLTextureBuffer(bool defaultValue=false) const
qint32 checkSize(bool defaultValue=false) const
bool scrollCheckers(bool defaultValue=false) const
QColor getCursorMainColor(bool defaultValue=false) const
bool separateEraserCursor(bool defaultValue=false) const
QColor getEraserCursorMainColor(bool defaultValue=false) const
_Private::Traits< T >::Result widgetToDocument(const T &obj) const
_Private::Traits< T >::Result widgetToViewport(const T &obj) const
void imagePhysicalScale(qreal *scaleX, qreal *scaleY) const
void getOpenGLCheckersInfo(const QRectF &viewportRect, QTransform *textureTransform, QTransform *modelTransform, QRectF *textureRect, QRectF *modelRect, const bool scrollCheckers) const
_Private::Traits< T >::Result widgetToImage(const T &obj) const
_Private::Traits< T >::Result documentToImage(const T &obj) const
_Private::Traits< T >::Result imageToViewport(const T &obj) const
KisDisplayConfig This class keeps track of the color management configuration for image to display....
KoColorConversionTransformation::ConversionFlags conversionFlags
const KoColorProfile * profile
KoColorConversionTransformation::Intent intent
virtual KisCanvas2 * canvas() const =0
virtual QColor borderColor() const =0
virtual KisCoordinatesConverter * coordinatesConverter() const =0
virtual QOpenGLContext * openglContext() const =0
virtual GLenum internalTextureFormat() const =0
virtual qreal devicePixelRatioF() const =0
QRect updateCanvasProjection(KisUpdateInfoSP info)
void setDisplayFilter(QSharedPointer< KisDisplayFilter > displayFilter)
void drawImage(const QRect &updateRect)
void drawBackground(const QRect &updateRect)
QRectF surfaceToWidget(const QRectF &rc)
void resizeGL(int width, int height)
KisOpenGLImageTexturesSP openGLImageTextures() const
void channelSelectionChanged(const QBitArray &channelFlags)
QOpenGLContext * context() const
KisUpdateInfoSP startUpdateCanvasProjection(const QRect &rc)
void paintCanvasOnly(const QRect &canvasImageDirtyRect, const QRect &viewportUpdateRect=QRect())
void setDisplayFilterImpl(QSharedPointer< KisDisplayFilter > displayFilter, bool initializing)
QRectF widgetToSurface(const QRectF &rc)
void drawImageTiles(int firstCol, int lastCol, int firstRow, int lastRow, qreal scaleX, qreal scaleY, const QPoint &wrapAroundOffset)
void drawGrid(const QRect &updateRect)
void reportFailedShaderCompilation(const QString &context)
void setDisplayConfig(const KisDisplayConfig &config)
WrapAroundAxis wrapAroundViewingModeAxis() const
KisOpenGLCanvasRenderer(CanvasBridge *canvasBridge, KisImageWSP image, const KisDisplayConfig &displayConfig, QSharedPointer< KisDisplayFilter > displayFilter)
void setWrapAroundViewingModeAxis(WrapAroundAxis value)
void drawCheckers(const QRect &updateRect)
void finishResizingImage(qint32 w, qint32 h)
void paintToolOutline(const KisOptimizedBrushOutline &path, const QRect &viewportUpdateRect, const int thickness=1)
void renderCanvasGL(const QRect &updateRect)
KisCoordinatesConverter * coordinatesConverter() const
void notifyImageColorSpaceChanged(const KoColorSpace *cs)
bool setInternalColorManagementActive(bool value)
int getTextureBufferIndexCR(int col, int row)
KisOpenGLUpdateInfoSP updateCache(const QRect &rect, KisImageSP srcImage)
void generateCheckerTexture(const QImage &checkImage)
const KoColorProfile * monitorProfile()
void initGL(QOpenGLFunctions *f)
void slotImageSizeChanged(qint32 w, qint32 h)
static const int BACKGROUND_TEXTURE_CHECK_SIZE
void updateConfig(bool useBuffer, int NumMipmapLevels)
void recalculateCache(KisUpdateInfoSP info, bool blockMipmapRegeneration)
bool setImageColorSpace(const KoColorSpace *cs)
static KisOpenGLImageTexturesSP createImageTextures(KisImageWSP image, const KoColorProfile *monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags)
void setChannelFlags(const QBitArray &channelFlags)
KisTextureTile * getTextureTileCR(int col, int row)
KisOpenGLUpdateInfoBuilder & updateInfoBuilder()
void setMonitorProfile(const KoColorProfile *monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags)
void setProofingConfig(KisProofingConfigurationSP)
KisShaderProgram * loadSolidColorShader()
KisShaderProgram * loadCheckerShader()
KisShaderProgram * loadDisplayShader(QSharedPointer< KisDisplayFilter > displayFilter, bool useHiQualityFiltering)
static bool useFBOForToolOutlineRendering()
supportsRenderToFBO
@ NearestFilterMode
Definition kis_opengl.h:34
@ HighQualityFiltering
Definition kis_opengl.h:37
@ BilinearFilterMode
Definition kis_opengl.h:35
@ TrilinearFilterMode
Definition kis_opengl.h:36
static void initializeContext(QOpenGLContext *ctx)
Initialize shared OpenGL context.
static bool supportsVAO()
int location(Uniform uniform)
QRect tileRectInImagePixels()
QRectF tileRectInTexturePixels()
int bindToActiveTexture(bool blockMipmapRegeneration)
QPointer< KoCanvasResourceProvider > resourceManager
virtual KoID colorDepthId() const =0
virtual void normalisedChannelsValue(const quint8 *pixel, QVector< float > &channels) const =0
void convertTo(const KoColorSpace *cs, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags)
Definition KoColor.cpp:136
quint8 * data()
Definition KoColor.h:144
const KoColorSpace * colorSpace() const
return the current colorSpace
Definition KoColor.h:82
QString id() const
Definition KoID.cpp:63
#define KIS_SAFE_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:128
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130
#define SCALE_LESS_THAN(scX, scY, value)
#define SCALE_MORE_OR_EQUAL_TO(scX, scY, value)
#define bounds(x, a, b)
#define warnUI
Definition kis_debug.h:94
T kisGrowRect(const T &rect, U offset)
Definition kis_global.h:186
#define PROGRAM_TEXCOORD_ATTRIBUTE
#define PROGRAM_VERTEX_ATTRIBUTE
@ ModelViewProjection
auto maxDimension(Size size) -> decltype(size.width())
T wrapValue(T value, T wrapBounds)
Point normalize(const Point &a)
qreal norm(const T &a)
PointTypeTraits< T >::value_type dotProduct(const T &a, const T &b)
void rectToTexCoords(QVector2D *texCoords, const QRectF &rc)
void rectToVertices(QVector3D *vertices, const QRectF &rc)
void allocate(int numBuffers, int bufferSize)
KisOpenGLBufferCircularStorage checkersVertexBuffer
QScopedPointer< QOpenGLFramebufferObject > canvasFBO
int yToRowWithWrapCompensation(int y, const QRect &imageRect)
int xToColWithWrapCompensation(int x, const QRect &imageRect)
KisOpenGLBufferCircularStorage checkersTextureVertexBuffer
QSharedPointer< KisDisplayFilter > displayFilter
const KoColorSpace * destinationColorSpace() const
const KoColorSpace * colorSpace(const QString &colorModelId, const QString &colorDepthId, const KoColorProfile *profile)
static KoColorSpaceRegistry * instance()