3 // Part of the Architektonas Project
4 // (C) 2011 Underground Software
5 // See the README and GPLv3 files for licensing and warranty information
7 // JLH = James L. Hammons <jlhamm@acm.org>
10 // --- ---------- -------------------------------------------------------------
11 // JLH 03/22/2011 Created this file
19 // - Redo rendering code to *not* use Qt's transform functions, as they are tied
20 // to a left-handed system and we need a right-handed one.
23 // Uncomment this for debugging...
25 //#define DEBUGFOO // Various tool debugging...
26 //#define DEBUGTP // Toolpalette debugging...
28 #include "drawingview.h"
31 #include "mathconstants.h"
35 #include "dimension.h"
40 DrawingView::DrawingView(QWidget * parent/*= NULL*/): QWidget(parent),
41 // The value in the settings file will override this.
42 useAntialiasing(true),
43 scale(1.0), offsetX(-10), offsetY(-10),
44 document(Vector(0, 0)),
45 gridSpacing(32.0), collided(false), rotateTool(false), rx(150.0), ry(150.0)
47 setBackgroundRole(QPalette::Base);
48 setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
50 // toolPalette = new ToolWindow();
52 // setCursor(cur[TOOLSelect]);
53 // setMouseTracking(true);
55 Line * line = new Line(Vector(5, 5), Vector(50, 40), &document);
57 document.Add(new Line(Vector(50, 40), Vector(10, 83), &document));
58 document.Add(new Line(Vector(10, 83), Vector(17, 2), &document));
59 document.Add(new Circle(Vector(100, 100), 36, &document));
60 document.Add(new Circle(Vector(50, 150), 49, &document));
61 document.Add(new Arc(Vector(300, 300), 32, PI / 4.0, PI * 1.3, &document)),
62 document.Add(new Arc(Vector(200, 200), 60, PI / 2.0, PI * 1.5, &document));
64 Dimension * dimension = new Dimension(Vector(0, 0), Vector(0, 0), &document);
65 line->SetDimensionOnLine(dimension);
66 document.Add(dimension);
68 // Alternate way to do the above...
69 line->SetDimensionOnLine();
73 void DrawingView::SetRotateToolActive(bool state/*= true*/)
79 QPoint DrawingView::GetAdjustedMousePosition(QMouseEvent * event)
81 // This is undoing the transform, e.g. going from client coords to local coords.
82 // In essence, the height - y is height + (y * -1), the (y * -1) term doing the
83 // conversion of the y-axis from increasing bottom to top.
84 return QPoint(offsetX + event->x(), offsetY + (size().height() - event->y()));
87 QPoint DrawingView::GetAdjustedClientPosition(int x, int y)
89 // VOODOO ALERT (ON Y COMPONENT!!!!) (eh?)
90 // No voodoo here, it's just grouped wrong to see it. It should be:
91 // -offsetY + (size.height() + (y * -1.0)) <-- this is wrong, offsetY should be positive
92 return QPoint(-offsetX + x, (size().height() - (-offsetY + y)) * +1.0);
95 void DrawingView::paintEvent(QPaintEvent * /*event*/)
97 QPainter qtPainter(this);
98 Painter painter(&qtPainter);
101 qtPainter.setRenderHint(QPainter::Antialiasing);
103 Painter::screenSize = Vector(size().width(), size().height());
106 painter.translate(QPoint(-offsetX, size.height() - (-offsetY)));
107 painter.scale(1.0, -1.0);
109 QTransform transform;
110 //order of operations is important! N.B.: Can't use scaling other than 1.0, it
111 //causes lines to look strange (i.e., it scales the pen strokes too)
112 // transform.translate(-offsetX, size().height() - (-offsetY));
113 transform.scale(1.0, -1.0);
114 transform.translate(-offsetX, -size().height() - offsetY);
115 // transform.scale(0.25, 0.25);
116 painter.setTransform(transform);
119 Object::SetViewportHeight(size().height());
121 // Draw coordinate axes
123 painter.SetPen(QPen(Qt::blue, 1.0, Qt::DotLine));
124 painter.DrawLine(0, -16384, 0, 16384);
125 painter.DrawLine(-16384, 0, 16384, 0);
127 // Draw supplemental (tool related) points
131 painter.SetPen(QPen(QColor(0, 200, 0), 2.0, Qt::SolidLine));
132 painter.DrawLine(rx - 10, ry, rx + 10, ry);
133 painter.DrawLine(rx, ry - 10, rx, ry + 10);
136 // Maybe we can make the grid into a background brush instead, and let Qt deal
141 painter.setPen(QPen(QColor(90, 90, 90), 1.0, Qt::DotLine));
143 //these two loops kill performance!
144 // Also, these overwrite our coordinate axes
145 for(double x=0; x<size().width(); x+=gridSpacing*10.0)
146 painter.drawLine((int)x, -16384, (int)x, 16384);
148 for(double y=0; y<size().height(); y+=gridSpacing*10.0)
149 painter.drawLine(-16384, (int)y, 16384, (int)y);
152 painter.SetPen(QPen(Qt::black, 1.0, Qt::SolidLine));
154 for(double x=0; x<size().width(); x+=gridSpacing)
155 for(double y=0; y<size().height(); y+=gridSpacing)
156 painter.DrawPoint((int)x, (int)y);
158 // The top level document takes care of rendering for us...
159 document.Draw(&painter);
162 void DrawingView::mousePressEvent(QMouseEvent * event)
164 if (event->button() == Qt::LeftButton)
166 QPoint pt = GetAdjustedMousePosition(event);
167 Vector point(pt.x(), pt.y());
169 collided = document.Collided(point);
172 update(); // Do an update if collided with at least *one* object in the document
176 void DrawingView::mouseMoveEvent(QMouseEvent * event)
178 QPoint pt = GetAdjustedMousePosition(event);
179 Vector point(pt.x(), pt.y());
181 // Grid processing...
183 // This looks strange, but it's really quite simple: We want a point that's
184 // more than half-way to the next grid point to snap there while conversely
185 // we want a point that's less than half-way to to the next grid point then
186 // snap to the one before it. So we add half of the grid spacing to the
187 // point, then divide by it so that we can remove the fractional part, then
188 // multiply it back to get back to the correct answer.
189 if (event->buttons() & Qt::LeftButton)
191 point += gridSpacing / 2.0; // *This* adds to Z!!!
192 point /= gridSpacing;
193 point.x = floor(point.x);//need to fix this for negative numbers...
194 point.y = floor(point.y);
195 point.z = 0; // Make *sure* Z doesn't go anywhere!!!
196 point *= gridSpacing;
199 //we should keep track of the last point here and only pass this down *if* the point
201 document.PointerMoved(point);
203 if (document.NeedsUpdate())
207 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
209 if (event->button() == Qt::LeftButton)
211 document.PointerReleased();
213 //We need to update especially if nothing collided and the state needs to change. !!! FIX !!!
214 //could set it up to use the document's update function (assumes that all object updates
215 //are being reported correctly:
216 // if (document.NeedsUpdate())
218 update(); // Do an update if collided with at least *one* object in the document
224 QSize DrawingView::minimumSizeHint() const
226 return QSize(50, 50);
229 QSize DrawingView::sizeHint() const
231 return QSize(400, 400);
234 void DrawingView::CreateCursors(void)
236 int hotx[8] = { 1, 1, 11, 15, 1, 1, 1, 1 };
237 int hoty[8] = { 1, 1, 11, 13, 1, 1, 1, 1 };
239 for(int i=0; i<8; i++)
242 s.sprintf(":/res/cursor%u.png", i+1);
244 cur[i] = QCursor(pmTmp, hotx[i], hoty[i]);
250 o Different colors for polys on selected points
251 o Different colors for handles on non-selected polys
252 o Line of sight (dashed, dotted) for off-curve points
253 o Repaints for press/release of CTRL/SHIFT during point creation
255 void DrawingView::paintEvent(QPaintEvent * /*event*/)
259 // p.setRenderHint(QPainter::Antialiasing);
261 //dc.SetBackground(*wxWHITE_BRUSH);
263 // Due to the screwiness of wxWidgets coord system, the origin is ALWAYS
264 // the upper left corner--regardless of axis orientation, etc...
265 // int width, height;
266 // dc.GetSize(&width, &height);
267 QSize winSize = size();
269 // dc.SetDeviceOrigin(-offsetX, height - (-offsetY));
270 // dc.SetAxisOrientation(true, true);
271 p.translate(QPoint(-offsetX, winSize.height() - (-offsetY)));
274 // Scrolling can be done by using OffsetViewportOrgEx
275 // Scaling can be done by adjusting SetWindowExtEx (it's denominator of txform)
276 // you'd use: % = ViewportExt / WindowExt
277 // But it makes the window look like crap: fuggetuboutit.
278 // Instead, we have to scale EVERYTHING by hand. Crap!
279 // It's not *that* bad, but not as convenient either...
281 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0xFF), 1, wxDOT)));
282 //// dc.DrawLine(0, 0, 10, 10);
283 p.setPen(QPen(Qt::blue, 1.0, Qt::DotLine));
285 // Draw coordinate axes
287 // dc.CrossHair(0, 0);
288 p.drawLine(0, -16384, 0, 16384);
289 p.drawLine(-16384, 0, 16384, 0);
293 for(int i=0; i<pts.GetNumPoints(); i++)
295 if (i == ptHighlight)
297 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
298 //// SelectObject(hdc, hRedPen1);
299 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
301 if (pts.GetOnCurve(i))
303 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
304 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
308 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
309 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
312 else if ((i == ptHighlight || i == ptNextHighlight) && tool == TOOLAddPt)
314 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0xAF, 0x00), 1, wxSOLID)));
315 //// SelectObject(hdc, hGreenPen1);
316 p.setPen(QPen(Qt::green, 1.0, Qt::SolidLine));
318 if (pts.GetOnCurve(i))
320 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
321 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
325 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
326 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
331 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
332 //// SelectObject(hdc, hBlackPen1);
333 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
335 if (pts.GetOnCurve(i))
336 DrawSquareDot(p, pts.GetX(i), pts.GetY(i));
338 DrawRoundDot(p, pts.GetX(i), pts.GetY(i));
341 if (tool == TOOLDelPt && i == ptHighlight)
344 dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0xFF, 0x00, 0x00), 1, wxSOLID)));
345 // SelectObject(hdc, hRedPen1);
346 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5, NULL);
347 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) + 5);
348 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) - 5);//Lameness!
349 // MoveToEx(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5, NULL);
350 // LineTo(hdc, pts.GetX(i) + 5, pts.GetY(i) - 5);
351 // LineTo(hdc, pts.GetX(i) - 5, pts.GetY(i) + 5);//More lameness!!
353 p.setPen(QPen(Qt::red, 1.0, Qt::SolidLine));
354 p.drawLine(pts.GetX(i) - 5, pts.GetY(i) - 5, pts.GetX(i) + 5, pts.GetY(i) + 5);
355 p.drawLine(pts.GetX(i) + 5, pts.GetY(i) - 5, pts.GetX(i) - 5, pts.GetY(i) + 5);
359 //// SelectObject(hdc, hBlackPen1);
360 // dc.SetPen(*(wxThePenList->FindOrCreatePen(wxColour(0x00, 0x00, 0x00), 1, wxSOLID)));
361 p.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
363 // Draw curve formed by points
365 for(int poly=0; poly<pts.GetNumPolys(); poly++)
367 if (pts.GetNumPoints(poly) > 2)
370 // If it's not on curve, then move to it, otherwise move to last point...
374 if (pts.GetOnCurve(poly, pts.GetNumPoints(poly) - 1))
375 x = (int)pts.GetX(poly, pts.GetNumPoints(poly) - 1), y = (int)pts.GetY(poly, pts.GetNumPoints(poly) - 1);
377 x = (int)pts.GetX(poly, 0), y = (int)pts.GetY(poly, 0);
379 for(int i=0; i<pts.GetNumPoints(poly); i++)
381 if (pts.GetOnCurve(poly, i))
382 // LineTo(hdc, pts.GetX(poly, i), pts.GetY(poly, i));
384 p.drawLine(x, y, pts.GetX(poly, i), pts.GetY(poly, i));
385 x = (int)pts.GetX(poly, i), y = (int)pts.GetY(poly, i);
389 uint32 prev = pts.GetPrev(poly, i), next = pts.GetNext(poly, i);
390 float px = pts.GetX(poly, prev), py = pts.GetY(poly, prev),
391 nx = pts.GetX(poly, next), ny = pts.GetY(poly, next);
393 if (!pts.GetOnCurve(poly, prev))
394 px = (px + pts.GetX(poly, i)) / 2.0f,
395 py = (py + pts.GetY(poly, i)) / 2.0f;
397 if (!pts.GetOnCurve(poly, next))
398 nx = (nx + pts.GetX(poly, i)) / 2.0f,
399 ny = (ny + pts.GetY(poly, i)) / 2.0f;
401 Bezier(p, point(px, py), point(pts.GetX(poly, i), pts.GetY(poly, i)), point(nx, ny));
402 x = (int)nx, y = (int)ny;
404 if (pts.GetOnCurve(poly, next))
405 i++; // Following point is on curve, so move past it
412 void DrawingView::mousePressEvent(QMouseEvent * event)
414 if (event->button() == Qt::RightButton)
416 toolPalette->move(event->globalPos());
417 toolPalette->setVisible(true);
418 setCursor(cur[TOOLSelect]);
419 toolPalette->prevTool = TOOLSelect;
421 else if (event->button() == Qt::MidButton)
423 setCursor(cur[2]); // Scrolling cursor
425 else if (event->button() == Qt::LeftButton)
427 if (tool == TOOLScroll || tool == TOOLZoom)
428 ;//meh CaptureMouse(); // Make sure we capture the mouse when in scroll/zoom mode
429 else if (tool == TOOLAddPt) // "Add Point" tool
431 if (pts.GetNumPoints() > 0)
433 QPoint pt = GetAdjustedMousePosition(event);
434 pts.InsertPoint(pts.GetNext(ptHighlight), pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
435 ptHighlight = ptNextHighlight;
439 else if (tool == TOOLAddPoly) // "Add Poly" tool
442 WriteLogMsg("Adding point... # polys: %u, # points: %u", pts.GetNumPolys(), pts.GetNumPoints());
446 polyFirstPoint = false;
447 pts.AddNewPolyAtEnd();
450 QPoint pt = GetAdjustedMousePosition(event);
451 //printf("GetAdjustedMousePosition = %i, %i\n", pt.x(), pt.y());
452 // Append a point to the end of the structure
453 pts += IPoint(pt.x(), pt.y(), ((event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier) ? false : true));
454 ptHighlight = pts.GetNumPoints() - 1;
457 WriteLogMsg(" --> [# polys: %u, # points: %u]\n", pts.GetNumPolys(), pts.GetNumPoints());
460 else if (tool == TOOLSelect || tool == TOOLPolySelect)
462 if (pts.GetNumPoints() > 0)
464 pt = GetAdjustedClientPosition(pts.GetX(ptHighlight), pts.GetY(ptHighlight));
465 //printf("GetAdjustedClientPosition = %i, %i\n", pt.x(), pt.y());
466 // WarpPointer(pt.x, pt.y);
467 QCursor::setPos(mapToGlobal(pt));
469 if (event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier)
471 pts.SetOnCurve(ptHighlight, !pts.GetOnCurve(ptHighlight));
476 else if (tool == TOOLDelPt)
478 if (pts.GetNumPoints() > 0)
480 // if (ptHighlight != -1)
482 //This assumes that WM_MOUSEMOVE happens before this!
483 //The above commented out line should take care of this contingency... !!! FIX !!!
484 pts.DeletePoint(ptHighlight);
493 void DrawingView::mouseMoveEvent(QMouseEvent * event)
495 if (event->buttons() == Qt::RightButton)
497 ToolType newTool = toolPalette->FindSelectedTool();
499 if (newTool != toolPalette->prevTool)
501 toolPalette->prevTool = newTool;
502 toolPalette->repaint();
505 else if (event->buttons() == Qt::MidButton)
507 // Calc offset from previous point
509 ptOffset = QPoint(pt.x() - ptPrevious.x(), pt.y() - ptPrevious.y());
511 // Then multiply it by the scaling factor. Whee!
512 // This looks wacky because we're using screen coords for the offset...
513 // Otherwise, we would subtract both offsets!
514 offsetX -= ptOffset.x(), offsetY += ptOffset.y();
518 else if (event->buttons() == Qt::LeftButton)
521 if (tool == TOOLScroll)
523 // Extract current point from lParam/calc offset from previous point
525 pt = e.GetPosition();
526 ptOffset.x = pt.x - ptPrevious.x,
527 ptOffset.y = pt.y - ptPrevious.y;
529 // NOTE: OffsetViewportOrg operates in DEVICE UNITS...
531 //Seems there's no equivalent for this in wxWidgets...!
533 // hdc = GetDC(hWnd);
534 // OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, NULL);
535 // ReleaseDC(hWnd, hdc);
537 // this shows that it works, so the logic above must be faulty...
538 // And it is. It should convert the coords first, then do the subtraction to figure the offset...
540 // Then multiply it by the scaling factor. Whee!
541 // This looks wacky because we're using screen coords for the offset...
542 // Otherwise, we would subtract both offsets!
543 offsetX -= ptOffset.x, offsetY += ptOffset.y;
548 if (tool == TOOLAddPt || tool == TOOLAddPoly || tool == TOOLSelect)
550 if (tool != TOOLAddPt || pts.GetNumPoints() > 0)//yecch.
552 //temporary, for testing. BTW, Select drag bug is here...!
554 QPoint pt2 = GetAdjustedMousePosition(event);
555 pts.SetXY(ptHighlight, pt2.x(), pt2.y());
560 else if (tool == TOOLPolySelect)
562 if (pts.GetNumPoints() > 0)
564 QPoint pt2 = GetAdjustedMousePosition(event);
565 // Should also set onCurve here as well, depending on keystate
567 pts.OffsetPoly(pts.GetPoly(ptHighlight), pt2.x() - pts.GetX(ptHighlight), pt2.y() - pts.GetY(ptHighlight));
572 else if (event->buttons() == Qt::NoButton)
574 // Moving, not dragging...
575 if (tool == TOOLSelect || tool == TOOLDelPt || tool == TOOLAddPt
576 || tool == TOOLPolySelect)// || tool == TOOLAddPoly)
578 QPoint pt2 = GetAdjustedMousePosition(event);
579 double closest = 1.0e+99;
581 for(int i=0; i<pts.GetNumPoints(); i++)
583 double dist = ((pt2.x() - pts.GetX(i)) * (pt2.x() - pts.GetX(i)))
584 + ((pt2.y() - pts.GetY(i)) * (pt2.y() - pts.GetY(i)));
587 closest = dist, ptHighlight = i;
590 if (ptHighlight != oldPtHighlight)
592 oldPtHighlight = ptHighlight;
596 // What follows here looks like voodoo, but is really simple. What we do is
597 // check to see if the mouse point has a perpendicular intersection with any of
598 // the line segments. If it does, calculate the length of the perpendicular
599 // and choose the smallest length. If there is no perpendicular, then choose the
600 // length of line connecting the closer of either the first endpoint or the
601 // second and choose the smallest of those.
603 // There is one bit of math that looks like voodoo to me ATM--will explain once
604 // I understand it better (the calculation of the length of the perpendicular).
606 if (pts.GetNumPoints() > 1 && tool == TOOLAddPt)
608 double smallest = 1.0e+99;
610 for(int i=0; i<pts.GetNumPoints(); i++)
612 int32 p1x = pts.GetX(i), p1y = pts.GetY(i),
613 p2x = pts.GetX(pts.GetNext(i)), p2y = pts.GetY(pts.GetNext(i));
615 vector ls(p2x, p2y, 0, p1x, p1y, 0), v1(pt2.x(), pt2.y(), 0, p1x, p1y, 0),
616 v2(pt2.x(), pt2.y(), 0, p2x, p2y, 0);
617 double pp = ls.dot(v1) / ls.length(), dist;
618 // Geometric interpretation:
619 // pp is the paremeterized point on the vector ls where the perpendicular intersects ls.
620 // If pp < 0, then the perpendicular lies beyond the 1st endpoint. If pp > length of ls,
621 // then the perpendicular lies beyond the 2nd endpoint.
625 else if (pp > ls.length())
627 else // distance = ?Det?(ls, v1) / |ls|
628 dist = fabs((ls.x * v1.y - v1.x * ls.y) / ls.length());
630 //The answer to the above looks like it might be found here:
632 //If the segment endpoints are s and e, and the point is p, then the test for the perpendicular
633 //intercepting the segment is equivalent to insisting that the two dot products {s-e}.{s-p} and
634 //{e-s}.{e-p} are both non-negative. Perpendicular distance from the point to the segment is
635 //computed by first computing the area of the triangle the three points form, then dividing by the
636 //length of the segment. Distances are done just by the Pythagorean theorem. Twice the area of the
637 //triangle formed by three points is the determinant of the following matrix:
643 //By translating the start point to the origin, this can be rewritten as:
644 //By subtracting row 1 from all rows, you get the following:
645 //[because sx = sy = 0. you could leave out the -sx/y terms below. because we subtracted
646 // row 1 from all rows (including row 1) row 1 turns out to be zero. duh!]
649 //(ex - sx) (ey - sy) 0
650 //(px - sx) (py - sy) 0
652 //which greatly simplifies the calculation of the determinant.
655 smallest = dist, ptNextHighlight = pts.GetNext(i), ptHighlight = i;
658 if (ptNextHighlight != oldPtNextHighlight)
660 oldPtNextHighlight = ptNextHighlight;
666 ptPrevious = event->pos();
672 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
674 if (event->button() == Qt::RightButton)
676 ToolType newTool = toolPalette->FindSelectedTool();
678 // We only change the tool if a new one was actually selected. Otherwise, we do nothing.
679 if (newTool != TOOLNone)
683 if (tool == TOOLScroll || tool == TOOLZoom || tool == TOOLAddPoly
684 || tool == TOOLDelPoly)
687 if (tool == TOOLAddPoly)
688 polyFirstPoint = true;
691 toolPalette->setVisible(false);
692 setCursor(cur[tool]);
693 // Just in case we changed highlighting style with the new tool...
696 else if (event->button() == Qt::MidButton)
698 setCursor(cur[tool]); // Restore previous cursor
700 else if (event->button() == Qt::LeftButton)
702 // if (tool == TOOLScroll || tool == TOOLZoom)
704 //this is prolly too much
705 ((TTEdit *)qApp)->charWnd->MakePathFromPoints(&pts);
706 ((TTEdit *)qApp)->charWnd->update();