]> Shamusworld >> Repos - architektonas/blob - src/drawingview.cpp
Added glue layer to Qt painting, to properly render cartesian coordinates.
[architektonas] / src / drawingview.cpp
1 // drawingview.cpp
2 //
3 // Part of the Architektonas Project
4 // (C) 2011 Underground Software
5 // See the README and GPLv3 files for licensing and warranty information
6 //
7 // JLH = James L. Hammons <jlhamm@acm.org>
8 //
9 // Who  When        What
10 // ---  ----------  -------------------------------------------------------------
11 // JLH  03/22/2011  Created this file
12 //
13
14 // FIXED:
15 //
16 //
17 // STILL TO BE DONE:
18 //
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.
21 //
22
23 // Uncomment this for debugging...
24 //#define DEBUG
25 //#define DEBUGFOO                              // Various tool debugging...
26 //#define DEBUGTP                               // Toolpalette debugging...
27
28 #include "drawingview.h"
29
30 #include <stdint.h>
31 #include "mathconstants.h"
32
33 #include "arc.h"
34 #include "circle.h"
35 #include "dimension.h"
36 #include "line.h"
37 #include "painter.h"
38
39
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)
46 {
47         setBackgroundRole(QPalette::Base);
48         setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
49
50 //      toolPalette = new ToolWindow();
51 //      CreateCursors();
52 //      setCursor(cur[TOOLSelect]);
53 //      setMouseTracking(true);
54
55         Line * line = new Line(Vector(5, 5), Vector(50, 40), &document);
56         document.Add(line);
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));
63 #if 1
64         Dimension * dimension = new Dimension(Vector(0, 0), Vector(0, 0), &document);
65         line->SetDimensionOnLine(dimension);
66         document.Add(dimension);
67 #else
68         // Alternate way to do the above...
69         line->SetDimensionOnLine();
70 #endif
71 }
72
73 void DrawingView::SetRotateToolActive(bool state/*= true*/)
74 {
75         rotateTool = state;
76         update();
77 }
78
79 QPoint DrawingView::GetAdjustedMousePosition(QMouseEvent * event)
80 {
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()));
85 }
86
87 QPoint DrawingView::GetAdjustedClientPosition(int x, int y)
88 {
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);
93 }
94
95 void DrawingView::paintEvent(QPaintEvent * /*event*/)
96 {
97         QPainter qtPainter(this);
98         Painter painter(&qtPainter);
99
100         if (useAntialiasing)
101                 qtPainter.setRenderHint(QPainter::Antialiasing);
102
103         Painter::screenSize = Vector(size().width(), size().height());
104 #if 0
105 #if 0
106         painter.translate(QPoint(-offsetX, size.height() - (-offsetY)));
107         painter.scale(1.0, -1.0);
108 #else
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);
117 #endif
118 #endif
119         Object::SetViewportHeight(size().height());
120
121         // Draw coordinate axes
122
123         painter.SetPen(QPen(Qt::blue, 1.0, Qt::DotLine));
124         painter.DrawLine(0, -16384, 0, 16384);
125         painter.DrawLine(-16384, 0, 16384, 0);
126
127         // Draw supplemental (tool related) points
128
129         if (rotateTool)
130         {
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);
134         }
135
136 // Maybe we can make the grid into a background brush instead, and let Qt deal
137 // with it???
138         // Draw grid
139
140 #if 0
141         painter.setPen(QPen(QColor(90, 90, 90), 1.0, Qt::DotLine));
142
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);
147
148         for(double y=0; y<size().height(); y+=gridSpacing*10.0)
149                 painter.drawLine(-16384, (int)y, 16384, (int)y);
150 #endif
151
152         painter.SetPen(QPen(Qt::black, 1.0, Qt::SolidLine));
153
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);
157
158         // The top level document takes care of rendering for us...
159         document.Draw(&painter);
160 }
161
162 void DrawingView::mousePressEvent(QMouseEvent * event)
163 {
164         if (event->button() == Qt::LeftButton)
165         {
166                 QPoint pt = GetAdjustedMousePosition(event);
167                 Vector point(pt.x(), pt.y());
168
169                 collided = document.Collided(point);
170
171                 if (collided)
172                         update();       // Do an update if collided with at least *one* object in the document
173         }
174 }
175
176 void DrawingView::mouseMoveEvent(QMouseEvent * event)
177 {
178         QPoint pt = GetAdjustedMousePosition(event);
179         Vector point(pt.x(), pt.y());
180
181         // Grid processing...
182 #if 1
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)
190         {
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;
197         }
198 #endif
199 //we should keep track of the last point here and only pass this down *if* the point
200 //changed...
201         document.PointerMoved(point);
202
203         if (document.NeedsUpdate())
204                 update();
205 }
206
207 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
208 {
209         if (event->button() == Qt::LeftButton)
210         {
211                 document.PointerReleased();
212
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())
217 //              if (collided)
218                         update();       // Do an update if collided with at least *one* object in the document
219         }
220 }
221
222
223 #if 0
224 QSize DrawingView::minimumSizeHint() const
225 {
226         return QSize(50, 50);
227 }
228
229 QSize DrawingView::sizeHint() const
230 {
231         return QSize(400, 400);
232 }
233
234 void DrawingView::CreateCursors(void)
235 {
236         int hotx[8] = {  1,  1, 11, 15,  1,  1,  1,  1 };
237         int hoty[8] = {  1,  1, 11, 13,  1,  1,  1,  1 };
238
239         for(int i=0; i<8; i++)
240         {
241                 QString s;
242                 s.sprintf(":/res/cursor%u.png", i+1);
243                 QPixmap pmTmp(s);
244                 cur[i] = QCursor(pmTmp, hotx[i], hoty[i]);
245         }
246 }
247
248 /*
249 TODO:
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
254 */
255 void DrawingView::paintEvent(QPaintEvent * /*event*/)
256 {
257         QPainter p(this);
258 //hm, causes lockup
259 //      p.setRenderHint(QPainter::Antialiasing);
260 //Doesn't do crap!
261 //dc.SetBackground(*wxWHITE_BRUSH);
262
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();
268
269 //      dc.SetDeviceOrigin(-offsetX, height - (-offsetY));
270 //      dc.SetAxisOrientation(true, true);
271         p.translate(QPoint(-offsetX, winSize.height() - (-offsetY)));
272         p.scale(1.0, -1.0);
273
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...
280
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));
284
285     // Draw coordinate axes
286
287 //      dc.CrossHair(0, 0);
288         p.drawLine(0, -16384, 0, 16384);
289         p.drawLine(-16384, 0, 16384, 0);
290
291     // Draw points
292
293         for(int i=0; i<pts.GetNumPoints(); i++)
294         {
295                 if (i == ptHighlight)
296                 {
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));
300
301                         if (pts.GetOnCurve(i))
302                         {
303                                 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
304                                 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
305                         }
306                         else
307                         {
308                                 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
309                                 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
310                         }
311                 }
312                 else if ((i == ptHighlight || i == ptNextHighlight) && tool == TOOLAddPt)
313                 {
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));
317
318                         if (pts.GetOnCurve(i))
319                         {
320                                 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 7);
321                                 DrawSquareDotN(p, pts.GetX(i), pts.GetY(i), 9);
322                         }
323                         else
324                         {
325                                 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 7);
326                                 DrawRoundDotN(p, pts.GetX(i), pts.GetY(i), 9);
327                         }
328                 }
329                 else
330                 {
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));
334
335                         if (pts.GetOnCurve(i))
336                                 DrawSquareDot(p, pts.GetX(i), pts.GetY(i));
337                         else
338                                 DrawRoundDot(p, pts.GetX(i), pts.GetY(i));
339                 }
340
341                 if (tool == TOOLDelPt && i == ptHighlight)
342                 {
343 #if 0
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!!
352 #endif
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);
356                 }
357         }
358
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));
362
363         // Draw curve formed by points
364
365         for(int poly=0; poly<pts.GetNumPolys(); poly++)
366         {
367                 if (pts.GetNumPoints(poly) > 2)
368                 {
369                         // Initial move...
370                         // If it's not on curve, then move to it, otherwise move to last point...
371
372                         int x, y;
373
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);
376                         else
377                                 x = (int)pts.GetX(poly, 0), y = (int)pts.GetY(poly, 0);
378
379                         for(int i=0; i<pts.GetNumPoints(poly); i++)
380                         {
381                                 if (pts.GetOnCurve(poly, i))
382 //                                      LineTo(hdc, pts.GetX(poly, i), pts.GetY(poly, i));
383                                 {
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);
386                                 }
387                                 else
388                                 {
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);
392
393                                         if (!pts.GetOnCurve(poly, prev))
394                                                 px = (px + pts.GetX(poly, i)) / 2.0f,
395                                                 py = (py + pts.GetY(poly, i)) / 2.0f;
396
397                                         if (!pts.GetOnCurve(poly, next))
398                                                 nx = (nx + pts.GetX(poly, i)) / 2.0f,
399                                                 ny = (ny + pts.GetY(poly, i)) / 2.0f;
400
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;
403
404                                         if (pts.GetOnCurve(poly, next))
405                                                 i++;                                    // Following point is on curve, so move past it
406                                 }
407                         }
408                 }
409         }
410 }
411
412 void DrawingView::mousePressEvent(QMouseEvent * event)
413 {
414         if (event->button() == Qt::RightButton)
415         {
416                 toolPalette->move(event->globalPos());
417                 toolPalette->setVisible(true);
418                 setCursor(cur[TOOLSelect]);
419                 toolPalette->prevTool = TOOLSelect;
420         }
421         else if (event->button() == Qt::MidButton)
422         {
423                 setCursor(cur[2]);                                                      // Scrolling cursor
424         }
425         else if (event->button() == Qt::LeftButton)
426         {
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
430                 {
431                         if (pts.GetNumPoints() > 0)
432                         {
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;
436                                 update();
437                         }
438                 }
439                 else if (tool == TOOLAddPoly)   // "Add Poly" tool
440                 {
441 #ifdef DEBUGFOO
442 WriteLogMsg("Adding point... # polys: %u, # points: %u", pts.GetNumPolys(), pts.GetNumPoints());
443 #endif
444                         if (polyFirstPoint)
445                         {
446                                 polyFirstPoint = false;
447                                 pts.AddNewPolyAtEnd();
448                         }
449
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;
455                         update();
456 #ifdef DEBUGFOO
457 WriteLogMsg(" --> [# polys: %u, # points: %u]\n", pts.GetNumPolys(), pts.GetNumPoints());
458 #endif
459                 }
460                 else if (tool == TOOLSelect || tool == TOOLPolySelect)
461                 {
462                         if (pts.GetNumPoints() > 0)
463                         {
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));
468
469                                 if (event->modifiers() == Qt::ShiftModifier || event->modifiers() == Qt::ControlModifier)
470                                 {
471                                         pts.SetOnCurve(ptHighlight, !pts.GetOnCurve(ptHighlight));
472                                         update();
473                                 }
474                         }
475                 }
476                 else if (tool == TOOLDelPt)
477                 {
478                         if (pts.GetNumPoints() > 0)
479 //Or could use:
480 //                      if (ptHighlight != -1)
481                         {
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);
485                                 update();
486                         }
487                 }
488         }
489
490         event->accept();
491 }
492
493 void DrawingView::mouseMoveEvent(QMouseEvent * event)
494 {
495         if (event->buttons() == Qt::RightButton)
496         {
497                 ToolType newTool = toolPalette->FindSelectedTool();
498
499                 if (newTool != toolPalette->prevTool)
500                 {
501                         toolPalette->prevTool = newTool;
502                         toolPalette->repaint();
503                 }
504         }
505         else if (event->buttons() == Qt::MidButton)
506         {
507                 // Calc offset from previous point
508                 pt = event->pos();
509                 ptOffset = QPoint(pt.x() - ptPrevious.x(), pt.y() - ptPrevious.y());
510
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();
515                 update();
516                 ptPrevious = pt;
517         }
518         else if (event->buttons() == Qt::LeftButton)
519         {
520 #if 0
521                         if (tool == TOOLScroll)
522                         {
523                             // Extract current point from lParam/calc offset from previous point
524
525                                 pt = e.GetPosition();
526                                 ptOffset.x = pt.x - ptPrevious.x,
527                                 ptOffset.y = pt.y - ptPrevious.y;
528
529                                 // NOTE: OffsetViewportOrg operates in DEVICE UNITS...
530
531 //Seems there's no equivalent for this in wxWidgets...!
532 //!!! FIX !!!
533 //                              hdc = GetDC(hWnd);
534 //                              OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, NULL);
535 //                              ReleaseDC(hWnd, hdc);
536
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...
539 // Above: DONE
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;
544                                 Refresh();
545                         }
546                         else
547 #endif
548                         if (tool == TOOLAddPt || tool == TOOLAddPoly || tool == TOOLSelect)
549                         {
550                                 if (tool != TOOLAddPt || pts.GetNumPoints() > 0)//yecch.
551                                 {
552 //temporary, for testing. BTW, Select drag bug is here...!
553 #if 1
554                                         QPoint pt2 = GetAdjustedMousePosition(event);
555                                         pts.SetXY(ptHighlight, pt2.x(), pt2.y());
556                                         update();
557 #endif
558                                 }
559                         }
560                         else if (tool == TOOLPolySelect)
561                         {
562                                 if (pts.GetNumPoints() > 0)
563                                 {
564                                         QPoint pt2 = GetAdjustedMousePosition(event);
565                                         // Should also set onCurve here as well, depending on keystate
566 //Or should we?
567                                         pts.OffsetPoly(pts.GetPoly(ptHighlight), pt2.x() - pts.GetX(ptHighlight), pt2.y() - pts.GetY(ptHighlight));
568                                         update();
569                                 }
570                         }
571         }
572         else if (event->buttons() == Qt::NoButton)
573         {
574                 // Moving, not dragging...
575                 if (tool == TOOLSelect || tool == TOOLDelPt || tool == TOOLAddPt
576                         || tool == TOOLPolySelect)// || tool == TOOLAddPoly)
577                 {
578                         QPoint pt2 = GetAdjustedMousePosition(event);
579                         double closest = 1.0e+99;
580
581                         for(int i=0; i<pts.GetNumPoints(); i++)
582                         {
583                                 double dist = ((pt2.x() - pts.GetX(i)) * (pt2.x() - pts.GetX(i)))
584                                         + ((pt2.y() - pts.GetY(i)) * (pt2.y() - pts.GetY(i)));
585
586                                 if (dist < closest)
587                                         closest = dist, ptHighlight = i;
588                         }
589
590                         if (ptHighlight != oldPtHighlight)
591                         {
592                                 oldPtHighlight = ptHighlight;
593                                 update();
594                         }
595
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.
602
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).
605
606                         if (pts.GetNumPoints() > 1 && tool == TOOLAddPt)
607                         {
608                                 double smallest = 1.0e+99;
609
610                                 for(int i=0; i<pts.GetNumPoints(); i++)
611                                 {
612                                         int32 p1x = pts.GetX(i), p1y = pts.GetY(i),
613                                                 p2x = pts.GetX(pts.GetNext(i)), p2y = pts.GetY(pts.GetNext(i));
614
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.
622
623                                         if (pp < 0.0)
624                                                 dist = v1.length();
625                                         else if (pp > ls.length())
626                                                 dist = v2.length();
627                                         else                                    // distance = ?Det?(ls, v1) / |ls|
628                                                 dist = fabs((ls.x * v1.y - v1.x * ls.y) / ls.length());
629
630 //The answer to the above looks like it might be found here:
631 //
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:
638 //
639 //sx sy 1
640 //ex ey 1
641 //px py 1
642 //
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!]
647 //
648 //0         0         0
649 //(ex - sx) (ey - sy) 0
650 //(px - sx) (py - sy) 0
651 //
652 //which greatly simplifies the calculation of the determinant.
653
654                                         if (dist < smallest)
655                                                 smallest = dist, ptNextHighlight = pts.GetNext(i), ptHighlight = i;
656                                 }
657
658                                 if (ptNextHighlight != oldPtNextHighlight)
659                                 {
660                                         oldPtNextHighlight = ptNextHighlight;
661                                         update();
662                                 }
663                         }
664                 }
665
666                 ptPrevious = event->pos();
667         }
668
669         event->accept();
670 }
671
672 void DrawingView::mouseReleaseEvent(QMouseEvent * event)
673 {
674         if (event->button() == Qt::RightButton)
675         {
676                 ToolType newTool = toolPalette->FindSelectedTool();
677
678                 // We only change the tool if a new one was actually selected. Otherwise, we do nothing.
679                 if (newTool != TOOLNone)
680                 {
681                         tool = newTool;
682
683                         if (tool == TOOLScroll || tool == TOOLZoom || tool == TOOLAddPoly
684                                 || tool == TOOLDelPoly)
685                                 ptHighlight = -1;
686
687                         if (tool == TOOLAddPoly)
688                                 polyFirstPoint = true;
689                 }
690
691                 toolPalette->setVisible(false);
692                 setCursor(cur[tool]);
693                 // Just in case we changed highlighting style with the new tool...
694                 update();
695         }
696         else if (event->button() == Qt::MidButton)
697         {
698                 setCursor(cur[tool]);                                           // Restore previous cursor
699         }
700         else if (event->button() == Qt::LeftButton)
701         {
702 //              if (tool == TOOLScroll || tool == TOOLZoom)
703 //                      ReleaseMouse();
704 //this is prolly too much
705                 ((TTEdit *)qApp)->charWnd->MakePathFromPoints(&pts);
706                 ((TTEdit *)qApp)->charWnd->update();
707         }
708
709         event->accept();
710 }
711 #endif