]> git.sesse.net Git - kdenlive/blob - src/beziercurve/beziersplineeditor.cpp
Bezier spline editor: Fix inaccurate placement of handles
[kdenlive] / src / beziercurve / beziersplineeditor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Till Theato (root@ttill.de)                     *
3  *   This file is part of Kdenlive (www.kdenlive.org).                     *
4  *                                                                         *
5  *   Kdenlive is free software: you can redistribute it and/or modify      *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation, either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   Kdenlive is distributed in the hope that it will be useful,           *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with Kdenlive.  If not, see <http://www.gnu.org/licenses/>.     *
17  ***************************************************************************/
18
19 #include "beziersplineeditor.h"
20
21 #include <QPainter>
22 #include <QMouseEvent>
23
24
25 BezierSplineEditor::BezierSplineEditor(QWidget* parent) :
26         QWidget(parent),
27         m_mode(ModeNormal),
28         m_zoomLevel(0),
29         m_gridLines(3),
30         m_showAllHandles(true),
31         m_pixmapCache(NULL),
32         m_pixmapIsDirty(true),
33         m_currentPointIndex(-1)
34 {
35     setMouseTracking(true);
36     setAutoFillBackground(false);
37     setAttribute(Qt::WA_OpaquePaintEvent);
38     setMinimumSize(150, 150);
39     setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
40 }
41
42 BezierSplineEditor::~BezierSplineEditor()
43 {
44     if (m_pixmapCache)
45         delete m_pixmapCache;
46 }
47
48 CubicBezierSpline BezierSplineEditor::spline()
49 {
50     return m_spline;
51 }
52
53 void BezierSplineEditor::setSpline(const CubicBezierSpline& spline)
54 {
55     int precision = m_spline.getPrecision();
56     m_spline = spline;
57     m_spline.setPrecision(precision);
58     m_currentPointIndex = -1;
59     m_mode = ModeNormal;
60     emit currentPoint(BPoint());
61     emit modified();
62     update();
63 }
64
65 BPoint BezierSplineEditor::getCurrentPoint()
66 {
67     if (m_currentPointIndex >= 0)
68         return m_spline.points()[m_currentPointIndex];
69     else
70         return BPoint();
71 }
72
73 void BezierSplineEditor::updateCurrentPoint(const BPoint& p)
74 {
75     if (m_currentPointIndex >= 0) {
76         m_spline.setPoint(m_currentPointIndex, p);
77         // during validation the point might have changed
78         emit currentPoint(m_spline.points()[m_currentPointIndex]);
79         emit modified();
80         update();
81     }
82 }
83
84 void BezierSplineEditor::setPixmap(const QPixmap& pixmap)
85 {
86     m_pixmap = pixmap;
87     m_pixmapIsDirty = true;
88     update();
89 }
90
91 void BezierSplineEditor::slotZoomIn()
92 {
93     m_zoomLevel = qMax(m_zoomLevel-1, 0);
94     m_pixmapIsDirty = true;
95     update();
96 }
97
98 void BezierSplineEditor::slotZoomOut()
99 {
100     m_zoomLevel = qMin(m_zoomLevel+1, 3);
101     m_pixmapIsDirty = true;
102     update();
103 }
104
105 void BezierSplineEditor::setShowAllHandles(bool show)
106 {
107     m_showAllHandles = show;
108     update();
109 }
110
111 int BezierSplineEditor::gridLines()
112 {
113     return m_gridLines;
114 }
115
116 void BezierSplineEditor::setGridLines(int lines)
117 {
118     m_gridLines = qBound(0, lines, 8);
119     update();
120 }
121
122 void BezierSplineEditor::paintEvent(QPaintEvent* event)
123 {
124     Q_UNUSED(event);
125
126     QPainter p(this);
127
128     int wWidth = width() - 1;
129     int wHeight = height() - 1;
130     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
131     wWidth -= 2 * offset;
132     wHeight -= 2 * offset;
133
134     p.translate(offset, offset);
135
136     /*
137      * Background
138      */
139     p.fillRect(rect().translated(-offset, -offset), palette().background());
140     if (!m_pixmap.isNull()) {
141         if (m_pixmapIsDirty || !m_pixmapCache) {
142             if (m_pixmapCache)
143                 delete m_pixmapCache;
144             m_pixmapCache = new QPixmap(wWidth + 1, wHeight + 1);
145             QPainter cachePainter(m_pixmapCache);
146
147             cachePainter.scale(1.0*(wWidth+1) / m_pixmap.width(), 1.0*(wHeight+1) / m_pixmap.height());
148             cachePainter.drawPixmap(0, 0, m_pixmap);
149             m_pixmapIsDirty = false;
150         }
151         p.drawPixmap(0, 0, *m_pixmapCache);
152     }
153
154
155     p.setPen(QPen(Qt::gray, 1, Qt::SolidLine));
156
157     /*
158      * Borders
159      */
160     if (m_zoomLevel != 0) {
161         p.drawRect(0, 0, wWidth, wHeight);
162     }
163
164     /*
165      * Grid
166      */
167     if (m_gridLines != 0) {
168         double stepH = wWidth / (double)(m_gridLines + 1);
169         double stepV = wHeight / (double)(m_gridLines + 1);
170         for (int i = 1; i <= m_gridLines; ++i) {
171             p.drawLine(QLineF(i * stepH, 0, i * stepH, wHeight));
172             p.drawLine(QLineF(0, i * stepV, wWidth, i * stepV));
173         }
174     }
175
176     p.setRenderHint(QPainter::Antialiasing);
177
178     /*
179      * Standard line
180      */
181     p.drawLine(QLineF(0, wHeight, wWidth, 0));
182
183     /*
184      * Spline
185      */
186     double prevY = wHeight - m_spline.value(0.) * wHeight;
187     double prevX = 0.;
188     double curY;
189     double normalizedX = -1;
190     int x;
191     
192     p.setPen(QPen(Qt::black, 1, Qt::SolidLine));
193     for (x = 0 ; x < wWidth ; ++x) {
194         normalizedX = x / (double)wWidth;
195         curY = wHeight - m_spline.value(normalizedX, true) * wHeight;
196
197         /*
198          * Keep in mind that QLineF rounds doubles
199          * to ints mathematically, not just rounds down
200          * like in C
201          */
202         p.drawLine(QLineF(prevX, prevY, x, curY));
203         prevX = x;
204         prevY = curY;
205     }
206     p.drawLine(QLineF(prevX, prevY ,
207                       x, wHeight - m_spline.value(1.0, true) * wHeight));
208
209     /*
210      * Points + Handles
211      */
212     int max = m_spline.points().count() - 1;
213     p.setPen(QPen(Qt::red, 1, Qt::SolidLine));
214     BPoint point;
215
216     QPolygonF handle = QPolygonF() << QPointF(0, -3) << QPointF(3, 0) << QPointF(0, 3) << QPointF(-3, 0);
217 #if QT_VERSION < 0x040600
218     QPolygonF tmp;
219 #endif
220
221     for (int i = 0; i <= max; ++i) {
222         point = m_spline.points().at(i);
223         if (i == m_currentPointIndex) {
224             // selected point: fill p and handles
225             p.setBrush(QBrush(QColor(Qt::red), Qt::SolidPattern));
226             // connect p and handles with lines
227             if (i != 0)
228                 p.drawLine(QLineF(point.h1.x() * wWidth, wHeight - point.h1.y() * wHeight, point.p.x() * wWidth, wHeight - point.p.y() * wHeight));
229             if (i != max)
230                 p.drawLine(QLineF(point.p.x() * wWidth, wHeight - point.p.y() * wHeight, point.h2.x() * wWidth, wHeight - point.h2.y() * wHeight));
231         }
232
233         p.drawEllipse(QRectF(point.p.x() * wWidth - 3,
234                              wHeight - 3 - point.p.y() * wHeight, 6, 6));
235         if (i != 0 && (i == m_currentPointIndex || m_showAllHandles)) {
236 #if QT_VERSION >= 0x040600
237             p.drawConvexPolygon(handle.translated(point.h1.x() * wWidth, wHeight - point.h1.y() * wHeight));
238 #else
239             tmp = handle;
240             tmp.translate(point.h1.x() * wWidth, wHeight - point.h1.y() * wHeight);
241             p.drawConvexPolygon(tmp);
242 #endif
243         }
244         if (i != max && (i == m_currentPointIndex || m_showAllHandles)) {
245 #if QT_VERSION >= 0x040600
246             p.drawConvexPolygon(handle.translated(point.h2.x() * wWidth, wHeight - point.h2.y() * wHeight));
247 #else
248             tmp = handle;
249             tmp.translate(point.h2.x() * wWidth, wHeight - point.h2.y() * wHeight);
250             p.drawConvexPolygon(tmp);
251 #endif
252         }
253
254         if ( i == m_currentPointIndex)
255             p.setBrush(QBrush(Qt::NoBrush));
256     }
257 }
258
259 void BezierSplineEditor::resizeEvent(QResizeEvent* event)
260 {
261     m_spline.setPrecision(width() > height() ? width() : height());
262     m_pixmapIsDirty = true;
263     QWidget::resizeEvent(event);
264 }
265
266 void BezierSplineEditor::mousePressEvent(QMouseEvent* event)
267 {
268     int wWidth = width() - 1;
269     int wHeight = height() - 1;
270     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
271     wWidth -= 2 * offset;
272     wHeight -= 2 * offset;
273
274     double x = (event->pos().x() - offset) / (double)(wWidth);
275     double y = 1.0 - (event->pos().y() - offset) / (double)(wHeight);
276
277     point_types selectedPoint;
278     int closestPointIndex = nearestPointInRange(QPointF(x, y), wWidth, wHeight, &selectedPoint);
279
280     if (event->button() == Qt::RightButton && closestPointIndex > 0 && closestPointIndex < m_spline.points().count() - 1 && selectedPoint == PTypeP) {
281         m_spline.removePoint(closestPointIndex);
282         setCursor(Qt::ArrowCursor);
283         m_mode = ModeNormal;
284         if (closestPointIndex < m_currentPointIndex)
285             --m_currentPointIndex;
286         update();
287         if (m_currentPointIndex >= 0)
288             emit currentPoint(m_spline.points()[m_currentPointIndex]);
289         else
290             emit currentPoint(BPoint());
291         emit modified();
292         return;
293     } else if (event->button() != Qt::LeftButton) {
294         return;
295     }
296
297     if (closestPointIndex < 0) {
298         m_currentPointIndex = m_spline.addPoint(BPoint(QPointF(x-0.05, y-0.05),
299                                                        QPointF(x, y),
300                                                        QPointF(x+0.05, y+0.05)));
301         m_currentPointType = PTypeP;
302     } else {
303         m_currentPointIndex = closestPointIndex;
304         m_currentPointType = selectedPoint;
305     }
306
307     BPoint point = m_spline.points()[m_currentPointIndex];
308
309     m_grabPOriginal = point;
310     if (m_currentPointIndex > 0)
311         m_grabPPrevious = m_spline.points()[m_currentPointIndex - 1];
312     if (m_currentPointIndex < m_spline.points().count() - 1)
313         m_grabPNext = m_spline.points()[m_currentPointIndex + 1];
314     m_grabOffsetX = point[(int)m_currentPointType].x() - x;
315     m_grabOffsetY = point[(int)m_currentPointType].y() - y;
316
317     point[(int)m_currentPointType] = QPointF(x + m_grabOffsetX, y + m_grabOffsetY);
318
319     m_spline.setPoint(m_currentPointIndex, point);
320
321     m_mode = ModeDrag;
322
323     emit currentPoint(point);
324     update();
325 }
326
327 void BezierSplineEditor::mouseReleaseEvent(QMouseEvent* event)
328 {
329     if (event->button() != Qt::LeftButton)
330         return;
331
332     setCursor(Qt::ArrowCursor);
333     m_mode = ModeNormal;
334
335     emit modified();
336 }
337
338 void BezierSplineEditor::mouseMoveEvent(QMouseEvent* event)
339 {
340     int wWidth = width() - 1;
341     int wHeight = height() - 1;
342     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
343     wWidth -= 2 * offset;
344     wHeight -= 2 * offset;
345
346     double x = (event->pos().x() - offset) / (double)(wWidth);
347     double y = 1.0 - (event->pos().y() - offset) / (double)(wHeight);
348     
349     if (m_mode == ModeNormal) {
350         // If no point is selected set the the cursor shape if on top
351         point_types type;
352         int nearestPointIndex = nearestPointInRange(QPointF(x, y), wWidth, wHeight, &type);
353
354         if (nearestPointIndex < 0)
355             setCursor(Qt::ArrowCursor);
356         else
357             setCursor(Qt::CrossCursor);
358     } else {
359         // Else, drag the selected point
360         setCursor(Qt::CrossCursor);
361
362         x += m_grabOffsetX;
363         y += m_grabOffsetY;
364
365         double leftX = 0.;
366         double rightX = 1.;
367         BPoint point = m_spline.points()[m_currentPointIndex];
368         switch (m_currentPointType) {
369         case PTypeH1:
370             rightX = point.p.x();
371             if (m_currentPointIndex == 0)
372                 leftX = -4;
373             else
374                 leftX = m_spline.points()[m_currentPointIndex - 1].p.x();
375
376             x = qBound(leftX, x, rightX);
377             point.setH1(QPointF(x, y));
378             break;
379
380         case PTypeP:
381             if (m_currentPointIndex == 0)
382                 rightX = 0.0;
383             else if (m_currentPointIndex == m_spline.points().count() - 1)
384                 leftX = 1.0;
385
386             x = qBound(leftX, x, rightX);
387             y = qBound(0., y, 1.);
388
389             // handles might have changed because we neared another point
390             // try to restore
391             point.h1 = m_grabPOriginal.h1;
392             point.h2 = m_grabPOriginal.h2;
393             // and move by same offset
394             // (using update handle in point.setP won't work because the offset between new and old point is very small)
395             point.h1 += QPointF(x, y) - m_grabPOriginal.p;
396             point.h2 += QPointF(x, y) - m_grabPOriginal.p;
397
398             point.setP(QPointF(x, y), false);
399             break;
400
401         case PTypeH2:
402             leftX = point.p.x();
403             if (m_currentPointIndex == m_spline.points().count() - 1)
404                 rightX = 5;
405             else
406                 rightX = m_spline.points()[m_currentPointIndex + 1].p.x();
407
408             x = qBound(leftX, x, rightX);
409             point.setH2(QPointF(x, y));
410         };
411
412         int index = m_currentPointIndex;
413         m_currentPointIndex = m_spline.setPoint(m_currentPointIndex, point);
414
415         if (m_currentPointType == PTypeP) {
416             // we might have changed the handles of other points
417             // try to restore
418             if (index == m_currentPointIndex) {
419                 if (m_currentPointIndex > 0)
420                     m_spline.setPoint(m_currentPointIndex - 1, m_grabPPrevious);
421                 if (m_currentPointIndex < m_spline.points().count() -1)
422                     m_spline.setPoint(m_currentPointIndex + 1, m_grabPNext);
423             } else {
424                 if (m_currentPointIndex < index) {
425                     m_spline.setPoint(index, m_grabPPrevious);
426                     m_grabPNext = m_grabPPrevious;
427                     if (m_currentPointIndex > 0)
428                         m_grabPPrevious = m_spline.points()[m_currentPointIndex - 1];
429                 } else {
430                     m_spline.setPoint(index, m_grabPNext);
431                     m_grabPPrevious = m_grabPNext;
432                     if (m_currentPointIndex < m_spline.points().count() - 1)
433                         m_grabPNext = m_spline.points()[m_currentPointIndex + 1];
434                 }
435             }
436         }
437
438         emit currentPoint(point);
439         update();
440     }
441 }
442
443 void BezierSplineEditor::leaveEvent(QEvent* event)
444 {
445     QWidget::leaveEvent(event);
446 }
447
448 int BezierSplineEditor::nearestPointInRange(QPointF p, int wWidth, int wHeight, BezierSplineEditor::point_types* sel)
449 {
450     double nearestDistanceSquared = 1000;
451     point_types selectedPoint;
452     int nearestIndex = -1;
453     int i = 0;
454
455     double distanceSquared;
456     // find out distance using the Pythagorean theorem
457     foreach(const BPoint & point, m_spline.points()) {
458         for (int j = 0; j < 3; ++j) {
459             distanceSquared = pow(point[j].x() - p.x(), 2) + pow(point[j].y() - p.y(), 2);
460             if (distanceSquared < nearestDistanceSquared) {
461                 nearestIndex = i;
462                 nearestDistanceSquared = distanceSquared;
463                 selectedPoint = (point_types)j;
464             }
465         }
466         ++i;
467     }
468
469     if (nearestIndex >= 0 && (nearestIndex == m_currentPointIndex || selectedPoint == PTypeP || m_showAllHandles)) {
470         // a point was found and it is not a hidden handle
471         BPoint point = m_spline.points()[nearestIndex];
472         if (qAbs(p.x() - point[(int)selectedPoint].x()) * wWidth < 5 && qAbs(p.y() - point[(int)selectedPoint].y()) * wHeight < 5) {
473             *sel = selectedPoint;
474             return nearestIndex;
475         }
476     }
477
478     return -1;
479 }
480
481 #include "beziersplineeditor.moc"