src/glRenderer.cc

changeset 655
b376645315ab
child 662
2f1bd9112408
child 706
d79083b9f74d
equal deleted inserted replaced
654:a74f2ff353b8 655:b376645315ab
1 /*
2 * LDForge: LDraw parts authoring CAD
3 * Copyright (C) 2013, 2014 Santeri Piippo
4 *
5 * This program 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 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <QGLWidget>
20 #include <QWheelEvent>
21 #include <QMouseEvent>
22 #include <QContextMenuEvent>
23 #include <QInputDialog>
24 #include <QToolTip>
25 #include <QTimer>
26 #include <GL/glu.h>
27
28 #include "main.h"
29 #include "configuration.h"
30 #include "ldDocument.h"
31 #include "glRenderer.h"
32 #include "colors.h"
33 #include "mainWindow.h"
34 #include "miscallenous.h"
35 #include "editHistory.h"
36 #include "dialogs.h"
37 #include "addObjectDialog.h"
38 #include "messageLog.h"
39 #include "primitives.h"
40 #include "misc/ringFinder.h"
41
42 static const LDFixedCameraInfo g_FixedCameras[6] =
43 {
44 {{ 1, 0, 0 }, X, Z, false, false },
45 {{ 0, 0, 0 }, X, Y, false, true },
46 {{ 0, 1, 0 }, Z, Y, true, true },
47 {{ -1, 0, 0 }, X, Z, false, true },
48 {{ 0, 0, 0 }, X, Y, true, true },
49 {{ 0, -1, 0 }, Z, Y, false, true },
50 };
51
52 // Matrix templates for circle drawing. 2 is substituted with
53 // the scale value, 1 is inverted to -1 if needed.
54 static const Matrix g_circleDrawMatrixTemplates[3] =
55 {
56 { 2, 0, 0, 0, 1, 0, 0, 0, 2 },
57 { 2, 0, 0, 0, 0, 2, 0, 1, 0 },
58 { 0, 1, 0, 2, 0, 0, 0, 0, 2 },
59 };
60
61 cfg (String, gl_bgcolor, "#FFFFFF")
62 cfg (String, gl_maincolor, "#A0A0A0")
63 cfg (Float, gl_maincolor_alpha, 1.0)
64 cfg (String, gl_selectcolor, "#0080FF")
65 cfg (Int, gl_linethickness, 2)
66 cfg (Bool, gl_colorbfc, false)
67 cfg (Int, gl_camera, GLRenderer::EFreeCamera)
68 cfg (Bool, gl_blackedges, false)
69 cfg (Bool, gl_axes, false)
70 cfg (Bool, gl_wireframe, false)
71 cfg (Bool, gl_logostuds, false)
72 cfg (Bool, gl_aa, true)
73 cfg (Bool, gl_linelengths, true)
74 cfg (Bool, gl_drawangles, false)
75
76 // argh
77 const char* g_CameraNames[7] =
78 {
79 QT_TRANSLATE_NOOP ("GLRenderer", "Top"),
80 QT_TRANSLATE_NOOP ("GLRenderer", "Front"),
81 QT_TRANSLATE_NOOP ("GLRenderer", "Left"),
82 QT_TRANSLATE_NOOP ("GLRenderer", "Bottom"),
83 QT_TRANSLATE_NOOP ("GLRenderer", "Back"),
84 QT_TRANSLATE_NOOP ("GLRenderer", "Right"),
85 QT_TRANSLATE_NOOP ("GLRenderer", "Free")
86 };
87
88 const GL::EFixedCamera g_Cameras[7] =
89 {
90 GL::ETopCamera,
91 GL::EFrontCamera,
92 GL::ELeftCamera,
93 GL::EBottomCamera,
94 GL::EBackCamera,
95 GL::ERightCamera,
96 GL::EFreeCamera
97 };
98
99 // Definitions for visual axes, drawn on the screen
100 const struct LDGLAxis
101 {
102 const QColor col;
103 const Vertex vert;
104 } g_GLAxes[3] =
105 {
106 { QColor (255, 0, 0), Vertex (10000, 0, 0) }, // X
107 { QColor (80, 192, 0), Vertex (0, 10000, 0) }, // Y
108 { QColor (0, 160, 192), Vertex (0, 0, 10000) }, // Z
109 };
110
111 static bool g_glInvert = false;
112 static QList<int> g_warnedColors;
113
114 // =============================================================================
115 //
116 GLRenderer::GLRenderer (QWidget* parent) : QGLWidget (parent)
117 {
118 m_isPicking = m_rangepick = false;
119 m_camera = (GL::EFixedCamera) gl_camera;
120 m_drawToolTip = false;
121 m_editMode = ESelectMode;
122 m_rectdraw = false;
123 m_panning = false;
124 setDocument (null);
125 setDrawOnly (false);
126 setMessageLog (null);
127 m_width = m_height = -1;
128 m_hoverpos = g_origin;
129
130 m_toolTipTimer = new QTimer (this);
131 m_toolTipTimer->setSingleShot (true);
132 connect (m_toolTipTimer, SIGNAL (timeout()), this, SLOT (slot_toolTipTimer()));
133
134 m_thickBorderPen = QPen (QColor (0, 0, 0, 208), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
135 m_thinBorderPen = m_thickBorderPen;
136 m_thinBorderPen.setWidth (1);
137
138 // Init camera icons
139 for (const GL::EFixedCamera cam : g_Cameras)
140 {
141 QString iconname = format ("camera-%1", tr (g_CameraNames[cam]).toLower());
142
143 CameraIcon* info = &m_cameraIcons[cam];
144 info->img = new QPixmap (getIcon (iconname));
145 info->cam = cam;
146 }
147
148 calcCameraIcons();
149 }
150
151 // =============================================================================
152 //
153 GLRenderer::~GLRenderer()
154 {
155 for (int i = 0; i < 6; ++i)
156 delete currentDocumentData().overlays[i].img;
157
158 for (CameraIcon& info : m_cameraIcons)
159 delete info.img;
160 }
161
162 // =============================================================================
163 // Calculates the "hitboxes" of the camera icons so that we can tell when the
164 // cursor is pointing at the camera icon.
165 //
166 void GLRenderer::calcCameraIcons()
167 {
168 int i = 0;
169
170 for (CameraIcon& info : m_cameraIcons)
171 {
172 // MATH
173 const long x1 = (m_width - (info.cam != EFreeCamera ? 48 : 16)) + ((i % 3) * 16) - 1,
174 y1 = ((i / 3) * 16) + 1;
175
176 info.srcRect = QRect (0, 0, 16, 16);
177 info.destRect = QRect (x1, y1, 16, 16);
178 info.selRect = QRect (
179 info.destRect.x(),
180 info.destRect.y(),
181 info.destRect.width() + 1,
182 info.destRect.height() + 1
183 );
184
185 ++i;
186 }
187 }
188
189 // =============================================================================
190 //
191 void GLRenderer::initGLData()
192 {
193 glEnable (GL_BLEND);
194 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
195 glEnable (GL_POLYGON_OFFSET_FILL);
196 glPolygonOffset (1.0f, 1.0f);
197
198 glEnable (GL_DEPTH_TEST);
199 glShadeModel (GL_SMOOTH);
200 glEnable (GL_MULTISAMPLE);
201
202 if (gl_aa)
203 {
204 glEnable (GL_LINE_SMOOTH);
205 glEnable (GL_POLYGON_SMOOTH);
206 glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
207 glHint (GL_POLYGON_SMOOTH_HINT, GL_NICEST);
208 } else
209 {
210 glDisable (GL_LINE_SMOOTH);
211 glDisable (GL_POLYGON_SMOOTH);
212 }
213 }
214
215 // =============================================================================
216 //
217 void GLRenderer::resetAngles()
218 {
219 rot (X) = 30.0f;
220 rot (Y) = 325.f;
221 pan (X) = pan (Y) = rot (Z) = 0.0f;
222 zoomToFit();
223 }
224
225 // =============================================================================
226 //
227 void GLRenderer::resetAllAngles()
228 {
229 EFixedCamera oldcam = camera();
230
231 for (int i = 0; i < 7; ++i)
232 {
233 setCamera ((EFixedCamera) i);
234 resetAngles();
235 }
236
237 setCamera (oldcam);
238 }
239
240 // =============================================================================
241 //
242 void GLRenderer::initializeGL()
243 {
244 setBackground();
245
246 glLineWidth (gl_linethickness);
247
248 setAutoFillBackground (false);
249 setMouseTracking (true);
250 setFocusPolicy (Qt::WheelFocus);
251 compileAllObjects();
252 }
253
254 // =============================================================================
255 //
256 QColor GLRenderer::getMainColor()
257 {
258 QColor col (gl_maincolor);
259
260 if (!col.isValid())
261 return QColor (0, 0, 0);
262
263 col.setAlpha (gl_maincolor_alpha * 255.f);
264 return col;
265 }
266
267 // =============================================================================
268 //
269 void GLRenderer::setBackground()
270 {
271 QColor col (gl_bgcolor);
272
273 if (!col.isValid())
274 return;
275
276 col.setAlpha (255);
277
278 m_darkbg = luma (col) < 80;
279 m_bgcolor = col;
280 qglClearColor (col);
281 }
282
283 // =============================================================================
284 //
285 void GLRenderer::setObjectColor (LDObject* obj, const ListType list)
286 {
287 QColor qcol;
288
289 if (!obj->isColored())
290 return;
291
292 if (list == GL::PickList)
293 {
294 // Make the color by the object's ID if we're picking, so we can make the
295 // ID again from the color we get from the picking results. Be sure to use
296 // the top level parent's index since we want a subfile's children point
297 // to the subfile itself.
298 long i = obj->topLevelParent()->id();
299
300 // Calculate a color based from this index. This method caters for
301 // 16777216 objects. I don't think that'll be exceeded anytime soon. :)
302 // ATM biggest is 53588.dat with 12600 lines.
303 double r = (i / 0x10000) % 0x100,
304 g = (i / 0x100) % 0x100,
305 b = i % 0x100;
306
307 qglColor (QColor (r, g, b));
308 return;
309 }
310
311 if ((list == BFCFrontList || list == BFCBackList) &&
312 obj->type() != LDObject::ELine &&
313 obj->type() != LDObject::ECondLine)
314 {
315 if (list == GL::BFCFrontList)
316 qcol = QColor (40, 192, 0);
317 else
318 qcol = QColor (224, 0, 0);
319 }
320 else
321 {
322 if (obj->color() == maincolor)
323 qcol = getMainColor();
324 else
325 {
326 LDColor* col = ::getColor (obj->color());
327
328 if (col)
329 qcol = col->faceColor;
330 }
331
332 if (obj->color() == edgecolor)
333 {
334 LDColor* col;
335
336 if (!gl_blackedges && obj->parent() && (col = ::getColor (obj->parent()->color())))
337 qcol = col->edgeColor;
338 else
339 qcol = (m_darkbg == false) ? Qt::black : Qt::white;
340 }
341
342 if (qcol.isValid() == false)
343 {
344 // The color was unknown. Use main color to make the object at least
345 // not appear pitch-black.
346 if (obj->color() != edgecolor)
347 qcol = getMainColor();
348
349 // Warn about the unknown colors, but only once.
350 for (int i : g_warnedColors)
351 if (obj->color() == i)
352 return;
353
354 print ("%1: Unknown color %2!\n", __func__, obj->color());
355 g_warnedColors << obj->color();
356 return;
357 }
358 }
359
360 int r = qcol.red(),
361 g = qcol.green(),
362 b = qcol.blue(),
363 a = qcol.alpha();
364
365 if (obj->topLevelParent()->isSelected())
366 {
367 // Brighten it up for the select list.
368 QColor selcolor (gl_selectcolor);
369 r = (r + selcolor.red()) / 2;
370 g = (g + selcolor.green()) / 2;
371 b = (b + selcolor.blue()) / 2;
372 }
373
374 glColor4f (
375 ((double) r) / 255.0f,
376 ((double) g) / 255.0f,
377 ((double) b) / 255.0f,
378 ((double) a) / 255.0f);
379 }
380
381 // =============================================================================
382 //
383 void GLRenderer::refresh()
384 {
385 update();
386 swapBuffers();
387 }
388
389 // =============================================================================
390 //
391 void GLRenderer::hardRefresh()
392 {
393 compileAllObjects();
394 refresh();
395
396 glLineWidth (gl_linethickness);
397 }
398
399 // =============================================================================
400 //
401 void GLRenderer::resizeGL (int w, int h)
402 {
403 m_width = w;
404 m_height = h;
405
406 calcCameraIcons();
407
408 glViewport (0, 0, w, h);
409 glMatrixMode (GL_PROJECTION);
410 glLoadIdentity();
411 gluPerspective (45.0f, (double) w / (double) h, 1.0f, 10000.0f);
412 glMatrixMode (GL_MODELVIEW);
413 }
414
415 // =============================================================================
416 //
417 void GLRenderer::drawGLScene()
418 {
419 if (document() == null)
420 return;
421
422 if (gl_wireframe && !isPicking())
423 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
424
425 glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
426 glEnable (GL_DEPTH_TEST);
427
428 if (m_camera != EFreeCamera)
429 {
430 glMatrixMode (GL_PROJECTION);
431 glPushMatrix();
432
433 glLoadIdentity();
434 glOrtho (-m_virtWidth, m_virtWidth, -m_virtHeight, m_virtHeight, -100.0f, 100.0f);
435 glTranslatef (pan (X), pan (Y), 0.0f);
436
437 if (m_camera != EFrontCamera && m_camera != EBackCamera)
438 {
439 glRotatef (90.0f, g_FixedCameras[camera()].glrotate[0],
440 g_FixedCameras[camera()].glrotate[1],
441 g_FixedCameras[camera()].glrotate[2]);
442 }
443
444 // Back camera needs to be handled differently
445 if (m_camera == GLRenderer::EBackCamera)
446 {
447 glRotatef (180.0f, 1.0f, 0.0f, 0.0f);
448 glRotatef (180.0f, 0.0f, 0.0f, 1.0f);
449 }
450 }
451 else
452 {
453 glMatrixMode (GL_MODELVIEW);
454 glPushMatrix();
455 glLoadIdentity();
456
457 glTranslatef (0.0f, 0.0f, -2.0f);
458 glTranslatef (pan (X), pan (Y), -zoom());
459 glRotatef (rot (X), 1.0f, 0.0f, 0.0f);
460 glRotatef (rot (Y), 0.0f, 1.0f, 0.0f);
461 glRotatef (rot (Z), 0.0f, 0.0f, 1.0f);
462 }
463
464 const GL::ListType list = (!isDrawOnly() && isPicking()) ? PickList : NormalList;
465
466 if (gl_colorbfc && !isPicking() && !isDrawOnly())
467 {
468 glEnable (GL_CULL_FACE);
469
470 for (LDObject* obj : document()->objects())
471 {
472 if (obj->isHidden())
473 continue;
474
475 glCullFace (GL_BACK);
476 glCallList (obj->glLists[BFCFrontList]);
477
478 glCullFace (GL_FRONT);
479 glCallList (obj->glLists[BFCBackList]);
480 }
481
482 glDisable (GL_CULL_FACE);
483 }
484 else
485 {
486 for (LDObject* obj : document()->objects())
487 {
488 if (obj->isHidden())
489 continue;
490
491 glCallList (obj->glLists[list]);
492 }
493 }
494
495 if (gl_axes && !isPicking() && !isDrawOnly())
496 glCallList (m_axeslist);
497
498 glPopMatrix();
499 glMatrixMode (GL_MODELVIEW);
500 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
501 }
502
503 // =============================================================================
504 //
505 // This converts a 2D point on the screen to a 3D point in the model. If 'snap'
506 // is true, the 3D point will snap to the current grid.
507 //
508 Vertex GLRenderer::coordconv2_3 (const QPoint& pos2d, bool snap) const
509 {
510 assert (camera() != EFreeCamera);
511
512 Vertex pos3d;
513 const LDFixedCameraInfo* cam = &g_FixedCameras[m_camera];
514 const Axis axisX = cam->axisX;
515 const Axis axisY = cam->axisY;
516 const int negXFac = cam->negX ? -1 : 1,
517 negYFac = cam->negY ? -1 : 1;
518
519 // Calculate cx and cy - these are the LDraw unit coords the cursor is at.
520 double cx = (-m_virtWidth + ((2 * pos2d.x() * m_virtWidth) / m_width) - pan (X));
521 double cy = (m_virtHeight - ((2 * pos2d.y() * m_virtHeight) / m_height) - pan (Y));
522
523 if (snap)
524 {
525 cx = Grid::snap (cx, (Grid::Config) axisX);
526 cy = Grid::snap (cy, (Grid::Config) axisY);
527 }
528
529 cx *= negXFac;
530 cy *= negYFac;
531
532 roundToDecimals (cx, 4);
533 roundToDecimals (cy, 4);
534
535 // Create the vertex from the coordinates
536 pos3d[axisX] = cx;
537 pos3d[axisY] = cy;
538 pos3d[3 - axisX - axisY] = getDepthValue();
539 return pos3d;
540 }
541
542 // =============================================================================
543 //
544 // Inverse operation for the above - convert a 3D position to a 2D screen
545 // position. Don't ask me how this code manages to work, I don't even know.
546 //
547 QPoint GLRenderer::coordconv3_2 (const Vertex& pos3d) const
548 {
549 GLfloat m[16];
550 const LDFixedCameraInfo* cam = &g_FixedCameras[m_camera];
551 const Axis axisX = cam->axisX;
552 const Axis axisY = cam->axisY;
553 const int negXFac = cam->negX ? -1 : 1,
554 negYFac = cam->negY ? -1 : 1;
555
556 glGetFloatv (GL_MODELVIEW_MATRIX, m);
557
558 const double x = pos3d.x();
559 const double y = pos3d.y();
560 const double z = pos3d.z();
561
562 Vertex transformed;
563 transformed[X] = (m[0] * x) + (m[1] * y) + (m[2] * z) + m[3];
564 transformed[Y] = (m[4] * x) + (m[5] * y) + (m[6] * z) + m[7];
565 transformed[Z] = (m[8] * x) + (m[9] * y) + (m[10] * z) + m[11];
566
567 double rx = (((transformed[axisX] * negXFac) + m_virtWidth + pan (X)) * m_width) / (2 * m_virtWidth);
568 double ry = (((transformed[axisY] * negYFac) - m_virtHeight + pan (Y)) * m_height) / (2 * m_virtHeight);
569
570 return QPoint (rx, -ry);
571 }
572
573 // =============================================================================
574 //
575 void GLRenderer::paintEvent (QPaintEvent* ev)
576 {
577 Q_UNUSED (ev)
578
579 makeCurrent();
580 m_virtWidth = zoom();
581 m_virtHeight = (m_height * m_virtWidth) / m_width;
582
583 initGLData();
584 drawGLScene();
585
586 const QPen textpen (m_darkbg ? Qt::white : Qt::black);
587 const QBrush polybrush (QColor (64, 192, 0, 128));
588 QPainter paint (this);
589 QFontMetrics metrics = QFontMetrics (QFont());
590 paint.setRenderHint (QPainter::HighQualityAntialiasing);
591
592 // If we wish to only draw the brick, stop here
593 if (isDrawOnly())
594 return;
595
596 if (m_camera != EFreeCamera && !isPicking())
597 {
598 // Paint the overlay image if we have one
599 const LDGLOverlay& overlay = currentDocumentData().overlays[m_camera];
600
601 if (overlay.img != null)
602 {
603 QPoint v0 = coordconv3_2 (currentDocumentData().overlays[m_camera].v0),
604 v1 = coordconv3_2 (currentDocumentData().overlays[m_camera].v1);
605
606 QRect targRect (v0.x(), v0.y(), abs (v1.x() - v0.x()), abs (v1.y() - v0.y())),
607 srcRect (0, 0, overlay.img->width(), overlay.img->height());
608 paint.drawImage (targRect, *overlay.img, srcRect);
609 }
610
611 // Paint the coordinates onto the screen.
612 QString text = format (tr ("X: %1, Y: %2, Z: %3"), m_hoverpos[X], m_hoverpos[Y], m_hoverpos[Z]);
613 QFontMetrics metrics = QFontMetrics (font());
614 QRect textSize = metrics.boundingRect (0, 0, m_width, m_height, Qt::AlignCenter, text);
615 paint.setPen (textpen);
616 paint.drawText (m_width - textSize.width(), m_height - 16, textSize.width(),
617 textSize.height(), Qt::AlignCenter, text);
618
619 QPen linepen = m_thinBorderPen;
620 linepen.setWidth (2);
621 linepen.setColor (luma (m_bgcolor) < 40 ? Qt::white : Qt::black);
622
623 // Mode-specific rendering
624 if (editMode() == EDrawMode)
625 {
626 QPoint poly[4];
627 Vertex poly3d[4];
628 int numverts = 4;
629
630 // Calculate polygon data
631 if (!m_rectdraw)
632 {
633 numverts = m_drawedVerts.size() + 1;
634 int i = 0;
635
636 for (Vertex& vert : m_drawedVerts)
637 poly3d[i++] = vert;
638
639 // Draw the cursor vertex as the last one in the list.
640 if (numverts <= 4)
641 poly3d[i] = m_hoverpos;
642 else
643 numverts = 4;
644 }
645 else
646 {
647 // Get vertex information from m_rectverts
648 if (m_drawedVerts.size() > 0)
649 for (int i = 0; i < numverts; ++i)
650 poly3d[i] = m_rectverts[i];
651 else
652 poly3d[0] = m_hoverpos;
653 }
654
655 // Convert to 2D
656 for (int i = 0; i < numverts; ++i)
657 poly[i] = coordconv3_2 (poly3d[i]);
658
659 if (numverts > 0)
660 {
661 // Draw the polygon-to-be
662 paint.setBrush (polybrush);
663 paint.drawPolygon (poly, numverts);
664
665 // Draw vertex blips
666 for (int i = 0; i < numverts; ++i)
667 {
668 QPoint& blip = poly[i];
669 paint.setPen (linepen);
670 drawBlip (paint, blip);
671
672 // Draw their coordinates
673 paint.setPen (textpen);
674 paint.drawText (blip.x(), blip.y() - 8, poly3d[i].toString (true));
675 }
676
677 // Draw line lenghts and angle info if appropriate
678 if (numverts >= 2)
679 {
680 int numlines = (m_drawedVerts.size() == 1) ? 1 : m_drawedVerts.size() + 1;
681 paint.setPen (textpen);
682
683 for (int i = 0; i < numlines; ++i)
684 {
685 const int j = (i + 1 < numverts) ? i + 1 : 0;
686 const int h = (i - 1 >= 0) ? i - 1 : numverts - 1;
687
688 if (gl_linelengths)
689 {
690 const QString label = QString::number (poly3d[i].distanceTo (poly3d[j]));
691 QPoint origin = QLineF (poly[i], poly[j]).pointAt (0.5).toPoint();
692 paint.drawText (origin, label);
693 }
694
695 if (gl_drawangles)
696 {
697 QLineF l0 (poly[h], poly[i]),
698 l1 (poly[i], poly[j]);
699
700 double angle = 180 - l0.angleTo (l1);
701
702 if (angle < 0)
703 angle = 180 - l1.angleTo (l0);
704
705 QString label = QString::number (angle) + QString::fromUtf8 (QByteArray ("\302\260"));
706 QPoint pos = poly[i];
707 pos.setY (pos.y() + metrics.height());
708
709 paint.drawText (pos, label);
710 }
711 }
712 }
713 }
714 }
715 elif (editMode() == ECircleMode)
716 {
717 // If we have not specified the center point of the circle yet, preview it on the screen.
718 if (m_drawedVerts.isEmpty())
719 drawBlip (paint, coordconv3_2 (m_hoverpos));
720 else
721 {
722 QVector<Vertex> verts, verts2;
723 const double dist0 = getCircleDrawDist (0),
724 dist1 = (m_drawedVerts.size() >= 2) ? getCircleDrawDist (1) : -1;
725 const int segs = g_lores;
726 const double angleUnit = (2 * pi) / segs;
727 Axis relX, relY;
728 QVector<QPoint> ringpoints, circlepoints, circle2points;
729
730 getRelativeAxes (relX, relY);
731
732 // Calculate the preview positions of vertices
733 for (int i = 0; i < segs; ++i)
734 {
735 Vertex v = g_origin;
736 v[relX] = m_drawedVerts[0][relX] + (cos (i * angleUnit) * dist0);
737 v[relY] = m_drawedVerts[0][relY] + (sin (i * angleUnit) * dist0);
738 verts << v;
739
740 if (dist1 != -1)
741 {
742 v[relX] = m_drawedVerts[0][relX] + (cos (i * angleUnit) * dist1);
743 v[relY] = m_drawedVerts[0][relY] + (sin (i * angleUnit) * dist1);
744 verts2 << v;
745 }
746 }
747
748 int i = 0;
749 for (const Vertex& v : verts + verts2)
750 {
751 // Calculate the 2D point of the vertex
752 QPoint point = coordconv3_2 (v);
753
754 // Draw a green blip at where it is
755 drawBlip (paint, point);
756
757 // Add it to the list of points for the green ring fill.
758 ringpoints << point;
759
760 // Also add the circle points to separate lists
761 if (i < verts.size())
762 circlepoints << point;
763 else
764 circle2points << point;
765
766 ++i;
767 }
768
769 // Insert the first point as the seventeenth one so that
770 // the ring polygon is closed properly.
771 if (ringpoints.size() >= 16)
772 ringpoints.insert (16, ringpoints[0]);
773
774 // Same for the outer ring. Note that the indices are offset by 1
775 // because of the insertion done above bumps the values.
776 if (ringpoints.size() >= 33)
777 ringpoints.insert (33, ringpoints[17]);
778
779 // Draw the ring
780 paint.setBrush ((m_drawedVerts.size() >= 2) ? polybrush : Qt::NoBrush);
781 paint.setPen (Qt::NoPen);
782 paint.drawPolygon (QPolygon (ringpoints));
783
784 // Draw the circles
785 paint.setBrush (Qt::NoBrush);
786 paint.setPen (linepen);
787 paint.drawPolygon (QPolygon (circlepoints));
788 paint.drawPolygon (QPolygon (circle2points));
789
790 { // Draw the current radius in the middle of the circle.
791 QPoint origin = coordconv3_2 (m_drawedVerts[0]);
792 QString label = QString::number (dist0);
793 paint.setPen (textpen);
794 paint.drawText (origin.x() - (metrics.width (label) / 2), origin.y(), label);
795
796 if (m_drawedVerts.size() >= 2)
797 {
798 label = QString::number (dist1);
799 paint.drawText (origin.x() - (metrics.width (label) / 2), origin.y() + metrics.height(), label);
800 }
801 }
802 }
803 }
804 }
805
806 // Camera icons
807 if (!isPicking())
808 {
809 // Draw a background for the selected camera
810 paint.setPen (m_thinBorderPen);
811 paint.setBrush (QBrush (QColor (0, 128, 160, 128)));
812 paint.drawRect (m_cameraIcons[camera()].selRect);
813
814 // Draw the actual icons
815 for (CameraIcon& info : m_cameraIcons)
816 {
817 // Don't draw the free camera icon when in draw mode
818 if (&info == &m_cameraIcons[GL::EFreeCamera] && editMode() != ESelectMode)
819 continue;
820
821 paint.drawPixmap (info.destRect, *info.img, info.srcRect);
822 }
823
824 QString formatstr = tr ("%1 Camera");
825
826 // Draw a label for the current camera in the bottom left corner
827 {
828 const int margin = 4;
829
830 QString label;
831 label = format (formatstr, tr (g_CameraNames[camera()]));
832 paint.setPen (textpen);
833 paint.drawText (QPoint (margin, height() - (margin + metrics.descent())), label);
834 }
835
836 // Tool tips
837 if (m_drawToolTip)
838 {
839 if (m_cameraIcons[m_toolTipCamera].destRect.contains (m_pos) == false)
840 m_drawToolTip = false;
841 else
842 {
843 QString label = format (formatstr, tr (g_CameraNames[m_toolTipCamera]));
844 QToolTip::showText (m_globalpos, label);
845 }
846 }
847 }
848
849 // Message log
850 if (messageLog())
851 {
852 int y = 0;
853 const int margin = 2;
854 QColor penColor = textpen.color();
855
856 for (const MessageManager::Line& line : messageLog()->getLines())
857 {
858 penColor.setAlphaF (line.alpha);
859 paint.setPen (penColor);
860 paint.drawText (QPoint (margin, y + margin + metrics.ascent()), line.text);
861 y += metrics.height();
862 }
863 }
864
865 // If we're range-picking, draw a rectangle encompassing the selection area.
866 if (m_rangepick && !isPicking() && m_totalmove >= 10)
867 {
868 int x0 = m_rangeStart.x(),
869 y0 = m_rangeStart.y(),
870 x1 = m_pos.x(),
871 y1 = m_pos.y();
872
873 QRect rect (x0, y0, x1 - x0, y1 - y0);
874 QColor fillColor = (m_addpick ? "#40FF00" : "#00CCFF");
875 fillColor.setAlphaF (0.2f);
876
877 paint.setPen (m_thickBorderPen);
878 paint.setBrush (QBrush (fillColor));
879 paint.drawRect (rect);
880 }
881 }
882
883 // =============================================================================
884 //
885 void GLRenderer::drawBlip (QPainter& paint, QPoint pos) const
886 {
887 QPen pen = m_thinBorderPen;
888 const int blipsize = 8;
889 pen.setWidth (1);
890 paint.setPen (pen);
891 paint.setBrush (QColor (64, 192, 0));
892 paint.drawEllipse (pos.x() - blipsize / 2, pos.y() - blipsize / 2, blipsize, blipsize);
893 }
894
895 // =============================================================================
896 //
897 void GLRenderer::compileAllObjects()
898 {
899 if (!document())
900 return;
901
902 // Compiling all is a big job, use a busy cursor
903 setCursor (Qt::BusyCursor);
904
905 m_knownVerts.clear();
906
907 for (LDObject* obj : document()->objects())
908 compileObject (obj);
909
910 // Compile axes
911 glDeleteLists (m_axeslist, 1);
912 m_axeslist = glGenLists (1);
913 glNewList (m_axeslist, GL_COMPILE);
914 glBegin (GL_LINES);
915
916 for (const LDGLAxis& ax : g_GLAxes)
917 {
918 qglColor (ax.col);
919 compileVertex (ax.vert);
920 compileVertex (-ax.vert);
921 }
922
923 glEnd();
924 glEndList();
925
926 setCursor (Qt::ArrowCursor);
927 }
928
929 // =============================================================================
930 //
931 void GLRenderer::compileSubObject (LDObject* obj, const GLenum gltype)
932 {
933 glBegin (gltype);
934
935 const int numverts = (obj->type() != LDObject::ECondLine) ? obj->vertices() : 2;
936
937 if (g_glInvert == false)
938 for (int i = 0; i < numverts; ++i)
939 compileVertex (obj->vertex (i));
940 else
941 for (int i = numverts - 1; i >= 0; --i)
942 compileVertex (obj->vertex (i));
943
944 glEnd();
945 }
946
947 // =============================================================================
948 //
949 void GLRenderer::compileList (LDObject* obj, const GLRenderer::ListType list)
950 {
951 setObjectColor (obj, list);
952
953 switch (obj->type())
954 {
955 case LDObject::ELine:
956 {
957 compileSubObject (obj, GL_LINES);
958 } break;
959
960 case LDObject::ECondLine:
961 {
962 // Draw conditional lines with a dash pattern - however, use a full
963 // line when drawing a pick list to make selecting them easier.
964 if (list != GL::PickList)
965 {
966 glLineStipple (1, 0x6666);
967 glEnable (GL_LINE_STIPPLE);
968 }
969
970 compileSubObject (obj, GL_LINES);
971
972 glDisable (GL_LINE_STIPPLE);
973 } break;
974
975 case LDObject::ETriangle:
976 {
977 compileSubObject (obj, GL_TRIANGLES);
978 } break;
979
980 case LDObject::EQuad:
981 {
982 compileSubObject (obj, GL_QUADS);
983 } break;
984
985 case LDObject::ESubfile:
986 {
987 LDSubfile* ref = static_cast<LDSubfile*> (obj);
988 LDObjectList objs;
989
990 objs = ref->inlineContents (LDSubfile::DeepCacheInline | LDSubfile::RendererInline);
991 bool oldinvert = g_glInvert;
992
993 if (ref->transform().getDeterminant() < 0)
994 g_glInvert = !g_glInvert;
995
996 LDObject* prev = ref->previous();
997
998 if (prev && prev->type() == LDObject::EBFC && static_cast<LDBFC*> (prev)->statement() == LDBFC::InvertNext)
999 g_glInvert = !g_glInvert;
1000
1001 for (LDObject* obj : objs)
1002 {
1003 compileList (obj, list);
1004 obj->destroy();
1005 }
1006
1007 g_glInvert = oldinvert;
1008 } break;
1009
1010 default:
1011 break;
1012 }
1013 }
1014
1015 // =============================================================================
1016 //
1017 void GLRenderer::compileVertex (const Vertex& vrt)
1018 {
1019 glVertex3d (vrt[X], -vrt[Y], -vrt[Z]);
1020 }
1021
1022 // =============================================================================
1023 //
1024 void GLRenderer::clampAngle (double& angle) const
1025 {
1026 while (angle < 0)
1027 angle += 360.0;
1028
1029 while (angle > 360.0)
1030 angle -= 360.0;
1031 }
1032
1033 // =============================================================================
1034 //
1035 void GLRenderer::addDrawnVertex (Vertex pos)
1036 {
1037 // If we picked an already-existing vertex, stop drawing
1038 if (editMode() == EDrawMode)
1039 {
1040 for (Vertex& vert : m_drawedVerts)
1041 {
1042 if (vert == pos)
1043 {
1044 endDraw (true);
1045 return;
1046 }
1047 }
1048 }
1049
1050 m_drawedVerts << pos;
1051 }
1052
1053 // =============================================================================
1054 //
1055 void GLRenderer::mouseReleaseEvent (QMouseEvent* ev)
1056 {
1057 const bool wasLeft = (m_lastButtons & Qt::LeftButton) && ! (ev->buttons() & Qt::LeftButton),
1058 wasRight = (m_lastButtons & Qt::RightButton) && ! (ev->buttons() & Qt::RightButton),
1059 wasMid = (m_lastButtons & Qt::MidButton) && ! (ev->buttons() & Qt::MidButton);
1060
1061 if (m_panning)
1062 m_panning = false;
1063
1064 if (wasLeft)
1065 {
1066 // Check if we selected a camera icon
1067 if (!m_rangepick)
1068 {
1069 for (CameraIcon & info : m_cameraIcons)
1070 {
1071 if (info.destRect.contains (ev->pos()))
1072 {
1073 setCamera (info.cam);
1074 goto end;
1075 }
1076 }
1077 }
1078
1079 switch (editMode())
1080 {
1081 case EDrawMode:
1082 {
1083 if (m_rectdraw)
1084 {
1085 if (m_drawedVerts.size() == 2)
1086 {
1087 endDraw (true);
1088 return;
1089 }
1090 } else
1091 {
1092 // If we have 4 verts, stop drawing.
1093 if (m_drawedVerts.size() >= 4)
1094 {
1095 endDraw (true);
1096 return;
1097 }
1098
1099 if (m_drawedVerts.isEmpty() && ev->modifiers() & Qt::ShiftModifier)
1100 {
1101 m_rectdraw = true;
1102 updateRectVerts();
1103 }
1104 }
1105
1106 addDrawnVertex (m_hoverpos);
1107 } break;
1108
1109 case ECircleMode:
1110 {
1111 if (m_drawedVerts.size() == 3)
1112 {
1113 endDraw (true);
1114 return;
1115 }
1116
1117 addDrawnVertex (m_hoverpos);
1118 } break;
1119
1120 case ESelectMode:
1121 {
1122 if (!isDrawOnly())
1123 {
1124 if (m_totalmove < 10)
1125 m_rangepick = false;
1126
1127 if (!m_rangepick)
1128 m_addpick = (m_keymods & Qt::ControlModifier);
1129
1130 if (m_totalmove < 10 || m_rangepick)
1131 pick (ev->x(), ev->y());
1132 }
1133 } break;
1134 }
1135
1136 m_rangepick = false;
1137 }
1138
1139 if (wasMid && editMode() != ESelectMode && m_drawedVerts.size() < 4 && m_totalmove < 10)
1140 {
1141 // Find the closest vertex to our cursor
1142 double mindist = 1024.0f;
1143 Vertex closest;
1144 bool valid = false;
1145
1146 QPoint curspos = coordconv3_2 (m_hoverpos);
1147
1148 for (const Vertex& pos3d: m_knownVerts)
1149 {
1150 QPoint pos2d = coordconv3_2 (pos3d);
1151
1152 // Measure squared distance
1153 const double dx = abs (pos2d.x() - curspos.x()),
1154 dy = abs (pos2d.y() - curspos.y()),
1155 distsq = (dx * dx) + (dy * dy);
1156
1157 if (distsq >= 1024.0f) // 32.0f ** 2
1158 continue; // too far away
1159
1160 if (distsq < mindist)
1161 {
1162 mindist = distsq;
1163 closest = pos3d;
1164 valid = true;
1165
1166 // If it's only 4 pixels away, I think we found our vertex now.
1167 if (distsq <= 16.0f) // 4.0f ** 2
1168 break;
1169 }
1170 }
1171
1172 if (valid)
1173 addDrawnVertex (closest);
1174 }
1175
1176 if (wasRight && !m_drawedVerts.isEmpty())
1177 {
1178 // Remove the last vertex
1179 m_drawedVerts.removeLast();
1180
1181 if (m_drawedVerts.isEmpty())
1182 m_rectdraw = false;
1183 }
1184
1185 end:
1186 update();
1187 m_totalmove = 0;
1188 }
1189
1190 // =============================================================================
1191 //
1192 void GLRenderer::mousePressEvent (QMouseEvent* ev)
1193 {
1194 m_totalmove = 0;
1195
1196 if (ev->modifiers() & Qt::ControlModifier)
1197 {
1198 m_rangepick = true;
1199 m_rangeStart.setX (ev->x());
1200 m_rangeStart.setY (ev->y());
1201 m_addpick = (m_keymods & Qt::AltModifier);
1202 ev->accept();
1203 }
1204
1205 m_lastButtons = ev->buttons();
1206 }
1207
1208 // =============================================================================
1209 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1210 // =============================================================================
1211 void GLRenderer::mouseMoveEvent (QMouseEvent* ev)
1212 {
1213 int dx = ev->x() - m_pos.x();
1214 int dy = ev->y() - m_pos.y();
1215 m_totalmove += abs (dx) + abs (dy);
1216
1217 const bool left = ev->buttons() & Qt::LeftButton,
1218 mid = ev->buttons() & Qt::MidButton,
1219 shift = ev->modifiers() & Qt::ShiftModifier;
1220
1221 if (mid || (left && shift))
1222 {
1223 pan (X) += 0.03f * dx * (zoom() / 7.5f);
1224 pan (Y) -= 0.03f * dy * (zoom() / 7.5f);
1225 m_panning = true;
1226 } elif (left && !m_rangepick && camera() == EFreeCamera)
1227 {
1228 rot (X) = rot (X) + dy;
1229 rot (Y) = rot (Y) + dx;
1230
1231 clampAngle (rot (X));
1232 clampAngle (rot (Y));
1233 }
1234
1235 // Start the tool tip timer
1236 if (!m_drawToolTip)
1237 m_toolTipTimer->start (500);
1238
1239 // Update 2d position
1240 m_pos = ev->pos();
1241 m_globalpos = ev->globalPos();
1242
1243 // Calculate 3d position of the cursor
1244 m_hoverpos = (camera() != EFreeCamera) ? coordconv2_3 (m_pos, true) : g_origin;
1245
1246 // Update rect vertices since m_hoverpos may have changed
1247 updateRectVerts();
1248
1249 update();
1250 }
1251
1252 // =============================================================================
1253 //
1254 void GLRenderer::keyPressEvent (QKeyEvent* ev)
1255 {
1256 m_keymods = ev->modifiers();
1257 }
1258
1259 // =============================================================================
1260 //
1261 void GLRenderer::keyReleaseEvent (QKeyEvent* ev)
1262 {
1263 m_keymods = ev->modifiers();
1264 }
1265
1266 // =============================================================================
1267 //
1268 void GLRenderer::wheelEvent (QWheelEvent* ev)
1269 {
1270 makeCurrent();
1271
1272 zoomNotch (ev->delta() > 0);
1273 zoom() = clamp (zoom(), 0.01, 10000.0);
1274
1275 update();
1276 ev->accept();
1277 }
1278
1279 // =============================================================================
1280 //
1281 void GLRenderer::leaveEvent (QEvent* ev)
1282 {
1283 (void) ev;
1284 m_drawToolTip = false;
1285 m_toolTipTimer->stop();
1286 update();
1287 }
1288
1289 // =============================================================================
1290 //
1291 void GLRenderer::contextMenuEvent (QContextMenuEvent* ev)
1292 {
1293 g_win->spawnContextMenu (ev->globalPos());
1294 }
1295
1296 // =============================================================================
1297 //
1298 void GLRenderer::setCamera (const GLRenderer::EFixedCamera cam)
1299 {
1300 m_camera = cam;
1301 gl_camera = (int) cam;
1302 g_win->updateEditModeActions();
1303 }
1304
1305 // =============================================================================
1306 //
1307 void GLRenderer::pick (int mouseX, int mouseY)
1308 {
1309 makeCurrent();
1310
1311 // Use particularly thick lines while picking ease up selecting lines.
1312 glLineWidth (max<double> (gl_linethickness, 6.5f));
1313
1314 // Clear the selection if we do not wish to add to it.
1315 if (!m_addpick)
1316 {
1317 LDObjectList oldsel = selection();
1318 getCurrentDocument()->clearSelection();
1319
1320 for (LDObject* obj : oldsel)
1321 compileObject (obj);
1322 }
1323
1324 setPicking (true);
1325
1326 // Paint the picking scene
1327 glDisable (GL_DITHER);
1328 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
1329 drawGLScene();
1330
1331 int x0 = mouseX,
1332 y0 = mouseY;
1333 int x1, y1;
1334
1335 // Determine how big an area to read - with range picking, we pick by
1336 // the area given, with single pixel picking, we use an 1 x 1 area.
1337 if (m_rangepick)
1338 {
1339 x1 = m_rangeStart.x();
1340 y1 = m_rangeStart.y();
1341 }
1342 else
1343 {
1344 x1 = x0 + 1;
1345 y1 = y0 + 1;
1346 }
1347
1348 // x0 and y0 must be less than x1 and y1, respectively.
1349 if (x0 > x1)
1350 qSwap (x0, x1);
1351
1352 if (y0 > y1)
1353 qSwap (y0, y1);
1354
1355 // Clamp the values to ensure they're within bounds
1356 x0 = max (0, x0);
1357 y0 = max (0, y0);
1358 x1 = min (x1, m_width);
1359 y1 = min (y1, m_height);
1360 const int areawidth = (x1 - x0);
1361 const int areaheight = (y1 - y0);
1362 const qint32 numpixels = areawidth * areaheight;
1363
1364 // Allocate space for the pixel data.
1365 uchar* const pixeldata = new uchar[4 * numpixels];
1366 uchar* pixelptr = &pixeldata[0];
1367
1368 // Read pixels from the color buffer.
1369 glReadPixels (x0, m_height - y1, areawidth, areaheight, GL_RGBA, GL_UNSIGNED_BYTE, pixeldata);
1370
1371 LDObject* removedObj = null;
1372
1373 // Go through each pixel read and add them to the selection.
1374 for (qint32 i = 0; i < numpixels; ++i)
1375 {
1376 qint32 idx =
1377 (*(pixelptr + 0) * 0x10000) +
1378 (*(pixelptr + 1) * 0x00100) +
1379 (*(pixelptr + 2) * 0x00001);
1380 pixelptr += 4;
1381
1382 if (idx == 0xFFFFFF)
1383 continue; // White is background; skip
1384
1385 LDObject* obj = LDObject::fromID (idx);
1386 assert (obj != null);
1387
1388 // If this is an additive single pick and the object is currently selected,
1389 // we remove it from selection instead.
1390 if (!m_rangepick && m_addpick)
1391 {
1392 if (obj->isSelected())
1393 {
1394 obj->unselect();
1395 removedObj = obj;
1396 break;
1397 }
1398 }
1399
1400 obj->select();
1401 }
1402
1403 delete[] pixeldata;
1404
1405 // Update everything now.
1406 g_win->updateSelection();
1407
1408 // Recompile the objects now to update their color
1409 for (LDObject* obj : selection())
1410 compileObject (obj);
1411
1412 if (removedObj)
1413 compileObject (removedObj);
1414
1415 // Restore line thickness
1416 glLineWidth (gl_linethickness);
1417
1418 setPicking (false);
1419 m_rangepick = false;
1420 glEnable (GL_DITHER);
1421
1422 setBackground();
1423 repaint();
1424 }
1425
1426 // =============================================================================
1427 //
1428 void GLRenderer::setEditMode (EditMode const& a)
1429 {
1430 m_editMode = a;
1431
1432 switch (a)
1433 {
1434 case ESelectMode:
1435 {
1436 unsetCursor();
1437 setContextMenuPolicy (Qt::DefaultContextMenu);
1438 } break;
1439
1440 case EDrawMode:
1441 case ECircleMode:
1442 {
1443 // Cannot draw into the free camera - use top instead.
1444 if (m_camera == EFreeCamera)
1445 setCamera (ETopCamera);
1446
1447 // Disable the context menu - we need the right mouse button
1448 // for removing vertices.
1449 setContextMenuPolicy (Qt::NoContextMenu);
1450
1451 // Use the crosshair cursor when drawing.
1452 setCursor (Qt::CrossCursor);
1453
1454 // Clear the selection when beginning to draw.
1455 LDObjectList priorsel = selection();
1456 getCurrentDocument()->clearSelection();
1457
1458 for (LDObject* obj : priorsel)
1459 compileObject (obj);
1460
1461 g_win->updateSelection();
1462 m_drawedVerts.clear();
1463 } break;
1464 }
1465
1466 g_win->updateEditModeActions();
1467 update();
1468 }
1469
1470 // =============================================================================
1471 //
1472 void GLRenderer::setDocument (LDDocument* const& a)
1473 {
1474 m_document = a;
1475
1476 if (a != null)
1477 {
1478 initOverlaysFromObjects();
1479
1480 if (currentDocumentData().init == false)
1481 {
1482 resetAllAngles();
1483 currentDocumentData().init = true;
1484 }
1485 }
1486 }
1487
1488 // =============================================================================
1489 //
1490 Matrix GLRenderer::getCircleDrawMatrix (double scale)
1491 {
1492 Matrix transform = g_circleDrawMatrixTemplates[camera() % 3];
1493
1494 for (int i = 0; i < 9; ++i)
1495 {
1496 if (transform[i] == 2)
1497 transform[i] = scale;
1498 elif (transform[i] == 1 && camera() >= 3)
1499 transform[i] = -1;
1500 }
1501
1502 return transform;
1503 }
1504
1505 // =============================================================================
1506 //
1507 void GLRenderer::endDraw (bool accept)
1508 {
1509 (void) accept;
1510
1511 // Clean the selection and create the object
1512 QList<Vertex>& verts = m_drawedVerts;
1513 LDObjectList objs;
1514
1515 switch (editMode())
1516 {
1517 case EDrawMode:
1518 {
1519 if (m_rectdraw)
1520 {
1521 LDQuad* quad = new LDQuad;
1522
1523 // Copy the vertices from m_rectverts
1524 updateRectVerts();
1525
1526 for (int i = 0; i < quad->vertices(); ++i)
1527 quad->setVertex (i, m_rectverts[i]);
1528
1529 quad->setColor (maincolor);
1530 objs << quad;
1531 }
1532 else
1533 {
1534 switch (verts.size())
1535 {
1536 case 1:
1537 {
1538 // 1 vertex - add a vertex object
1539 LDVertex* obj = new LDVertex;
1540 obj->pos = verts[0];
1541 obj->setColor (maincolor);
1542 objs << obj;
1543 } break;
1544
1545 case 2:
1546 {
1547 // 2 verts - make a line
1548 LDLine* obj = new LDLine (verts[0], verts[1]);
1549 obj->setColor (edgecolor);
1550 objs << obj;
1551 } break;
1552
1553 case 3:
1554 case 4:
1555 {
1556 LDObject* obj = (verts.size() == 3) ?
1557 static_cast<LDObject*> (new LDTriangle) :
1558 static_cast<LDObject*> (new LDQuad);
1559
1560 obj->setColor (maincolor);
1561
1562 for (int i = 0; i < obj->vertices(); ++i)
1563 obj->setVertex (i, verts[i]);
1564
1565 objs << obj;
1566 } break;
1567 }
1568 }
1569 } break;
1570
1571 case ECircleMode:
1572 {
1573 const int segs = g_lores, divs = g_lores; // TODO: make customizable
1574 double dist0 = getCircleDrawDist (0),
1575 dist1 = getCircleDrawDist (1);
1576 LDDocument* refFile = null;
1577 Matrix transform;
1578 bool circleOrDisc = false;
1579
1580 if (dist1 < dist0)
1581 std::swap<double> (dist0, dist1);
1582
1583 if (dist0 == dist1)
1584 {
1585 // If the radii are the same, there's no ring space to fill. Use a circle.
1586 refFile = ::getDocument ("4-4edge.dat");
1587 transform = getCircleDrawMatrix (dist0);
1588 circleOrDisc = true;
1589 }
1590 elif (dist0 == 0 || dist1 == 0)
1591 {
1592 // If either radii is 0, use a disc.
1593 refFile = ::getDocument ("4-4disc.dat");
1594 transform = getCircleDrawMatrix ((dist0 != 0) ? dist0 : dist1);
1595 circleOrDisc = true;
1596 }
1597 elif (g_RingFinder.findRings (dist0, dist1))
1598 {
1599 // The ring finder found a solution, use that. Add the component rings to the file.
1600 for (const RingFinder::Component& cmp : g_RingFinder.bestSolution()->getComponents())
1601 {
1602 // Get a ref file for this primitive. If we cannot find it in the
1603 // LDraw library, generate it.
1604 if ((refFile = ::getDocument (radialFileName (::Ring, g_lores, g_lores, cmp.num))) == null)
1605 {
1606 refFile = generatePrimitive (::Ring, g_lores, g_lores, cmp.num);
1607 refFile->setImplicit (false);
1608 }
1609
1610 LDSubfile* ref = new LDSubfile;
1611 ref->setFileInfo (refFile);
1612 ref->setTransform (getCircleDrawMatrix (cmp.scale));
1613 ref->setPosition (m_drawedVerts[0]);
1614 ref->setColor (maincolor);
1615 objs << ref;
1616 }
1617 }
1618 else
1619 {
1620 // Ring finder failed, last resort: draw the ring with quads
1621 QList<QLineF> c0, c1;
1622 Axis relX, relY, relZ;
1623 getRelativeAxes (relX, relY);
1624 relZ = (Axis) (3 - relX - relY);
1625 double x0 = m_drawedVerts[0][relX],
1626 y0 = m_drawedVerts[0][relY];
1627
1628 Vertex templ;
1629 templ[relX] = x0;
1630 templ[relY] = y0;
1631 templ[relZ] = getDepthValue();
1632
1633 // Calculate circle coords
1634 makeCircle (segs, divs, dist0, c0);
1635 makeCircle (segs, divs, dist1, c1);
1636
1637 for (int i = 0; i < segs; ++i)
1638 {
1639 Vertex v0, v1, v2, v3;
1640 v0 = v1 = v2 = v3 = templ;
1641 v0[relX] += c0[i].x1();
1642 v0[relY] += c0[i].y1();
1643 v1[relX] += c0[i].x2();
1644 v1[relY] += c0[i].y2();
1645 v2[relX] += c1[i].x2();
1646 v2[relY] += c1[i].y2();
1647 v3[relX] += c1[i].x1();
1648 v3[relY] += c1[i].y1();
1649
1650 LDQuad* q = new LDQuad (v0, v1, v2, v3);
1651 q->setColor (maincolor);
1652
1653 // Ensure the quads always are BFC-front towards the camera
1654 if (camera() % 3 <= 0)
1655 q->invert();
1656
1657 objs << q;
1658 }
1659 }
1660
1661 if (circleOrDisc)
1662 {
1663 LDSubfile* ref = new LDSubfile;
1664 ref->setFileInfo (refFile);
1665 ref->setTransform (transform);
1666 ref->setPosition (m_drawedVerts[0]);
1667 ref->setColor (maincolor);
1668 objs << ref;
1669 }
1670 } break;
1671
1672 case ESelectMode:
1673 {
1674 // this shouldn't happen
1675 assert (false);
1676 return;
1677 } break;
1678 }
1679
1680 if (objs.size() > 0)
1681 {
1682 for (LDObject* obj : objs)
1683 {
1684 document()->addObject (obj);
1685 compileObject (obj);
1686 }
1687
1688 g_win->refresh();
1689 g_win->endAction();
1690 }
1691
1692 m_drawedVerts.clear();
1693 m_rectdraw = false;
1694 }
1695
1696 // =============================================================================
1697 //
1698 double GLRenderer::getCircleDrawDist (int pos) const
1699 {
1700 assert (m_drawedVerts.size() >= pos + 1);
1701 const Vertex& v1 = (m_drawedVerts.size() >= pos + 2) ? m_drawedVerts[pos + 1] : m_hoverpos;
1702 Axis relX, relY;
1703 getRelativeAxes (relX, relY);
1704
1705 const double dx = m_drawedVerts[0][relX] - v1[relX];
1706 const double dy = m_drawedVerts[0][relY] - v1[relY];
1707 return sqrt ((dx * dx) + (dy * dy));
1708 }
1709
1710 // =============================================================================
1711 //
1712 void GLRenderer::getRelativeAxes (Axis& relX, Axis& relY) const
1713 {
1714 const LDFixedCameraInfo* cam = &g_FixedCameras[m_camera];
1715 relX = cam->axisX;
1716 relY = cam->axisY;
1717 }
1718
1719 // =============================================================================
1720 //
1721 static QList<Vertex> getVertices (LDObject* obj)
1722 {
1723 QList<Vertex> verts;
1724
1725 if (obj->vertices() >= 2)
1726 {
1727 for (int i = 0; i < obj->vertices(); ++i)
1728 verts << obj->vertex (i);
1729 } elif (obj->type() == LDObject::ESubfile)
1730 {
1731 LDSubfile* ref = static_cast<LDSubfile*> (obj);
1732 LDObjectList objs = ref->inlineContents (LDSubfile::DeepCacheInline);
1733
1734 for (LDObject* obj : objs)
1735 {
1736 verts << getVertices (obj);
1737 obj->destroy();
1738 }
1739 }
1740
1741 return verts;
1742 }
1743
1744 // =============================================================================
1745 //
1746 void GLRenderer::compileObject (LDObject* obj)
1747 {
1748 deleteLists (obj);
1749
1750 for (const GL::ListType listType : g_glListTypes)
1751 {
1752 if (isDrawOnly() && listType != GL::NormalList)
1753 continue;
1754
1755 GLuint list = glGenLists (1);
1756 glNewList (list, GL_COMPILE);
1757
1758 obj->glLists[listType] = list;
1759 compileList (obj, listType);
1760
1761 glEndList();
1762 }
1763
1764 // Mark in known vertices of this object
1765 QList<Vertex> verts = getVertices (obj);
1766 m_knownVerts << verts;
1767 removeDuplicates (m_knownVerts);
1768
1769 obj->setGLInit (true);
1770 }
1771
1772 // =============================================================================
1773 //
1774 uchar* GLRenderer::getScreencap (int& w, int& h)
1775 {
1776 w = m_width;
1777 h = m_height;
1778 uchar* cap = new uchar[4 * w * h];
1779
1780 m_screencap = true;
1781 update();
1782 m_screencap = false;
1783
1784 // Capture the pixels
1785 glReadPixels (0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, cap);
1786
1787 return cap;
1788 }
1789
1790 // =============================================================================
1791 //
1792 void GLRenderer::slot_toolTipTimer()
1793 {
1794 // We come here if the cursor has stayed in one place for longer than a
1795 // a second. Check if we're holding it over a camera icon - if so, draw
1796 // a tooltip.
1797 for (CameraIcon & icon : m_cameraIcons)
1798 {
1799 if (icon.destRect.contains (m_pos))
1800 {
1801 m_toolTipCamera = icon.cam;
1802 m_drawToolTip = true;
1803 update();
1804 break;
1805 }
1806 }
1807 }
1808
1809 // =============================================================================
1810 //
1811 void GLRenderer::deleteLists (LDObject* obj)
1812 {
1813 // Delete the lists but only if they have been initialized
1814 if (!obj->isGLInit())
1815 return;
1816
1817 for (const GL::ListType listType : g_glListTypes)
1818 glDeleteLists (obj->glLists[listType], 1);
1819
1820 obj->setGLInit (false);
1821 }
1822
1823 // =============================================================================
1824 //
1825 Axis GLRenderer::getCameraAxis (bool y, GLRenderer::EFixedCamera camid)
1826 {
1827 if (camid == (GL::EFixedCamera) - 1)
1828 camid = m_camera;
1829
1830 const LDFixedCameraInfo* cam = &g_FixedCameras[camid];
1831 return (y) ? cam->axisY : cam->axisX;
1832 }
1833
1834 // =============================================================================
1835 //
1836 bool GLRenderer::setupOverlay (EFixedCamera cam, QString file, int x, int y, int w, int h)
1837 {
1838 QImage* img = new QImage (QImage (file).convertToFormat (QImage::Format_ARGB32));
1839 LDGLOverlay& info = getOverlay (cam);
1840
1841 if (img->isNull())
1842 {
1843 critical (tr ("Failed to load overlay image!"));
1844 delete img;
1845 return false;
1846 }
1847
1848 delete info.img; // delete the old image
1849
1850 info.fname = file;
1851 info.lw = w;
1852 info.lh = h;
1853 info.ox = x;
1854 info.oy = y;
1855 info.img = img;
1856
1857 if (info.lw == 0)
1858 info.lw = (info.lh * img->width()) / img->height();
1859 elif (info.lh == 0)
1860 info.lh = (info.lw * img->height()) / img->width();
1861
1862 const Axis x2d = getCameraAxis (false, cam),
1863 y2d = getCameraAxis (true, cam);
1864 const double negXFac = g_FixedCameras[cam].negX ? -1 : 1,
1865 negYFac = g_FixedCameras[cam].negY ? -1 : 1;
1866
1867 info.v0 = info.v1 = g_origin;
1868 info.v0[x2d] = - (info.ox * info.lw * negXFac) / img->width();
1869 info.v0[y2d] = (info.oy * info.lh * negYFac) / img->height();
1870 info.v1[x2d] = info.v0[x2d] + info.lw;
1871 info.v1[y2d] = info.v0[y2d] + info.lh;
1872
1873 // Set alpha of all pixels to 0.5
1874 for (long i = 0; i < img->width(); ++i)
1875 for (long j = 0; j < img->height(); ++j)
1876 {
1877 uint32 pixel = img->pixel (i, j);
1878 img->setPixel (i, j, 0x80000000 | (pixel & 0x00FFFFFF));
1879 }
1880
1881 updateOverlayObjects();
1882 return true;
1883 }
1884
1885 // =============================================================================
1886 //
1887 void GLRenderer::clearOverlay()
1888 {
1889 if (camera() == EFreeCamera)
1890 return;
1891
1892 LDGLOverlay& info = currentDocumentData().overlays[camera()];
1893 delete info.img;
1894 info.img = null;
1895
1896 updateOverlayObjects();
1897 }
1898
1899 // =============================================================================
1900 //
1901 void GLRenderer::setDepthValue (double depth)
1902 {
1903 assert (camera() < EFreeCamera);
1904 currentDocumentData().depthValues[camera()] = depth;
1905 }
1906
1907 // =============================================================================
1908 //
1909 double GLRenderer::getDepthValue() const
1910 {
1911 assert (camera() < EFreeCamera);
1912 return currentDocumentData().depthValues[camera()];
1913 }
1914
1915 // =============================================================================
1916 //
1917 const char* GLRenderer::getCameraName() const
1918 {
1919 return g_CameraNames[camera()];
1920 }
1921
1922 // =============================================================================
1923 //
1924 LDGLOverlay& GLRenderer::getOverlay (int newcam)
1925 {
1926 return currentDocumentData().overlays[newcam];
1927 }
1928
1929 // =============================================================================
1930 //
1931 void GLRenderer::zoomNotch (bool inward)
1932 {
1933 if (zoom() > 15)
1934 zoom() *= inward ? 0.833f : 1.2f;
1935 else
1936 zoom() += inward ? -1.2f : 1.2f;
1937 }
1938
1939 // =============================================================================
1940 //
1941 void GLRenderer::zoomToFit()
1942 {
1943 if (document() == null || m_width == -1 || m_height == -1)
1944 {
1945 zoom() = 30.0f;
1946 return;
1947 }
1948
1949 bool lastfilled = false;
1950 bool firstrun = true;
1951 const uint32 white = 0xFFFFFFFF;
1952 bool inward = true;
1953 const int w = m_width, h = m_height;
1954 int runaway = 50;
1955
1956 glClearColor (1.0, 1.0, 1.0, 1.0);
1957 glDisable (GL_DITHER);
1958
1959 // Use the pick list while drawing the scene, this way we can tell whether borders
1960 // are background or not.
1961 setPicking (true);
1962
1963 while (--runaway)
1964 {
1965 if (zoom() > 10000.0 || zoom() < 0.0)
1966 {
1967 // Obviously, there's nothing to draw if we get here.
1968 // Default to 30.0f and break out.
1969 zoom() = 30.0;
1970 break;
1971 }
1972
1973 zoomNotch (inward);
1974
1975 uchar* cap = new uchar[4 * w * h];
1976 drawGLScene();
1977 glReadPixels (0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, cap);
1978 uint32* imgdata = reinterpret_cast<uint32*> (cap);
1979 bool filled = false;
1980
1981 // Check the top and bottom rows
1982 for (int i = 0; i < w; ++i)
1983 {
1984 if (imgdata[i] != white || imgdata[((h - 1) * w) + i] != white)
1985 {
1986 filled = true;
1987 goto endOfLoop;
1988 }
1989 }
1990
1991 // Left and right edges
1992 for (int i = 0; i < h; ++i)
1993 {
1994 if (imgdata[i * w] != white || imgdata[(i * w) + w - 1] != white)
1995 {
1996 filled = true;
1997 goto endOfLoop;
1998 }
1999 }
2000
2001 endOfLoop:
2002
2003 delete[] cap;
2004
2005 if (firstrun)
2006 {
2007 // If this is the first run, we don't know enough to determine
2008 // whether the zoom was to fit, so we mark in our knowledge so
2009 // far and start over.
2010 inward = !filled;
2011 firstrun = false;
2012 }
2013 else
2014 {
2015 // If this run filled the screen and the last one did not, the
2016 // last run had ideal zoom - zoom a bit back and we should reach it.
2017 if (filled && !lastfilled)
2018 {
2019 zoomNotch (false);
2020 break;
2021 }
2022
2023 // If this run did not fill the screen and the last one did, we've
2024 // now reached ideal zoom so we're done here.
2025 if (!filled && lastfilled)
2026 break;
2027
2028 inward = !filled;
2029 }
2030
2031 lastfilled = filled;
2032 }
2033
2034 setBackground();
2035 setPicking (false);
2036 }
2037
2038 // =============================================================================
2039 //
2040 void GLRenderer::zoomAllToFit()
2041 {
2042 EFixedCamera oldcam = camera();
2043
2044 for (int i = 0; i < 7; ++i)
2045 {
2046 setCamera ((EFixedCamera) i);
2047 zoomToFit();
2048 }
2049
2050 setCamera (oldcam);
2051 }
2052
2053 // =============================================================================
2054 //
2055 void GLRenderer::updateRectVerts()
2056 {
2057 if (!m_rectdraw)
2058 return;
2059
2060 if (m_drawedVerts.isEmpty())
2061 {
2062 for (int i = 0; i < 4; ++i)
2063 m_rectverts[i] = m_hoverpos;
2064
2065 return;
2066 }
2067
2068 Vertex v0 = m_drawedVerts[0],
2069 v1 = (m_drawedVerts.size() >= 2) ? m_drawedVerts[1] : m_hoverpos;
2070
2071 const Axis ax = getCameraAxis (false),
2072 ay = getCameraAxis (true),
2073 az = (Axis) (3 - ax - ay);
2074
2075 for (int i = 0; i < 4; ++i)
2076 m_rectverts[i][az] = getDepthValue();
2077
2078 m_rectverts[0][ax] = v0[ax];
2079 m_rectverts[0][ay] = v0[ay];
2080 m_rectverts[1][ax] = v1[ax];
2081 m_rectverts[1][ay] = v0[ay];
2082 m_rectverts[2][ax] = v1[ax];
2083 m_rectverts[2][ay] = v1[ay];
2084 m_rectverts[3][ax] = v0[ax];
2085 m_rectverts[3][ay] = v1[ay];
2086 }
2087
2088 // =============================================================================
2089 //
2090 void GLRenderer::mouseDoubleClickEvent (QMouseEvent* ev)
2091 {
2092 if (!(ev->buttons() & Qt::LeftButton) || editMode() != ESelectMode)
2093 return;
2094
2095 pick (ev->x(), ev->y());
2096
2097 if (selection().isEmpty())
2098 return;
2099
2100 LDObject* obj = selection().first();
2101 AddObjectDialog::staticDialog (obj->type(), obj);
2102 g_win->endAction();
2103 ev->accept();
2104 }
2105
2106 // =============================================================================
2107 //
2108 LDOverlay* GLRenderer::findOverlayObject (EFixedCamera cam)
2109 {
2110 LDOverlay* ovlobj = null;
2111
2112 for (LDObject* obj : document()->objects())
2113 {
2114 if (obj->type() == LDObject::EOverlay && static_cast<LDOverlay*> (obj)->camera() == cam)
2115 {
2116 ovlobj = static_cast<LDOverlay*> (obj);
2117 break;
2118 }
2119 }
2120
2121 return ovlobj;
2122 }
2123
2124 // =============================================================================
2125 //
2126 // Read in overlays from the current file and update overlay info accordingly.
2127 //
2128 void GLRenderer::initOverlaysFromObjects()
2129 {
2130 for (EFixedCamera cam : g_Cameras)
2131 {
2132 if (cam == EFreeCamera)
2133 continue;
2134
2135 LDGLOverlay& meta = currentDocumentData().overlays[cam];
2136 LDOverlay* ovlobj = findOverlayObject (cam);
2137
2138 if (!ovlobj && meta.img)
2139 {
2140 delete meta.img;
2141 meta.img = null;
2142 }
2143 elif (ovlobj && (!meta.img || meta.fname != ovlobj->fileName()))
2144 setupOverlay (cam, ovlobj->fileName(), ovlobj->x(),
2145 ovlobj->y(), ovlobj->width(), ovlobj->height());
2146 }
2147 }
2148
2149 // =============================================================================
2150 //
2151 void GLRenderer::updateOverlayObjects()
2152 {
2153 for (EFixedCamera cam : g_Cameras)
2154 {
2155 if (cam == EFreeCamera)
2156 continue;
2157
2158 LDGLOverlay& meta = currentDocumentData().overlays[cam];
2159 LDOverlay* ovlobj = findOverlayObject (cam);
2160
2161 if (!meta.img && ovlobj)
2162 {
2163 // If this is the last overlay image, we need to remove the empty space after it as well.
2164 LDObject* nextobj = ovlobj->next();
2165
2166 if (nextobj && nextobj->type() == LDObject::EEmpty)
2167 nextobj->destroy();
2168
2169 // If the overlay object was there and the overlay itself is
2170 // not, remove the object.
2171 ovlobj->destroy();
2172 } elif (meta.img && !ovlobj)
2173 {
2174 // Inverse case: image is there but the overlay object is
2175 // not, thus create the object.
2176 ovlobj = new LDOverlay;
2177
2178 // Find a suitable position to place this object. We want to place
2179 // this into the header, which is everything up to the first scemantic
2180 // object. If we find another overlay object, place this object after
2181 // the last one found. Otherwise, place it before the first schemantic
2182 // object and put an empty object after it (though don't do this if
2183 // there was no schemantic elements at all)
2184 int i, lastOverlay = -1;
2185 bool found = false;
2186
2187 for (i = 0; i < document()->getObjectCount(); ++i)
2188 {
2189 LDObject* obj = document()->getObject (i);
2190
2191 if (obj->isScemantic())
2192 {
2193 found = true;
2194 break;
2195 }
2196
2197 if (obj->type() == LDObject::EOverlay)
2198 lastOverlay = i;
2199 }
2200
2201 if (lastOverlay != -1)
2202 document()->insertObj (lastOverlay + 1, ovlobj);
2203 else
2204 {
2205 document()->insertObj (i, ovlobj);
2206
2207 if (found)
2208 document()->insertObj (i + 1, new LDEmpty);
2209 }
2210 }
2211
2212 if (meta.img && ovlobj)
2213 {
2214 ovlobj->setCamera (cam);
2215 ovlobj->setFileName (meta.fname);
2216 ovlobj->setX (meta.ox);
2217 ovlobj->setY (meta.oy);
2218 ovlobj->setWidth (meta.lw);
2219 ovlobj->setHeight (meta.lh);
2220 }
2221 }
2222
2223 if (g_win->R() == this)
2224 g_win->refresh();
2225 }

mercurial