Better document which members can be set when writing
[survex.git] / src / gfxcore.cc
blob82064db354648eeb2a5e707260e8309ed28df410
1 //
2 // gfxcore.cc
3 //
4 // Core drawing code for Aven.
5 //
6 // Copyright (C) 2000-2003,2005,2006 Mark R. Shinwell
7 // Copyright (C) 2001-2003,2004,2005,2006,2007,2010,2011,2012,2014,2015 Olly Betts
8 // Copyright (C) 2005 Martin Green
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #include <assert.h>
30 #include <float.h>
32 #include "aven.h"
33 #include "date.h"
34 #include "filename.h"
35 #include "gfxcore.h"
36 #include "mainfrm.h"
37 #include "message.h"
38 #include "useful.h"
39 #include "printing.h"
40 #include "guicontrol.h"
41 #include "moviemaker.h"
43 #include <wx/confbase.h>
44 #include <wx/wfstream.h>
45 #include <wx/image.h>
46 #include <wx/zipstrm.h>
48 #include <proj_api.h>
50 const unsigned long DEFAULT_HGT_DIM = 3601;
51 const unsigned long DEFAULT_HGT_SIZE = sqrd(DEFAULT_HGT_DIM) * 2;
53 // Values for m_SwitchingTo
54 #define PLAN 1
55 #define ELEVATION 2
56 #define NORTH 3
57 #define EAST 4
58 #define SOUTH 5
59 #define WEST 6
61 // Any error value higher than this is clamped to this.
62 #define MAX_ERROR 12.0
64 // Any length greater than pow(10, LOG_LEN_MAX) will be clamped to this.
65 const Double LOG_LEN_MAX = 1.5;
67 // How many bins per letter height to use when working out non-overlapping
68 // labels.
69 const unsigned int QUANTISE_FACTOR = 2;
71 #include "avenpal.h"
73 static const int INDICATOR_BOX_SIZE = 60;
74 static const int INDICATOR_GAP = 2;
75 static const int INDICATOR_MARGIN = 5;
76 static const int INDICATOR_OFFSET_X = 15;
77 static const int INDICATOR_OFFSET_Y = 15;
78 static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
79 static const int KEY_OFFSET_X = 10;
80 static const int KEY_OFFSET_Y = 10;
81 static const int KEY_EXTRA_LEFT_MARGIN = 2;
82 static const int KEY_BLOCK_WIDTH = 20;
83 static const int KEY_BLOCK_HEIGHT = 16;
84 static const int TICK_LENGTH = 4;
85 static const int SCALE_BAR_OFFSET_X = 15;
86 static const int SCALE_BAR_OFFSET_Y = 12;
87 static const int SCALE_BAR_HEIGHT = 12;
89 static const gla_colour TEXT_COLOUR = col_GREEN;
90 static const gla_colour HERE_COLOUR = col_WHITE;
91 static const gla_colour NAME_COLOUR = col_GREEN;
92 static const gla_colour SEL_COLOUR = col_WHITE;
94 // Number of entries across and down the hit-test grid:
95 #define HITTEST_SIZE 20
97 // How close the pointer needs to be to a station to be considered:
98 #define MEASURE_THRESHOLD 7
100 // vector for lighting angle
101 static const Vector3 light(.577, .577, .577);
103 BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
104 EVT_PAINT(GfxCore::OnPaint)
105 EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
106 EVT_LEFT_UP(GfxCore::OnLButtonUp)
107 EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
108 EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
109 EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
110 EVT_RIGHT_UP(GfxCore::OnRButtonUp)
111 EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
112 EVT_MOTION(GfxCore::OnMouseMove)
113 EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
114 EVT_SIZE(GfxCore::OnSize)
115 EVT_IDLE(GfxCore::OnIdle)
116 EVT_CHAR(GfxCore::OnKeyPress)
117 END_EVENT_TABLE()
119 GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
120 GLACanvas(parent_win, 100),
121 m_Scale(0.0),
122 initial_scale(1.0),
123 m_ScaleBarWidth(0),
124 m_Control(control),
125 m_LabelGrid(NULL),
126 m_Parent(parent),
127 m_DoneFirstShow(false),
128 m_TiltAngle(0.0),
129 m_PanAngle(0.0),
130 m_Rotating(false),
131 m_RotationStep(0.0),
132 m_SwitchingTo(0),
133 m_Crosses(false),
134 m_Legs(true),
135 m_Splays(SPLAYS_SHOW_FADED),
136 m_Names(false),
137 m_Scalebar(true),
138 m_ColourKey(true),
139 m_OverlappingNames(false),
140 m_Compass(true),
141 m_Clino(true),
142 m_Tubes(false),
143 m_ColourBy(COLOUR_BY_DEPTH),
144 m_HaveData(false),
145 m_HaveTerrain(true),
146 m_MouseOutsideCompass(false),
147 m_MouseOutsideElev(false),
148 m_Surface(false),
149 m_Entrances(false),
150 m_FixedPts(false),
151 m_ExportedPts(false),
152 m_Grid(false),
153 m_BoundingBox(false),
154 m_Terrain(false),
155 m_Degrees(false),
156 m_Metric(false),
157 m_Percent(false),
158 m_HitTestDebug(false),
159 m_RenderStats(false),
160 m_PointGrid(NULL),
161 m_HitTestGridValid(false),
162 m_here(NULL),
163 m_there(NULL),
164 presentation_mode(0),
165 pres_reverse(false),
166 pres_speed(0.0),
167 movie(NULL),
168 current_cursor(GfxCore::CURSOR_DEFAULT),
169 sqrd_measure_threshold(sqrd(MEASURE_THRESHOLD)),
170 dem(NULL),
171 last_time(0),
172 n_tris(0)
174 AddQuad = &GfxCore::AddQuadrilateralDepth;
175 AddPoly = &GfxCore::AddPolylineDepth;
176 wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
177 wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
178 wxConfigBase::Get()->Read(wxT("percent"), &m_Percent, false);
180 for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
181 m_Pens[pen].SetColour(REDS[pen] / 255.0,
182 GREENS[pen] / 255.0,
183 BLUES[pen] / 255.0);
186 timer.Start();
189 GfxCore::~GfxCore()
191 TryToFreeArrays();
193 delete[] m_PointGrid;
196 void GfxCore::TryToFreeArrays()
198 // Free up any memory allocated for arrays.
199 delete[] m_LabelGrid;
200 m_LabelGrid = NULL;
204 // Initialisation methods
207 void GfxCore::Initialise(bool same_file)
209 // Initialise the view from the parent holding the survey data.
211 TryToFreeArrays();
213 m_DoneFirstShow = false;
215 m_HitTestGridValid = false;
216 m_here = NULL;
217 m_there = NULL;
219 m_MouseOutsideCompass = m_MouseOutsideElev = false;
221 if (!same_file) {
222 // Apply default parameters unless reloading the same file.
223 DefaultParameters();
226 m_HaveData = true;
228 // Clear any cached OpenGL lists which depend on the data.
229 InvalidateList(LIST_SCALE_BAR);
230 InvalidateList(LIST_DEPTH_KEY);
231 InvalidateList(LIST_DATE_KEY);
232 InvalidateList(LIST_ERROR_KEY);
233 InvalidateList(LIST_GRADIENT_KEY);
234 InvalidateList(LIST_LENGTH_KEY);
235 InvalidateList(LIST_UNDERGROUND_LEGS);
236 InvalidateList(LIST_TUBES);
237 InvalidateList(LIST_SURFACE_LEGS);
238 InvalidateList(LIST_BLOBS);
239 InvalidateList(LIST_CROSSES);
240 InvalidateList(LIST_GRID);
241 InvalidateList(LIST_SHADOW);
242 InvalidateList(LIST_TERRAIN);
244 // Set diameter of the viewing volume.
245 double cave_diameter = sqrt(sqrd(m_Parent->GetXExtent()) +
246 sqrd(m_Parent->GetYExtent()) +
247 sqrd(m_Parent->GetZExtent()));
249 // Allow for terrain.
250 double diameter = max(1000.0 * 2, cave_diameter * 2);
252 if (!same_file) {
253 SetVolumeDiameter(diameter);
255 // Set initial scale based on the size of the cave.
256 initial_scale = diameter / cave_diameter;
257 SetScale(initial_scale);
258 } else {
259 // Try to keep the same scale, allowing for the
260 // cave having grown (or shrunk).
261 double rescale = GetVolumeDiameter() / diameter;
262 SetVolumeDiameter(diameter);
263 SetScale(GetScale() * rescale);
264 initial_scale = initial_scale * rescale;
267 ForceRefresh();
270 void GfxCore::FirstShow()
272 GLACanvas::FirstShow();
274 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
275 list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
276 while (pos != m_Parent->GetLabelsNCEnd()) {
277 LabelInfo* label = *pos++;
278 // Calculate and set the label width for use when plotting
279 // none-overlapping labels.
280 int ext_x;
281 GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
282 label->set_width(unsigned(ext_x) / quantise + 1);
285 m_DoneFirstShow = true;
289 // Recalculating methods
292 void GfxCore::SetScale(Double scale)
294 if (scale < 0.05) {
295 scale = 0.05;
296 } else if (scale > GetVolumeDiameter()) {
297 scale = GetVolumeDiameter();
300 m_Scale = scale;
301 m_HitTestGridValid = false;
302 if (m_here && m_here == &temp_here) SetHere();
304 GLACanvas::SetScale(scale);
307 bool GfxCore::HasUndergroundLegs() const
309 return m_Parent->HasUndergroundLegs();
312 bool GfxCore::HasSplays() const
314 return m_Parent->HasSplays();
317 bool GfxCore::HasSurfaceLegs() const
319 return m_Parent->HasSurfaceLegs();
322 bool GfxCore::HasTubes() const
324 return m_Parent->HasTubes();
327 void GfxCore::UpdateBlobs()
329 InvalidateList(LIST_BLOBS);
333 // Event handlers
336 void GfxCore::OnLeaveWindow(wxMouseEvent&) {
337 SetHere();
338 ClearCoords();
341 void GfxCore::OnIdle(wxIdleEvent& event)
343 // Handle an idle event.
344 if (Animating()) {
345 Animate();
346 // If still animating, we want more idle events.
347 if (Animating())
348 event.RequestMore();
349 } else {
350 // If we're idle, don't show a bogus FPS next time we render.
351 last_time = 0;
355 void GfxCore::OnPaint(wxPaintEvent&)
357 // Redraw the window.
359 // Get a graphics context.
360 wxPaintDC dc(this);
362 if (m_HaveData) {
363 // Make sure we're initialised.
364 bool first_time = !m_DoneFirstShow;
365 if (first_time) {
366 FirstShow();
369 StartDrawing();
371 // Clear the background.
372 Clear();
374 // Set up model transformation matrix.
375 SetDataTransform();
377 if (m_Legs || m_Tubes) {
378 if (m_Tubes) {
379 EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
380 DrawList(LIST_TUBES);
381 DisableSmoothPolygons();
384 // Draw the underground legs. Do this last so that anti-aliasing
385 // works over polygons.
386 SetColour(col_GREEN);
387 DrawList(LIST_UNDERGROUND_LEGS);
390 if (m_Surface) {
391 // Draw the surface legs.
392 DrawList(LIST_SURFACE_LEGS);
395 if (m_BoundingBox) {
396 DrawShadowedBoundingBox();
398 if (m_Grid) {
399 // Draw the grid.
400 DrawList(LIST_GRID);
403 if (m_Terrain) {
404 // We don't want to be able to see the terrain through itself, so
405 // do a "Z-prepass" - plot the terrain once only updating the
406 // Z-buffer, then again with Z-clipping only plotting where the
407 // depth matches the value in the Z-buffer.
408 DrawListZPrepass(LIST_TERRAIN);
411 DrawList(LIST_BLOBS);
413 if (m_Crosses) {
414 DrawList(LIST_CROSSES);
417 SetIndicatorTransform();
419 // Draw station names.
420 if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
421 SetColour(NAME_COLOUR);
423 if (m_OverlappingNames) {
424 SimpleDrawNames();
425 } else {
426 NattyDrawNames();
430 if (m_HitTestDebug) {
431 // Show the hit test grid bucket sizes...
432 SetColour(m_HitTestGridValid ? col_LIGHT_GREY : col_DARK_GREY);
433 if (m_PointGrid) {
434 for (int i = 0; i != HITTEST_SIZE; ++i) {
435 int x = (GetXSize() + 1) * i / HITTEST_SIZE + 2;
436 for (int j = 0; j != HITTEST_SIZE; ++j) {
437 int square = i + j * HITTEST_SIZE;
438 unsigned long bucket_size = m_PointGrid[square].size();
439 if (bucket_size) {
440 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
441 DrawIndicatorText(x, y, wxString::Format(wxT("%lu"), bucket_size));
447 EnableDashedLines();
448 BeginLines();
449 for (int i = 0; i != HITTEST_SIZE; ++i) {
450 int x = (GetXSize() + 1) * i / HITTEST_SIZE;
451 PlaceIndicatorVertex(x, 0);
452 PlaceIndicatorVertex(x, GetYSize());
454 for (int j = 0; j != HITTEST_SIZE; ++j) {
455 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
456 PlaceIndicatorVertex(0, y);
457 PlaceIndicatorVertex(GetXSize(), y);
459 EndLines();
460 DisableDashedLines();
463 long now = timer.Time();
464 if (m_RenderStats) {
465 // Show stats about rendering.
466 SetColour(col_TURQUOISE);
467 int y = GetYSize() - GetFontSize();
468 if (last_time != 0.0) {
469 // timer.Time() measure in milliseconds.
470 double fps = 1000.0 / (now - last_time);
471 DrawIndicatorText(1, y, wxString::Format(wxT("FPS:% 5.1f"), fps));
473 y -= GetFontSize();
474 DrawIndicatorText(1, y, wxString::Format(wxT("▲:%lu"), (unsigned long)n_tris));
476 last_time = now;
478 // Draw indicators.
480 // There's no advantage in generating an OpenGL list for the
481 // indicators since they change with almost every redraw (and
482 // sometimes several times between redraws). This way we avoid
483 // the need to track when to update the indicator OpenGL list,
484 // and also avoid indicator update bugs when we don't quite get this
485 // right...
486 DrawIndicators();
488 if (zoombox.active()) {
489 SetColour(SEL_COLOUR);
490 EnableDashedLines();
491 BeginPolyline();
492 glaCoord Y = GetYSize();
493 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
494 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y2);
495 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y2);
496 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y1);
497 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
498 EndPolyline();
499 DisableDashedLines();
500 } else if (MeasuringLineActive()) {
501 // Draw "here" and "there".
502 double hx, hy;
503 SetColour(HERE_COLOUR);
504 if (m_here) {
505 double dummy;
506 Transform(*m_here, &hx, &hy, &dummy);
507 if (m_here != &temp_here) DrawRing(hx, hy);
509 if (m_there) {
510 double tx, ty;
511 double dummy;
512 Transform(*m_there, &tx, &ty, &dummy);
513 if (m_here) {
514 BeginLines();
515 PlaceIndicatorVertex(hx, hy);
516 PlaceIndicatorVertex(tx, ty);
517 EndLines();
519 BeginBlobs();
520 DrawBlob(tx, ty);
521 EndBlobs();
525 FinishDrawing();
526 } else {
527 dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
528 dc.Clear();
532 void GfxCore::DrawBoundingBox()
534 const Vector3 v = 0.5 * m_Parent->GetExtent();
536 SetColour(col_BLUE);
537 EnableDashedLines();
538 BeginPolyline();
539 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
540 PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
541 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
542 PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
543 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
544 EndPolyline();
545 BeginPolyline();
546 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
547 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
548 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
549 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
550 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
551 EndPolyline();
552 BeginLines();
553 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
554 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
555 PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
556 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
557 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
558 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
559 PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
560 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
561 EndLines();
562 DisableDashedLines();
565 void GfxCore::DrawShadowedBoundingBox()
567 const Vector3 v = 0.5 * m_Parent->GetExtent();
569 DrawBoundingBox();
571 PolygonOffset(true);
572 SetColour(col_DARK_GREY);
573 BeginQuadrilaterals();
574 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
575 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
576 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
577 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
578 EndQuadrilaterals();
579 PolygonOffset(false);
581 DrawList(LIST_SHADOW);
584 void GfxCore::DrawGrid()
586 // Draw the grid.
587 SetColour(col_RED);
589 // Calculate the extent of the survey, in metres across the screen plane.
590 Double m_across_screen = SurveyUnitsAcrossViewport();
591 // Calculate the length of the scale bar in metres.
592 //--move this elsewhere
593 Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
594 Double t = m_across_screen * 0.75 / size_snap;
595 if (t >= 5.0) {
596 size_snap *= 5.0;
598 else if (t >= 2.0) {
599 size_snap *= 2.0;
602 Double grid_size = size_snap * 0.1;
603 Double edge = grid_size * 2.0;
604 Double grid_z = -m_Parent->GetZExtent() * 0.5 - grid_size;
605 Double left = -m_Parent->GetXExtent() * 0.5 - edge;
606 Double right = m_Parent->GetXExtent() * 0.5 + edge;
607 Double bottom = -m_Parent->GetYExtent() * 0.5 - edge;
608 Double top = m_Parent->GetYExtent() * 0.5 + edge;
609 int count_x = (int) ceil((right - left) / grid_size);
610 int count_y = (int) ceil((top - bottom) / grid_size);
611 Double actual_right = left + count_x*grid_size;
612 Double actual_top = bottom + count_y*grid_size;
614 BeginLines();
616 for (int xc = 0; xc <= count_x; xc++) {
617 Double x = left + xc*grid_size;
619 PlaceVertex(x, bottom, grid_z);
620 PlaceVertex(x, actual_top, grid_z);
623 for (int yc = 0; yc <= count_y; yc++) {
624 Double y = bottom + yc*grid_size;
625 PlaceVertex(left, y, grid_z);
626 PlaceVertex(actual_right, y, grid_z);
629 EndLines();
632 int GfxCore::GetClinoOffset() const
634 int result = INDICATOR_OFFSET_X;
635 if (m_Compass) {
636 result += 6 + GetCompassWidth() + INDICATOR_GAP;
638 return result;
641 void GfxCore::DrawTick(int angle_cw)
643 const Double theta = rad(angle_cw);
644 const wxCoord length1 = INDICATOR_RADIUS;
645 const wxCoord length0 = length1 + TICK_LENGTH;
646 wxCoord x0 = wxCoord(length0 * sin(theta));
647 wxCoord y0 = wxCoord(length0 * cos(theta));
648 wxCoord x1 = wxCoord(length1 * sin(theta));
649 wxCoord y1 = wxCoord(length1 * cos(theta));
651 PlaceIndicatorVertex(x0, y0);
652 PlaceIndicatorVertex(x1, y1);
655 void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
656 Vector3 p1(0, INDICATOR_RADIUS, 0);
657 Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
658 Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
659 Vector3 pc(0, 0, 0);
661 DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
662 DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
665 void GfxCore::DrawCompass() {
666 // Ticks.
667 BeginLines();
668 for (int angle = 315; angle > 0; angle -= 45) {
669 DrawTick(angle);
671 SetColour(col_GREEN);
672 DrawTick(0);
673 EndLines();
675 // Compass background.
676 DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
678 // Compass arrow.
679 DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
682 // Draw the non-rotating background to the clino.
683 void GfxCore::DrawClinoBack() {
684 BeginLines();
685 for (int angle = 0; angle <= 180; angle += 90) {
686 DrawTick(angle);
689 SetColour(col_GREY);
690 PlaceIndicatorVertex(0, INDICATOR_RADIUS);
691 PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
692 PlaceIndicatorVertex(0, 0);
693 PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
695 EndLines();
698 void GfxCore::DrawClino() {
699 // Ticks.
700 SetColour(col_GREEN);
701 BeginLines();
702 DrawTick(0);
703 EndLines();
705 // Clino background.
706 DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
708 // Elevation arrow.
709 DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
712 void GfxCore::Draw2dIndicators()
714 // Draw the compass and elevation indicators.
716 const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
718 const int comp_centre_x = GetCompassXPosition();
720 if (m_Compass && !m_Parent->IsExtendedElevation()) {
721 // If the user is dragging the compass with the pointer outside the
722 // compass, we snap to 45 degree multiples, and the ticks go white.
723 SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
724 DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
727 const int elev_centre_x = GetClinoXPosition();
729 if (m_Clino) {
730 // If the user is dragging the clino with the pointer outside the
731 // clino, we snap to 90 degree multiples, and the ticks go white.
732 SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
733 DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
734 DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
737 SetColour(TEXT_COLOUR);
739 static int triple_zero_width = 0;
740 static int height = 0;
741 if (!triple_zero_width) {
742 GetTextExtent(wxT("000"), &triple_zero_width, &height);
744 const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
746 if (m_Compass && !m_Parent->IsExtendedElevation()) {
747 wxString str;
748 int value;
749 int brg_unit;
750 if (m_Degrees) {
751 value = int(m_PanAngle);
752 /* TRANSLATORS: degree symbol - probably should be translated to
753 * itself. */
754 brg_unit = /*°*/344;
755 } else {
756 value = int(m_PanAngle * 200.0 / 180.0);
757 /* TRANSLATORS: symbol for grad (400 grad = 360 degrees = full
758 * circle). */
759 brg_unit = /*ᵍ*/76;
761 str.Printf(wxT("%03d"), value);
762 str += wmsg(brg_unit);
763 DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
765 // TRANSLATORS: Used in aven above the compass indicator at the lower
766 // right of the display, with a bearing below "Facing". This indicates the
767 // direction the viewer is "facing" in.
769 // Try to keep this translation short - ideally at most 10 characters -
770 // as otherwise the compass and clino will be moved further apart to
771 // make room. */
772 str = wmsg(/*Facing*/203);
773 int w;
774 GetTextExtent(str, &w, NULL);
775 DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
778 if (m_Clino) {
779 if (m_TiltAngle == -90.0) {
780 // TRANSLATORS: Label used for "clino" in Aven when the view is
781 // from directly above.
783 // Try to keep this translation short - ideally at most 10
784 // characters - as otherwise the compass and clino will be moved
785 // further apart to make room. */
786 wxString str = wmsg(/*Plan*/432);
787 static int width = 0;
788 if (!width) {
789 GetTextExtent(str, &width, NULL);
791 int x = elev_centre_x - width / 2;
792 DrawIndicatorText(x, y_off + height / 2, str);
793 } else if (m_TiltAngle == 90.0) {
794 // TRANSLATORS: Label used for "clino" in Aven when the view is
795 // from directly below.
797 // Try to keep this translation short - ideally at most 10
798 // characters - as otherwise the compass and clino will be moved
799 // further apart to make room. */
800 wxString str = wmsg(/*Kiwi Plan*/433);
801 static int width = 0;
802 if (!width) {
803 GetTextExtent(str, &width, NULL);
805 int x = elev_centre_x - width / 2;
806 DrawIndicatorText(x, y_off + height / 2, str);
807 } else {
808 int angle;
809 wxString str;
810 int width;
811 int unit;
812 if (m_Percent) {
813 static int zero_width = 0;
814 if (!zero_width) {
815 GetTextExtent(wxT("0"), &zero_width, NULL);
817 width = zero_width;
818 if (m_TiltAngle > 89.99) {
819 angle = 1000000;
820 } else if (m_TiltAngle < -89.99) {
821 angle = -1000000;
822 } else {
823 angle = int(100 * tan(rad(m_TiltAngle)));
825 if (angle > 99999 || angle < -99999) {
826 str = angle > 0 ? wxT("+") : wxT("-");
827 /* TRANSLATORS: infinity symbol - used for the percentage gradient on
828 * vertical angles. */
829 str += wmsg(/*∞*/431);
830 } else {
831 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("0");
833 /* TRANSLATORS: symbol for percentage gradient (100% = 45
834 * degrees = 50 grad). */
835 unit = /*%*/96;
836 } else if (m_Degrees) {
837 static int zero_zero_width = 0;
838 if (!zero_zero_width) {
839 GetTextExtent(wxT("00"), &zero_zero_width, NULL);
841 width = zero_zero_width;
842 angle = int(m_TiltAngle);
843 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
844 unit = /*°*/344;
845 } else {
846 width = triple_zero_width;
847 angle = int(m_TiltAngle * 200.0 / 180.0);
848 str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
849 unit = /*ᵍ*/76;
852 int sign_offset = 0;
853 if (unit == /*%*/96) {
854 // Right align % since the width changes so much.
855 GetTextExtent(str, &sign_offset, NULL);
856 sign_offset -= width;
857 } else if (angle < 0) {
858 // Adjust horizontal position so the left of the first digit is
859 // always in the same place.
860 static int minus_width = 0;
861 if (!minus_width) {
862 GetTextExtent(wxT("-"), &minus_width, NULL);
864 sign_offset = minus_width;
865 } else if (angle > 0) {
866 // Adjust horizontal position so the left of the first digit is
867 // always in the same place.
868 static int plus_width = 0;
869 if (!plus_width) {
870 GetTextExtent(wxT("+"), &plus_width, NULL);
872 sign_offset = plus_width;
875 str += wmsg(unit);
876 DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
878 // TRANSLATORS: Label used for "clino" in Aven when the view is
879 // neither from directly above nor from directly below. It is
880 // also used in the dialog for editing a marked position in a
881 // presentation.
883 // Try to keep this translation short - ideally at most 10
884 // characters - as otherwise the compass and clino will be moved
885 // further apart to make room. */
886 str = wmsg(/*Elevation*/118);
887 static int elevation_width = 0;
888 if (!elevation_width) {
889 GetTextExtent(str, &elevation_width, NULL);
891 int x = elev_centre_x - elevation_width / 2;
892 DrawIndicatorText(x, y_off + height, str);
897 void GfxCore::NattyDrawNames()
899 // Draw station names, without overlapping.
901 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
902 const unsigned int quantised_x = GetXSize() / quantise;
903 const unsigned int quantised_y = GetYSize() / quantise;
904 const size_t buffer_size = quantised_x * quantised_y;
906 if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
908 memset((void*) m_LabelGrid, 0, buffer_size);
910 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
911 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
912 if (!((m_Surface && (*label)->IsSurface()) ||
913 (m_Legs && (*label)->IsUnderground()) ||
914 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
915 // if this station isn't to be displayed, skip to the next
916 // (last case is for stns with no legs attached)
917 continue;
920 double x, y, z;
922 Transform(**label, &x, &y, &z);
923 // Check if the label is behind us (in perspective view).
924 if (z <= 0.0 || z >= 1.0) continue;
926 // Apply a small shift so that translating the view doesn't make which
927 // labels are displayed change as the resulting twinkling effect is
928 // distracting.
929 double tx, ty, tz;
930 Transform(Vector3(), &tx, &ty, &tz);
931 tx -= floor(tx / quantise) * quantise;
932 ty -= floor(ty / quantise) * quantise;
934 tx = x - tx;
935 if (tx < 0) continue;
937 ty = y - ty;
938 if (ty < 0) continue;
940 unsigned int iy = unsigned(ty) / quantise;
941 if (iy >= quantised_y) continue;
942 unsigned int width = (*label)->get_width();
943 unsigned int ix = unsigned(tx) / quantise;
944 if (ix + width >= quantised_x) continue;
946 char * test = m_LabelGrid + ix + iy * quantised_x;
947 if (memchr(test, 1, width)) continue;
949 x += 3;
950 y -= GetFontSize() / 2;
951 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
953 if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
954 test -= quantised_x * iy;
955 iy += 4;
956 while (--iy && test < m_LabelGrid + buffer_size) {
957 memset(test, 1, width);
958 test += quantised_x;
963 void GfxCore::SimpleDrawNames()
965 // Draw all station names, without worrying about overlaps
966 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
967 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
968 if (!((m_Surface && (*label)->IsSurface()) ||
969 (m_Legs && (*label)->IsUnderground()) ||
970 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
971 // if this station isn't to be displayed, skip to the next
972 // (last case is for stns with no legs attached)
973 continue;
976 double x, y, z;
977 Transform(**label, &x, &y, &z);
979 // Check if the label is behind us (in perspective view).
980 if (z <= 0) continue;
982 x += 3;
983 y -= GetFontSize() / 2;
984 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
988 void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
990 int total_block_height =
991 KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
992 if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
993 if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
995 const int bottom = -total_block_height;
997 int size = 0;
998 if (!other.empty()) GetTextExtent(other, &size, NULL);
999 int band;
1000 for (band = 0; band < num_bands; ++band) {
1001 int x;
1002 GetTextExtent(key_legends[band], &x, NULL);
1003 if (x > size) size = x;
1006 int left = -KEY_BLOCK_WIDTH - size;
1008 key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
1009 key_lowerleft[m_ColourBy].y = bottom;
1011 int y = bottom;
1012 if (!units.empty()) y += KEY_BLOCK_HEIGHT;
1014 if (!other.empty()) {
1015 DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
1016 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1017 SetColour(col_BLACK);
1018 BeginPolyline();
1019 PlaceIndicatorVertex(left, y);
1020 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1021 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y + KEY_BLOCK_HEIGHT);
1022 PlaceIndicatorVertex(left, y + KEY_BLOCK_HEIGHT);
1023 PlaceIndicatorVertex(left, y);
1024 EndPolyline();
1025 y += KEY_BLOCK_HEIGHT * 2;
1028 int start = y;
1029 if (num_bands == 1) {
1030 DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
1031 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1032 y += KEY_BLOCK_HEIGHT;
1033 } else {
1034 for (band = 0; band < num_bands - 1; ++band) {
1035 DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
1036 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1037 y += KEY_BLOCK_HEIGHT;
1041 SetColour(col_BLACK);
1042 BeginPolyline();
1043 PlaceIndicatorVertex(left, y);
1044 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1045 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
1046 PlaceIndicatorVertex(left, start);
1047 PlaceIndicatorVertex(left, y);
1048 EndPolyline();
1050 SetColour(TEXT_COLOUR);
1052 y = bottom;
1053 if (!units.empty()) {
1054 GetTextExtent(units, &size, NULL);
1055 DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
1056 y += KEY_BLOCK_HEIGHT;
1058 y -= GetFontSize() / 2;
1059 left += KEY_BLOCK_WIDTH + 5;
1061 if (!other.empty()) {
1062 y += KEY_BLOCK_HEIGHT / 2;
1063 DrawIndicatorText(left, y, other);
1064 y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
1067 if (num_bands == 1) {
1068 y += KEY_BLOCK_HEIGHT / 2;
1069 DrawIndicatorText(left, y, key_legends[0]);
1070 } else {
1071 for (band = 0; band < num_bands; ++band) {
1072 DrawIndicatorText(left, y, key_legends[band]);
1073 y += KEY_BLOCK_HEIGHT;
1078 void GfxCore::DrawDepthKey()
1080 Double z_ext = m_Parent->GetDepthExtent();
1081 int num_bands = 1;
1082 int sf = 0;
1083 if (z_ext > 0.0) {
1084 num_bands = GetNumColourBands();
1085 Double z_range = z_ext;
1086 if (!m_Metric) z_range /= METRES_PER_FOOT;
1087 sf = max(0, 1 - (int)floor(log10(z_range)));
1090 Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
1091 for (int band = 0; band < num_bands; ++band) {
1092 Double z = z_min;
1093 if (band)
1094 z += z_ext * band / (num_bands - 1);
1096 if (!m_Metric)
1097 z /= METRES_PER_FOOT;
1099 key_legends[band].Printf(wxT("%.*f"), sf, z);
1102 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1105 void GfxCore::DrawDateKey()
1107 int num_bands;
1108 if (!HasDateInformation()) {
1109 num_bands = 0;
1110 } else {
1111 int date_ext = m_Parent->GetDateExtent();
1112 if (date_ext == 0) {
1113 num_bands = 1;
1114 } else {
1115 num_bands = GetNumColourBands();
1117 for (int band = 0; band < num_bands; ++band) {
1118 int y, m, d;
1119 int days = m_Parent->GetDateMin();
1120 if (band)
1121 days += date_ext * band / (num_bands - 1);
1122 ymd_from_days_since_1900(days, &y, &m, &d);
1123 key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
1127 wxString other;
1128 if (!m_Parent->HasCompleteDateInfo()) {
1129 /* TRANSLATORS: Used in the "colour key" for "colour by date" if there
1130 * are surveys without date information. Try to keep this fairly short.
1132 other = wmsg(/*Undated*/221);
1135 DrawColourKey(num_bands, other, wxString());
1138 void GfxCore::DrawErrorKey()
1140 int num_bands;
1141 if (HasErrorInformation()) {
1142 // Use fixed colours for each error factor so it's directly visually
1143 // comparable between surveys.
1144 num_bands = GetNumColourBands();
1145 for (int band = 0; band < num_bands; ++band) {
1146 double E = MAX_ERROR * band / (num_bands - 1);
1147 key_legends[band].Printf(wxT("%.2f"), E);
1149 } else {
1150 num_bands = 0;
1153 // Always show the "Not in loop" legend for now (FIXME).
1154 /* TRANSLATORS: Used in the "colour key" for "colour by error" for surveys
1155 * which aren’t part of a loop and so have no error information. Try to keep
1156 * this fairly short. */
1157 DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
1160 void GfxCore::DrawGradientKey()
1162 int num_bands;
1163 // Use fixed colours for each gradient so it's directly visually comparable
1164 // between surveys.
1165 num_bands = GetNumColourBands();
1166 wxString units = wmsg(m_Degrees ? /*°*/344 : /*ᵍ*/76);
1167 for (int band = 0; band < num_bands; ++band) {
1168 double gradient = double(band) / (num_bands - 1);
1169 if (m_Degrees) {
1170 gradient *= 90.0;
1171 } else {
1172 gradient *= 100.0;
1174 key_legends[band].Printf(wxT("%.f%s"), gradient, units);
1177 DrawColourKey(num_bands, wxString(), wxString());
1180 void GfxCore::DrawLengthKey()
1182 int num_bands;
1183 // Use fixed colours for each length so it's directly visually comparable
1184 // between surveys.
1185 num_bands = GetNumColourBands();
1186 for (int band = 0; band < num_bands; ++band) {
1187 double len = pow(10, LOG_LEN_MAX * band / (num_bands - 1));
1188 if (!m_Metric) {
1189 len /= METRES_PER_FOOT;
1191 key_legends[band].Printf(wxT("%.1f"), len);
1194 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1197 void GfxCore::DrawScaleBar()
1199 // Draw the scalebar.
1200 if (GetPerspective()) return;
1202 // Calculate how many metres of survey are currently displayed across the
1203 // screen.
1204 Double across_screen = SurveyUnitsAcrossViewport();
1206 double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
1207 if (f > 0.75) {
1208 f = 0.75;
1209 } else if (f < 0.5) {
1210 // Stop it getting squeezed to nothing.
1211 // FIXME: In this case we should probably move the compass and clino up
1212 // to make room rather than letting stuff overlap.
1213 f = 0.5;
1216 // Convert to imperial measurements if required.
1217 Double multiplier = 1.0;
1218 if (!m_Metric) {
1219 across_screen /= METRES_PER_FOOT;
1220 multiplier = METRES_PER_FOOT;
1221 if (across_screen >= 5280.0 / f) {
1222 across_screen /= 5280.0;
1223 multiplier *= 5280.0;
1227 // Calculate the length of the scale bar.
1228 Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1229 Double t = across_screen * f / size_snap;
1230 if (t >= 5.0) {
1231 size_snap *= 5.0;
1232 } else if (t >= 2.0) {
1233 size_snap *= 2.0;
1236 if (!m_Metric) size_snap *= multiplier;
1238 // Actual size of the thing in pixels:
1239 int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1240 m_ScaleBarWidth = size;
1242 // Draw it...
1243 const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1244 int interval = size / 10;
1246 gla_colour col = col_WHITE;
1247 for (int ix = 0; ix < 10; ix++) {
1248 int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1250 DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1252 col = (col == col_WHITE) ? col_GREY : col_WHITE;
1255 // Add labels.
1256 wxString str;
1257 int units;
1258 if (m_Metric) {
1259 Double km = size_snap * 1e-3;
1260 if (km >= 1.0) {
1261 size_snap = km;
1262 /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1263 * used e.g. "5km".
1265 * If there should be a space between the number and this, include
1266 * one in the translation. */
1267 units = /*km*/423;
1268 } else if (size_snap >= 1.0) {
1269 /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1270 * e.g. "10m".
1272 * If there should be a space between the number and this, include
1273 * one in the translation. */
1274 units = /*m*/424;
1275 } else {
1276 size_snap *= 1e2;
1277 /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1278 * used e.g. "50cm".
1280 * If there should be a space between the number and this, include
1281 * one in the translation. */
1282 units = /*cm*/425;
1284 } else {
1285 size_snap /= METRES_PER_FOOT;
1286 Double miles = size_snap / 5280.0;
1287 if (miles >= 1.0) {
1288 size_snap = miles;
1289 if (size_snap >= 2.0) {
1290 /* TRANSLATORS: abbreviation for "miles" (unit of length,
1291 * plural), used e.g. "2 miles".
1293 * If there should be a space between the number and this,
1294 * include one in the translation. */
1295 units = /* miles*/426;
1296 } else {
1297 /* TRANSLATORS: abbreviation for "mile" (unit of length,
1298 * singular), used e.g. "1 mile".
1300 * If there should be a space between the number and this,
1301 * include one in the translation. */
1302 units = /* mile*/427;
1304 } else if (size_snap >= 1.0) {
1305 /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1306 * as "10ft".
1308 * If there should be a space between the number and this, include
1309 * one in the translation. */
1310 units = /*ft*/428;
1311 } else {
1312 size_snap *= 12.0;
1313 /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1314 * e.g. as "6in".
1316 * If there should be a space between the number and this, include
1317 * one in the translation. */
1318 units = /*in*/429;
1321 if (size_snap >= 1.0) {
1322 str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1323 } else {
1324 int sf = -(int)floor(log10(size_snap));
1325 str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1328 int text_width, text_height;
1329 GetTextExtent(str, &text_width, &text_height);
1330 const int text_y = end_y - text_height + 1;
1331 SetColour(TEXT_COLOUR);
1332 DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1333 DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1336 bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1338 if (Animating()) return false;
1340 if (point.x < 0 || point.x >= GetXSize() ||
1341 point.y < 0 || point.y >= GetYSize()) {
1342 return false;
1345 SetDataTransform();
1347 if (!m_HitTestGridValid) CreateHitTestGrid();
1349 int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1350 int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
1352 LabelInfo *best = NULL;
1353 int dist_sqrd = sqrd_measure_threshold;
1354 int square = grid_x + grid_y * HITTEST_SIZE;
1355 list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1357 while (iter != m_PointGrid[square].end()) {
1358 LabelInfo *pt = *iter++;
1360 double cx, cy, cz;
1362 Transform(*pt, &cx, &cy, &cz);
1364 cy = GetYSize() - cy;
1366 int dx = point.x - int(cx);
1367 int ds = dx * dx;
1368 if (ds >= dist_sqrd) continue;
1369 int dy = point.y - int(cy);
1371 ds += dy * dy;
1372 if (ds >= dist_sqrd) continue;
1374 dist_sqrd = ds;
1375 best = pt;
1377 if (ds == 0) break;
1380 if (best) {
1381 m_Parent->ShowInfo(best, m_there);
1382 if (centre) {
1383 // FIXME: allow Ctrl-Click to not set there or something?
1384 CentreOn(*best);
1385 WarpPointer(GetXSize() / 2, GetYSize() / 2);
1386 SetThere(best);
1387 m_Parent->SelectTreeItem(best);
1389 } else {
1390 // Left-clicking not on a survey cancels the measuring line.
1391 if (centre) {
1392 ClearTreeSelection();
1393 } else {
1394 m_Parent->ShowInfo(best, m_there);
1395 double x, y, z;
1396 ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1397 temp_here.assign(Vector3(x, y, z));
1398 SetHere(&temp_here);
1402 return best;
1405 void GfxCore::OnSize(wxSizeEvent& event)
1407 // Handle a change in window size.
1408 wxSize size = event.GetSize();
1410 if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1411 // Before things are fully initialised, we sometimes get a bogus
1412 // resize message...
1413 // FIXME have changes in MainFrm cured this? It still happens with
1414 // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1415 // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1416 // is resized such that the GfxCore window isn't visible.
1417 //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1418 return;
1421 event.Skip();
1423 if (m_DoneFirstShow) {
1424 TryToFreeArrays();
1426 m_HitTestGridValid = false;
1428 ForceRefresh();
1432 void GfxCore::DefaultParameters()
1434 // Set default viewing parameters.
1436 m_Surface = false;
1437 if (!m_Parent->HasUndergroundLegs()) {
1438 if (m_Parent->HasSurfaceLegs()) {
1439 // If there are surface legs, but no underground legs, turn
1440 // surface surveys on.
1441 m_Surface = true;
1442 } else {
1443 // If there are no legs (e.g. after loading a .pos file), turn
1444 // crosses on.
1445 m_Crosses = true;
1449 m_PanAngle = 0.0;
1450 if (m_Parent->IsExtendedElevation()) {
1451 m_TiltAngle = 0.0;
1452 } else {
1453 m_TiltAngle = -90.0;
1456 SetRotation(m_PanAngle, m_TiltAngle);
1457 SetTranslation(Vector3());
1459 m_RotationStep = 30.0;
1460 m_Rotating = false;
1461 m_SwitchingTo = 0;
1462 m_Entrances = false;
1463 m_FixedPts = false;
1464 m_ExportedPts = false;
1465 m_Grid = false;
1466 m_BoundingBox = false;
1467 m_Tubes = false;
1468 if (GetPerspective()) TogglePerspective();
1470 // Set the initial scale.
1471 SetScale(initial_scale);
1474 void GfxCore::Defaults()
1476 // Restore default scale, rotation and translation parameters.
1477 DefaultParameters();
1479 // Invalidate all the cached lists.
1480 GLACanvas::FirstShow();
1482 ForceRefresh();
1485 void GfxCore::Animate()
1487 // Don't show pointer coordinates while animating.
1488 // FIXME : only do this when we *START* animating! Use a static copy
1489 // of the value of "Animating()" last time we were here to track this?
1490 // MainFrm now checks if we're trying to clear already cleared labels
1491 // and just returns, but it might be simpler to check here!
1492 ClearCoords();
1493 m_Parent->ShowInfo();
1495 long t;
1496 if (movie) {
1497 ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1498 if (!movie->AddFrame()) {
1499 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1500 delete movie;
1501 movie = NULL;
1502 presentation_mode = 0;
1503 return;
1505 t = 1000 / 25; // 25 frames per second
1506 } else {
1507 static long t_prev = 0;
1508 t = timer.Time();
1509 // Avoid redrawing twice in the same frame.
1510 long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1511 if (delta_t < 1000 / MAX_FRAMERATE)
1512 return;
1513 t_prev = t;
1514 if (presentation_mode == PLAYING && pres_speed != 0.0)
1515 t = delta_t;
1518 if (presentation_mode == PLAYING && pres_speed != 0.0) {
1519 // FIXME: It would probably be better to work relative to the time we
1520 // passed the last mark, but that's complicated by the speed
1521 // potentially changing (or even the direction of playback reversing)
1522 // at any point during playback.
1523 Double tick = t * 0.001 * fabs(pres_speed);
1524 while (tick >= next_mark_time) {
1525 tick -= next_mark_time;
1526 this_mark_total = 0;
1527 PresentationMark prev_mark = next_mark;
1528 if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1529 else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1530 if (pres_reverse)
1531 next_mark = m_Parent->GetPresMark(MARK_PREV);
1532 else
1533 next_mark = m_Parent->GetPresMark(MARK_NEXT);
1534 if (!next_mark.is_valid()) {
1535 SetView(prev_mark);
1536 presentation_mode = 0;
1537 if (movie && !movie->Close()) {
1538 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1540 delete movie;
1541 movie = NULL;
1542 break;
1545 double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1546 if (tmp > 0) {
1547 next_mark_time = tmp;
1548 } else {
1549 double d = (next_mark - prev_mark).magnitude();
1550 // FIXME: should ignore component of d which is unseen in
1551 // non-perspective mode?
1552 next_mark_time = sqrd(d / 30.0);
1553 double a = next_mark.angle - prev_mark.angle;
1554 if (a > 180.0) {
1555 next_mark.angle -= 360.0;
1556 a = 360.0 - a;
1557 } else if (a < -180.0) {
1558 next_mark.angle += 360.0;
1559 a += 360.0;
1560 } else {
1561 a = fabs(a);
1563 next_mark_time += sqrd(a / 60.0);
1564 double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1565 next_mark_time += sqrd(ta / 60.0);
1566 double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1567 next_mark_time += sqrd(s / 2.0);
1568 next_mark_time = sqrt(next_mark_time);
1569 // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1570 //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1571 // next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1572 if (tmp < 0) next_mark_time /= -tmp;
1576 if (presentation_mode) {
1577 // Advance position towards next_mark
1578 double p = tick / next_mark_time;
1579 double q = 1 - p;
1580 PresentationMark here = GetView();
1581 if (next_mark.angle < 0) {
1582 if (here.angle >= next_mark.angle + 360.0)
1583 here.angle -= 360.0;
1584 } else if (next_mark.angle >= 360.0) {
1585 if (here.angle <= next_mark.angle - 360.0)
1586 here.angle += 360.0;
1588 here.assign(q * here + p * next_mark);
1589 here.angle = q * here.angle + p * next_mark.angle;
1590 if (here.angle < 0) here.angle += 360.0;
1591 else if (here.angle >= 360.0) here.angle -= 360.0;
1592 here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1593 here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1594 SetView(here);
1595 this_mark_total += tick;
1596 next_mark_time -= tick;
1599 ForceRefresh();
1600 return;
1603 // When rotating...
1604 if (m_Rotating) {
1605 Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1606 TurnCave(step);
1609 if (m_SwitchingTo == PLAN) {
1610 // When switching to plan view...
1611 Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1612 TiltCave(step);
1613 if (m_TiltAngle == -90.0) {
1614 m_SwitchingTo = 0;
1616 } else if (m_SwitchingTo == ELEVATION) {
1617 // When switching to elevation view...
1618 Double step;
1619 if (m_TiltAngle > 0.0) {
1620 step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1621 } else {
1622 step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1624 if (fabs(step) >= fabs(m_TiltAngle)) {
1625 m_SwitchingTo = 0;
1626 step = -m_TiltAngle;
1628 TiltCave(step);
1629 } else if (m_SwitchingTo) {
1630 // Rotate the shortest way around to the destination angle. If we're
1631 // 180 off, we favour turning anticlockwise, as auto-rotation does by
1632 // default.
1633 Double target = (m_SwitchingTo - NORTH) * 90;
1634 Double diff = target - m_PanAngle;
1635 diff = fmod(diff, 360);
1636 if (diff <= -180)
1637 diff += 360;
1638 else if (diff > 180)
1639 diff -= 360;
1640 if (m_RotationStep < 0 && diff == 180.0)
1641 diff = -180.0;
1642 Double step = base_pan - m_PanAngle;
1643 Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1644 if (diff > 0) {
1645 step += delta;
1646 } else {
1647 step -= delta;
1649 step = fmod(step, 360);
1650 if (step <= -180)
1651 step += 360;
1652 else if (step > 180)
1653 step -= 360;
1654 if (fabs(step) >= fabs(diff)) {
1655 m_SwitchingTo = 0;
1656 step = diff;
1658 TurnCave(step);
1661 ForceRefresh();
1664 // How much to allow around the box - this is because of the ring shape
1665 // at one end of the line.
1666 static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1667 #define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1668 void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
1670 #ifdef __WXMSW__
1671 (void)a;
1672 (void)b;
1673 (void)c;
1674 // FIXME: We get odd redraw artifacts if we just update the line, and
1675 // redrawing the whole scene doesn't actually seem to be measurably
1676 // slower. That may not be true with software rendering though...
1677 ForceRefresh();
1678 #else
1679 // Best of all might be to copy the window contents before we draw the
1680 // line, then replace each time we redraw.
1682 // Calculate the minimum rectangle which includes the old and new
1683 // measuring lines to minimise the redraw time
1684 int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1685 double X, Y, Z;
1686 if (a) {
1687 if (!Transform(*a, &X, &Y, &Z)) {
1688 printf("oops\n");
1689 } else {
1690 int x = int(X);
1691 int y = GetYSize() - 1 - int(Y);
1692 l = x;
1693 r = x;
1694 u = y;
1695 d = y;
1698 if (b) {
1699 if (!Transform(*b, &X, &Y, &Z)) {
1700 printf("oops\n");
1701 } else {
1702 int x = int(X);
1703 int y = GetYSize() - 1 - int(Y);
1704 l = min(l, x);
1705 r = max(r, x);
1706 u = max(u, y);
1707 d = min(d, y);
1710 if (c) {
1711 if (!Transform(*c, &X, &Y, &Z)) {
1712 printf("oops\n");
1713 } else {
1714 int x = int(X);
1715 int y = GetYSize() - 1 - int(Y);
1716 l = min(l, x);
1717 r = max(r, x);
1718 u = max(u, y);
1719 d = min(d, y);
1722 l -= MARGIN;
1723 r += MARGIN;
1724 u += MARGIN;
1725 d -= MARGIN;
1726 RefreshRect(wxRect(l, d, r - l, u - d), false);
1727 #endif
1730 void GfxCore::SetHereFromTree(const LabelInfo * p)
1732 SetHere(p);
1733 m_Parent->ShowInfo(m_here, m_there);
1736 void GfxCore::SetHere()
1738 if (!m_here) return;
1739 bool line_active = MeasuringLineActive();
1740 const LabelInfo * old = m_here;
1741 m_here = NULL;
1742 if (line_active || MeasuringLineActive())
1743 RefreshLine(old, m_there, m_here);
1746 void GfxCore::SetHere(const LabelInfo *p)
1748 bool line_active = MeasuringLineActive();
1749 const LabelInfo * old = m_here;
1750 m_here = p;
1751 if (line_active || MeasuringLineActive())
1752 RefreshLine(old, m_there, m_here);
1755 void GfxCore::SetThere()
1757 if (!m_there) return;
1758 const LabelInfo * old = m_there;
1759 m_there = NULL;
1760 RefreshLine(m_here, old, m_there);
1763 void GfxCore::SetThere(const LabelInfo * p)
1765 const LabelInfo * old = m_there;
1766 m_there = p;
1767 RefreshLine(m_here, old, m_there);
1770 void GfxCore::CreateHitTestGrid()
1772 if (!m_PointGrid) {
1773 // Initialise hit-test grid.
1774 m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1775 } else {
1776 // Clear hit-test grid.
1777 for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1778 m_PointGrid[i].clear();
1782 // Fill the grid.
1783 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1784 list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1785 while (pos != end) {
1786 LabelInfo* label = *pos++;
1788 if (!((m_Surface && label->IsSurface()) ||
1789 (m_Legs && label->IsUnderground()) ||
1790 (!label->IsSurface() && !label->IsUnderground()))) {
1791 // if this station isn't to be displayed, skip to the next
1792 // (last case is for stns with no legs attached)
1793 continue;
1796 // Calculate screen coordinates.
1797 double cx, cy, cz;
1798 Transform(*label, &cx, &cy, &cz);
1799 if (cx < 0 || cx >= GetXSize()) continue;
1800 if (cy < 0 || cy >= GetYSize()) continue;
1802 cy = GetYSize() - cy;
1804 // On-screen, so add to hit-test grid...
1805 int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1806 int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
1808 m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1811 m_HitTestGridValid = true;
1815 // Methods for controlling the orientation of the survey
1818 void GfxCore::TurnCave(Double angle)
1820 // Turn the cave around its z-axis by a given angle.
1822 m_PanAngle += angle;
1823 // Wrap to range [0, 360):
1824 m_PanAngle = fmod(m_PanAngle, 360.0);
1825 if (m_PanAngle < 0.0) {
1826 m_PanAngle += 360.0;
1829 m_HitTestGridValid = false;
1830 if (m_here && m_here == &temp_here) SetHere();
1832 SetRotation(m_PanAngle, m_TiltAngle);
1835 void GfxCore::TurnCaveTo(Double angle)
1837 if (m_Rotating) {
1838 // If we're rotating, jump to the specified angle.
1839 TurnCave(angle - m_PanAngle);
1840 SetPanBase();
1841 return;
1844 int new_switching_to = ((int)angle) / 90 + NORTH;
1845 if (new_switching_to == m_SwitchingTo) {
1846 // A second order to switch takes us there right away
1847 TurnCave(angle - m_PanAngle);
1848 m_SwitchingTo = 0;
1849 ForceRefresh();
1850 } else {
1851 SetPanBase();
1852 m_SwitchingTo = new_switching_to;
1856 void GfxCore::TiltCave(Double tilt_angle)
1858 // Tilt the cave by a given angle.
1859 if (m_TiltAngle + tilt_angle > 90.0) {
1860 m_TiltAngle = 90.0;
1861 } else if (m_TiltAngle + tilt_angle < -90.0) {
1862 m_TiltAngle = -90.0;
1863 } else {
1864 m_TiltAngle += tilt_angle;
1867 m_HitTestGridValid = false;
1868 if (m_here && m_here == &temp_here) SetHere();
1870 SetRotation(m_PanAngle, m_TiltAngle);
1873 void GfxCore::TranslateCave(int dx, int dy)
1875 AddTranslationScreenCoordinates(dx, dy);
1876 m_HitTestGridValid = false;
1878 if (m_here && m_here == &temp_here) SetHere();
1880 ForceRefresh();
1883 void GfxCore::DragFinished()
1885 m_MouseOutsideCompass = m_MouseOutsideElev = false;
1886 ForceRefresh();
1889 void GfxCore::ClearCoords()
1891 m_Parent->ClearCoords();
1894 void GfxCore::SetCoords(wxPoint point)
1896 // We can't work out 2D coordinates from a perspective view, and it
1897 // doesn't really make sense to show coordinates while we're animating.
1898 if (GetPerspective() || Animating()) return;
1900 // Update the coordinate or altitude display, given the (x, y) position in
1901 // window coordinates. The relevant display is updated depending on
1902 // whether we're in plan or elevation view.
1904 double cx, cy, cz;
1906 SetDataTransform();
1907 ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
1909 if (ShowingPlan()) {
1910 m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1911 cy + m_Parent->GetOffset().GetY(),
1912 m_there);
1913 } else if (ShowingElevation()) {
1914 m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
1915 m_there);
1916 } else {
1917 m_Parent->ClearCoords();
1921 int GfxCore::GetCompassWidth() const
1923 static int result = 0;
1924 if (result == 0) {
1925 result = INDICATOR_BOX_SIZE;
1926 int width;
1927 const wxString & msg = wmsg(/*Facing*/203);
1928 GetTextExtent(msg, &width, NULL);
1929 if (width > result) result = width;
1931 return result;
1934 int GfxCore::GetClinoWidth() const
1936 static int result = 0;
1937 if (result == 0) {
1938 result = INDICATOR_BOX_SIZE;
1939 int width;
1940 const wxString & msg1 = wmsg(/*Plan*/432);
1941 GetTextExtent(msg1, &width, NULL);
1942 if (width > result) result = width;
1943 const wxString & msg2 = wmsg(/*Kiwi Plan*/433);
1944 GetTextExtent(msg2, &width, NULL);
1945 if (width > result) result = width;
1946 const wxString & msg3 = wmsg(/*Elevation*/118);
1947 GetTextExtent(msg3, &width, NULL);
1948 if (width > result) result = width;
1950 return result;
1953 int GfxCore::GetCompassXPosition() const
1955 // Return the x-coordinate of the centre of the compass in window
1956 // coordinates.
1957 return GetXSize() - INDICATOR_OFFSET_X - GetCompassWidth() / 2;
1960 int GfxCore::GetClinoXPosition() const
1962 // Return the x-coordinate of the centre of the compass in window
1963 // coordinates.
1964 return GetXSize() - GetClinoOffset() - GetClinoWidth() / 2;
1967 int GfxCore::GetIndicatorYPosition() const
1969 // Return the y-coordinate of the centre of the indicators in window
1970 // coordinates.
1971 return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1974 int GfxCore::GetIndicatorRadius() const
1976 // Return the radius of each indicator.
1977 return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1980 bool GfxCore::PointWithinCompass(wxPoint point) const
1982 // Determine whether a point (in window coordinates) lies within the
1983 // compass.
1984 if (!ShowingCompass()) return false;
1986 glaCoord dx = point.x - GetCompassXPosition();
1987 glaCoord dy = point.y - GetIndicatorYPosition();
1988 glaCoord radius = GetIndicatorRadius();
1990 return (dx * dx + dy * dy <= radius * radius);
1993 bool GfxCore::PointWithinClino(wxPoint point) const
1995 // Determine whether a point (in window coordinates) lies within the clino.
1996 if (!ShowingClino()) return false;
1998 glaCoord dx = point.x - GetClinoXPosition();
1999 glaCoord dy = point.y - GetIndicatorYPosition();
2000 glaCoord radius = GetIndicatorRadius();
2002 return (dx * dx + dy * dy <= radius * radius);
2005 bool GfxCore::PointWithinScaleBar(wxPoint point) const
2007 // Determine whether a point (in window coordinates) lies within the scale
2008 // bar.
2009 if (!ShowingScaleBar()) return false;
2011 return (point.x >= SCALE_BAR_OFFSET_X &&
2012 point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
2013 point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
2014 point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
2017 bool GfxCore::PointWithinColourKey(wxPoint point) const
2019 // Determine whether a point (in window coordinates) lies within the key.
2020 point.x -= GetXSize() - KEY_OFFSET_X;
2021 point.y = KEY_OFFSET_Y - point.y;
2022 return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
2023 point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
2026 void GfxCore::SetCompassFromPoint(wxPoint point)
2028 // Given a point in window coordinates, set the heading of the survey. If
2029 // the point is outside the compass, it snaps to 45 degree intervals;
2030 // otherwise it operates as normal.
2032 wxCoord dx = point.x - GetCompassXPosition();
2033 wxCoord dy = point.y - GetIndicatorYPosition();
2034 wxCoord radius = GetIndicatorRadius();
2036 double angle = deg(atan2(double(dx), double(dy))) - 180.0;
2037 if (dx * dx + dy * dy <= radius * radius) {
2038 TurnCave(angle - m_PanAngle);
2039 m_MouseOutsideCompass = false;
2040 } else {
2041 TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
2042 m_MouseOutsideCompass = true;
2045 ForceRefresh();
2048 void GfxCore::SetClinoFromPoint(wxPoint point)
2050 // Given a point in window coordinates, set the elevation of the survey.
2051 // If the point is outside the clino, it snaps to 90 degree intervals;
2052 // otherwise it operates as normal.
2054 glaCoord dx = point.x - GetClinoXPosition();
2055 glaCoord dy = point.y - GetIndicatorYPosition();
2056 glaCoord radius = GetIndicatorRadius();
2058 if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
2059 TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
2060 m_MouseOutsideElev = false;
2061 } else if (dy >= INDICATOR_MARGIN) {
2062 TiltCave(-90.0 - m_TiltAngle);
2063 m_MouseOutsideElev = true;
2064 } else if (dy <= -INDICATOR_MARGIN) {
2065 TiltCave(90.0 - m_TiltAngle);
2066 m_MouseOutsideElev = true;
2067 } else {
2068 TiltCave(-m_TiltAngle);
2069 m_MouseOutsideElev = true;
2072 ForceRefresh();
2075 void GfxCore::SetScaleBarFromOffset(wxCoord dx)
2077 // Set the scale of the survey, given an offset as to how much the mouse has
2078 // been dragged over the scalebar since the last scale change.
2080 SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
2081 ForceRefresh();
2084 void GfxCore::RedrawIndicators()
2086 // Redraw the compass and clino indicators.
2088 int total_width = GetCompassWidth() + INDICATOR_GAP + GetClinoWidth();
2089 RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - total_width,
2090 GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
2091 total_width,
2092 INDICATOR_BOX_SIZE), false);
2095 void GfxCore::StartRotation()
2097 // Start the survey rotating.
2099 if (m_SwitchingTo >= NORTH)
2100 m_SwitchingTo = 0;
2101 m_Rotating = true;
2102 SetPanBase();
2105 void GfxCore::ToggleRotation()
2107 // Toggle the survey rotation on/off.
2109 if (m_Rotating) {
2110 StopRotation();
2111 } else {
2112 StartRotation();
2116 void GfxCore::StopRotation()
2118 // Stop the survey rotating.
2120 m_Rotating = false;
2121 ForceRefresh();
2124 bool GfxCore::IsExtendedElevation() const
2126 return m_Parent->IsExtendedElevation();
2129 void GfxCore::ReverseRotation()
2131 // Reverse the direction of rotation.
2133 m_RotationStep = -m_RotationStep;
2134 if (m_Rotating)
2135 SetPanBase();
2138 void GfxCore::RotateSlower(bool accel)
2140 // Decrease the speed of rotation, optionally by an increased amount.
2141 if (fabs(m_RotationStep) == 1.0)
2142 return;
2144 m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2146 if (fabs(m_RotationStep) < 1.0) {
2147 m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
2149 if (m_Rotating)
2150 SetPanBase();
2153 void GfxCore::RotateFaster(bool accel)
2155 // Increase the speed of rotation, optionally by an increased amount.
2156 if (fabs(m_RotationStep) == 180.0)
2157 return;
2159 m_RotationStep *= accel ? 1.44 : 1.2;
2160 if (fabs(m_RotationStep) > 180.0) {
2161 m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
2163 if (m_Rotating)
2164 SetPanBase();
2167 void GfxCore::SwitchToElevation()
2169 // Perform an animated switch to elevation view.
2171 if (m_SwitchingTo != ELEVATION) {
2172 SetTiltBase();
2173 m_SwitchingTo = ELEVATION;
2174 } else {
2175 // A second order to switch takes us there right away
2176 TiltCave(-m_TiltAngle);
2177 m_SwitchingTo = 0;
2178 ForceRefresh();
2182 void GfxCore::SwitchToPlan()
2184 // Perform an animated switch to plan view.
2186 if (m_SwitchingTo != PLAN) {
2187 SetTiltBase();
2188 m_SwitchingTo = PLAN;
2189 } else {
2190 // A second order to switch takes us there right away
2191 TiltCave(-90.0 - m_TiltAngle);
2192 m_SwitchingTo = 0;
2193 ForceRefresh();
2197 void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2200 SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
2201 Double scale = HUGE_VAL;
2202 const Vector3 ext = m_Parent->GetExtent();
2203 if (xmax > xmin) {
2204 Double s = ext.GetX() / (xmax - xmin);
2205 if (s < scale) scale = s;
2207 if (ymax > ymin) {
2208 Double s = ext.GetY() / (ymax - ymin);
2209 if (s < scale) scale = s;
2211 if (!ShowingPlan() && zmax > zmin) {
2212 Double s = ext.GetZ() / (zmax - zmin);
2213 if (s < scale) scale = s;
2215 if (scale != HUGE_VAL) SetScale(scale);
2216 ForceRefresh();
2219 bool GfxCore::CanRaiseViewpoint() const
2221 // Determine if the survey can be viewed from a higher angle of elevation.
2223 return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
2226 bool GfxCore::CanLowerViewpoint() const
2228 // Determine if the survey can be viewed from a lower angle of elevation.
2230 return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
2233 bool GfxCore::HasDepth() const
2235 return m_Parent->GetDepthExtent() == 0.0;
2238 bool GfxCore::HasErrorInformation() const
2240 return m_Parent->HasErrorInformation();
2243 bool GfxCore::HasDateInformation() const
2245 return m_Parent->GetDateMin() >= 0;
2248 bool GfxCore::ShowingPlan() const
2250 // Determine if the survey is in plan view.
2252 return (m_TiltAngle == -90.0);
2255 bool GfxCore::ShowingElevation() const
2257 // Determine if the survey is in elevation view.
2259 return (m_TiltAngle == 0.0);
2262 bool GfxCore::ShowingMeasuringLine() const
2264 // Determine if the measuring line is being shown. Only check if "there"
2265 // is valid, since that means the measuring line anchor is out.
2267 return m_there;
2270 void GfxCore::ToggleFlag(bool* flag, int update)
2272 *flag = !*flag;
2273 if (update == UPDATE_BLOBS) {
2274 UpdateBlobs();
2275 } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2276 UpdateBlobs();
2277 InvalidateList(LIST_CROSSES);
2278 m_HitTestGridValid = false;
2280 ForceRefresh();
2283 int GfxCore::GetNumEntrances() const
2285 return m_Parent->GetNumEntrances();
2288 int GfxCore::GetNumFixedPts() const
2290 return m_Parent->GetNumFixedPts();
2293 int GfxCore::GetNumExportedPts() const
2295 return m_Parent->GetNumExportedPts();
2298 void GfxCore::ToggleTerrain()
2300 ToggleFlag(&m_Terrain);
2301 if (m_Terrain && !dem) {
2302 wxCommandEvent dummy;
2303 m_Parent->OnOpenTerrain(dummy);
2307 void GfxCore::ToggleFatFinger()
2309 if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2310 sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2311 wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2312 } else {
2313 sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2314 wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2318 void GfxCore::ClearTreeSelection()
2320 m_Parent->ClearTreeSelection();
2323 void GfxCore::CentreOn(const Point &p)
2325 SetTranslation(-p);
2326 m_HitTestGridValid = false;
2328 ForceRefresh();
2331 void GfxCore::ForceRefresh()
2333 Refresh(false);
2336 void GfxCore::GenerateList(unsigned int l)
2338 assert(m_HaveData);
2340 switch (l) {
2341 case LIST_COMPASS:
2342 DrawCompass();
2343 break;
2344 case LIST_CLINO:
2345 DrawClino();
2346 break;
2347 case LIST_CLINO_BACK:
2348 DrawClinoBack();
2349 break;
2350 case LIST_SCALE_BAR:
2351 DrawScaleBar();
2352 break;
2353 case LIST_DEPTH_KEY:
2354 DrawDepthKey();
2355 break;
2356 case LIST_DATE_KEY:
2357 DrawDateKey();
2358 break;
2359 case LIST_ERROR_KEY:
2360 DrawErrorKey();
2361 break;
2362 case LIST_GRADIENT_KEY:
2363 DrawGradientKey();
2364 break;
2365 case LIST_LENGTH_KEY:
2366 DrawLengthKey();
2367 break;
2368 case LIST_UNDERGROUND_LEGS:
2369 GenerateDisplayList();
2370 break;
2371 case LIST_TUBES:
2372 GenerateDisplayListTubes();
2373 break;
2374 case LIST_SURFACE_LEGS:
2375 GenerateDisplayListSurface();
2376 break;
2377 case LIST_BLOBS:
2378 GenerateBlobsDisplayList();
2379 break;
2380 case LIST_CROSSES: {
2381 BeginCrosses();
2382 SetColour(col_LIGHT_GREY);
2383 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2384 while (pos != m_Parent->GetLabelsEnd()) {
2385 const LabelInfo* label = *pos++;
2387 if ((m_Surface && label->IsSurface()) ||
2388 (m_Legs && label->IsUnderground()) ||
2389 (!label->IsSurface() && !label->IsUnderground())) {
2390 // Check if this station should be displayed
2391 // (last case is for stns with no legs attached)
2392 DrawCross(label->GetX(), label->GetY(), label->GetZ());
2395 EndCrosses();
2396 break;
2398 case LIST_GRID:
2399 DrawGrid();
2400 break;
2401 case LIST_SHADOW:
2402 GenerateDisplayListShadow();
2403 break;
2404 case LIST_TERRAIN:
2405 DrawTerrain();
2406 break;
2407 default:
2408 assert(false);
2409 break;
2413 void GfxCore::ToggleSmoothShading()
2415 GLACanvas::ToggleSmoothShading();
2416 InvalidateList(LIST_TUBES);
2417 ForceRefresh();
2420 void GfxCore::GenerateDisplayList()
2422 // Generate the display list for the underground legs.
2423 list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2424 list<traverse>::const_iterator tend = m_Parent->traverses_end();
2426 if (m_Splays == SPLAYS_SHOW_FADED) {
2427 SetAlpha(0.4);
2428 while (trav != tend) {
2429 if ((*trav).isSplay)
2430 (this->*AddPoly)(*trav);
2431 ++trav;
2433 SetAlpha(1.0);
2434 trav = m_Parent->traverses_begin();
2437 while (trav != tend) {
2438 if (m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
2439 (this->*AddPoly)(*trav);
2440 ++trav;
2444 void GfxCore::GenerateDisplayListTubes()
2446 // Generate the display list for the tubes.
2447 list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2448 list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2449 while (trav != tend) {
2450 SkinPassage(*trav);
2451 ++trav;
2455 void GfxCore::GenerateDisplayListSurface()
2457 // Generate the display list for the surface legs.
2458 EnableDashedLines();
2459 list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2460 list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2461 while (trav != tend) {
2462 if (m_ColourBy == COLOUR_BY_ERROR) {
2463 AddPolylineError(*trav);
2464 } else {
2465 AddPolyline(*trav);
2467 ++trav;
2469 DisableDashedLines();
2472 void GfxCore::GenerateDisplayListShadow()
2474 SetColour(col_BLACK);
2475 list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2476 list<traverse>::const_iterator tend = m_Parent->traverses_end();
2477 while (trav != tend) {
2478 AddPolylineShadow(*trav);
2479 ++trav;
2483 void
2484 GfxCore::parse_hgt_filename(const wxString & lc_name)
2486 char * leaf = leaf_from_fnm(lc_name.utf8_str());
2487 const char * p = leaf;
2488 char * q;
2489 char dirn = *p++;
2490 o_y = strtoul(p, &q, 10);
2491 p = q;
2492 if (dirn == 's')
2493 o_y = -o_y;
2494 ++o_y;
2495 dirn = *p++;
2496 o_x = strtoul(p, &q, 10);
2497 if (dirn == 'w')
2498 o_x = -o_x;
2499 bigendian = true;
2500 nodata_value = -32768;
2501 osfree(leaf);
2504 size_t
2505 GfxCore::parse_hdr(wxInputStream & is, unsigned long & skipbytes)
2507 unsigned long nbits;
2508 while (!is.Eof()) {
2509 wxString line;
2510 int ch;
2511 while ((ch = is.GetC()) != wxEOF) {
2512 if (ch == '\n' || ch == '\r') break;
2513 line += wxChar(ch);
2515 #define CHECK(X, COND) \
2516 } else if (line.StartsWith(wxT(X " "))) { \
2517 size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2518 if (v == line.npos || !(COND)) { \
2519 err += wxT("Unexpected value for " X); \
2521 wxString err;
2522 unsigned long dummy;
2523 if (false) {
2524 // I = little-endian; M = big-endian
2525 CHECK("BYTEORDER", (bigendian = (line[v] == 'M')) || line[v] == 'I')
2526 CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2527 CHECK("NROWS", line.substr(v).ToCULong(&dem_width))
2528 CHECK("NCOLS", line.substr(v).ToCULong(&dem_height))
2529 CHECK("NBANDS", line.substr(v).ToCULong(&dummy) && dummy == 1)
2530 CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2531 //: BANDROWBYTES 7202
2532 //: TOTALROWBYTES 7202
2533 // PIXELTYPE is a GDAL extension, so may not be present.
2534 CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2535 CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2536 CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2537 CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2538 CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2539 CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2540 CHECK("SKIPBYTES", line.substr(v).ToCULong(&skipbytes))
2542 if (!err.empty()) {
2543 wxMessageBox(err);
2546 return ((nbits + 7) / 8) * dem_width * dem_height;
2549 bool
2550 GfxCore::read_bil(wxInputStream & is, size_t size, unsigned long skipbytes)
2552 bool know_size = true;
2553 if (!size) {
2554 // If the stream doesn't know its size, GetSize() returns 0.
2555 size = is.GetSize();
2556 if (!size) {
2557 size = DEFAULT_HGT_SIZE;
2558 know_size = false;
2561 dem = new unsigned short[size / 2];
2562 if (skipbytes) {
2563 if (is.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2564 while (skipbytes) {
2565 unsigned long to_read = skipbytes;
2566 if (size < to_read) to_read = size;
2567 is.Read(reinterpret_cast<char *>(dem), to_read);
2568 size_t c = is.LastRead();
2569 if (c == 0) {
2570 wxMessageBox(wxT("Failed to skip terrain data header"));
2571 break;
2573 skipbytes -= c;
2578 #if wxCHECK_VERSION(2,9,5)
2579 if (!is.ReadAll(dem, size)) {
2580 if (know_size) {
2581 // FIXME: On __WXMSW__ currently we fail to
2582 // read any data from files in zips.
2583 delete [] dem;
2584 dem = NULL;
2585 wxMessageBox(wxT("Failed to read terrain data"));
2586 return false;
2588 size = is.LastRead();
2590 #else
2591 char * p = reinterpret_cast<char *>(dem);
2592 while (size) {
2593 is.Read(p, size);
2594 size_t c = is.LastRead();
2595 if (c == 0) {
2596 if (!know_size) {
2597 size = DEFAULT_HGT_SIZE - size;
2598 if (size)
2599 break;
2601 delete [] dem;
2602 dem = NULL;
2603 wxMessageBox(wxT("Failed to read terrain data"));
2604 return false;
2606 p += c;
2607 size -= c;
2609 #endif
2611 if (dem_width == 0 && dem_height == 0) {
2612 dem_width = dem_height = sqrt(size / 2);
2613 if (dem_width * dem_height * 2 != size) {
2614 delete [] dem;
2615 dem = NULL;
2616 wxMessageBox(wxT("HGT format data doesn't form a square"));
2617 return false;
2619 step_x = step_y = 1.0 / dem_width;
2622 return true;
2625 bool GfxCore::LoadDEM(const wxString & file)
2627 if (m_Parent->m_cs_proj.empty()) {
2628 wxMessageBox(wxT("No coordinate system specified in survey data"));
2629 return false;
2632 delete [] dem;
2633 dem = NULL;
2635 size_t size = 0;
2636 // Default is to not skip any bytes.
2637 unsigned long skipbytes = 0;
2638 // For .hgt files, default to using filesize to determine.
2639 dem_width = dem_height = 0;
2640 // ESRI say "The default byte order is the same as that of the host machine
2641 // executing the software", but that's stupid so we default to
2642 // little-endian.
2643 bigendian = false;
2645 wxFileInputStream fs(file);
2646 if (!fs.IsOk()) {
2647 wxMessageBox(wxT("Failed to open DEM file"));
2648 return false;
2651 const wxString & lc_file = file.Lower();
2652 if (lc_file.EndsWith(wxT(".hgt"))) {
2653 parse_hgt_filename(lc_file);
2654 read_bil(fs, size, skipbytes);
2655 } else if (lc_file.EndsWith(wxT(".bil"))) {
2656 wxString hdr_file = file;
2657 hdr_file.replace(file.size() - 4, 4, wxT(".hdr"));
2658 wxFileInputStream hdr_is(hdr_file);
2659 if (!hdr_is.IsOk()) {
2660 wxMessageBox(wxT("Failed to open HDR file '") + hdr_file + wxT("'"));
2661 return false;
2663 size = parse_hdr(hdr_is, skipbytes);
2664 read_bil(fs, size, skipbytes);
2665 } else if (lc_file.EndsWith(wxT(".zip"))) {
2666 wxZipEntry * ze_data = NULL;
2667 wxZipInputStream zs(fs);
2668 wxZipEntry * ze;
2669 while ((ze = zs.GetNextEntry()) != NULL) {
2670 if (!ze->IsDir()) {
2671 const wxString & lc_name = ze->GetName().Lower();
2672 if (!ze_data && lc_name.EndsWith(wxT(".hgt"))) {
2673 // SRTM .hgt files are raw binary data, with the filename
2674 // encoding the coordinates.
2675 parse_hgt_filename(lc_name);
2676 read_bil(zs, size, skipbytes);
2677 delete ze;
2678 break;
2681 if (!ze_data && lc_name.EndsWith(wxT(".bil"))) {
2682 if (size) {
2683 read_bil(zs, size, skipbytes);
2684 break;
2686 ze_data = ze;
2687 continue;
2690 if (lc_name.EndsWith(wxT(".hdr"))) {
2691 size = parse_hdr(zs, skipbytes);
2692 if (ze_data) {
2693 if (!zs.OpenEntry(*ze_data)) {
2694 wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2695 break;
2697 read_bil(zs, size, skipbytes);
2699 } else if (lc_name.EndsWith(wxT(".prj"))) {
2700 //FIXME: check this matches the datum string we use
2701 //Projection GEOGRAPHIC
2702 //Datum WGS84
2703 //Zunits METERS
2704 //Units DD
2705 //Spheroid WGS84
2706 //Xshift 0.0000000000
2707 //Yshift 0.0000000000
2708 //Parameters
2711 delete ze;
2713 delete ze_data;
2716 if (!dem) {
2717 return false;
2720 InvalidateList(LIST_TERRAIN);
2721 ForceRefresh();
2722 return true;
2725 void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2727 Vector3 n = (b - a) * (c - a);
2728 n.normalise();
2729 Double factor = dot(n, light) * .95 + .05;
2730 SetColour(col_WHITE, factor);
2731 PlaceVertex(a);
2732 PlaceVertex(b);
2733 PlaceVertex(c);
2734 ++n_tris;
2737 void GfxCore::DrawTerrain()
2739 if (!dem) return;
2741 wxBusyCursor hourglass;
2743 // Draw terrain to twice the extent, or at least 1km.
2744 double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2745 #define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2746 static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2747 if (!pj_in) {
2748 ToggleTerrain();
2749 error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2750 return;
2752 static projPJ pj_out = pj_init_plus(m_Parent->m_cs_proj.c_str());
2753 if (!pj_out) {
2754 ToggleTerrain();
2755 error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->m_cs_proj.c_str());
2756 return;
2758 n_tris = 0;
2759 SetAlpha(0.3);
2760 BeginTriangles();
2761 const Vector3 & off = m_Parent->GetOffset();
2762 vector<Vector3> prevcol(dem_height + 1);
2763 for (size_t x = 0; x < dem_width; ++x) {
2764 double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2765 Vector3 prev;
2766 for (size_t y = 0; y < dem_height; ++y) {
2767 unsigned short elev = dem[x + y * dem_width];
2768 #ifdef WORDS_BIGENDIAN
2769 const bool MACHINE_BIGENDIAN = true;
2770 #else
2771 const bool MACHINE_BIGENDIAN = false;
2772 #endif
2773 if (bigendian != MACHINE_BIGENDIAN) {
2774 #if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2775 elev = __builtin_bswap16(elev);
2776 #else
2777 elev = (elev >> 8) | (elev << 8);
2778 #endif
2780 double Z = (short)elev;
2781 Vector3 pt;
2782 if (Z == nodata_value) {
2783 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2784 } else {
2785 double X = X_;
2786 double Y = (o_y - y * step_y) * DEG_TO_RAD;
2787 pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2788 pt = Vector3(X, Y, Z) - off;
2789 double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2790 if (dist_2 > r_sqrd) {
2791 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2794 if (x > 0 && y > 0) {
2795 const Vector3 & a = prevcol[y - 1];
2796 const Vector3 & b = prevcol[y];
2797 // If all points are valid, split the quadrilateral into
2798 // triangles along the shorter 3D diagonal, which typically
2799 // looks better:
2801 // ----->
2802 // prev---a x prev---a
2803 // | |P /| |\ S|
2804 // y | | / | or | \ |
2805 // V | / | | \ |
2806 // |/ Q| |R \|
2807 // b----pt b----pt
2809 // FORWARD BACKWARD
2810 enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
2811 int valid =
2812 ((prev.GetZ() != DBL_MAX)) |
2813 ((a.GetZ() != DBL_MAX) << 1) |
2814 ((b.GetZ() != DBL_MAX) << 2) |
2815 ((pt.GetZ() != DBL_MAX) << 3);
2816 static const int tris_map[16] = {
2817 NONE, // nothing valid
2818 NONE, // prev
2819 NONE, // a
2820 NONE, // a, prev
2821 NONE, // b
2822 NONE, // b, prev
2823 NONE, // b, a
2824 P, // b, a, prev
2825 NONE, // pt
2826 NONE, // pt, prev
2827 NONE, // pt, a
2828 S, // pt, a, prev
2829 NONE, // pt, b
2830 R, // pt, b, prev
2831 Q, // pt, b, a
2832 ALL, // pt, b, a, prev
2834 int tris = tris_map[valid];
2835 if (tris == ALL) {
2836 // All points valid.
2837 if ((a - b).magnitude() < (prev - pt).magnitude()) {
2838 tris = P | Q;
2839 } else {
2840 tris = R | S;
2843 if (tris & P)
2844 DrawTerrainTriangle(a, prev, b);
2845 if (tris & Q)
2846 DrawTerrainTriangle(a, b, pt);
2847 if (tris & R)
2848 DrawTerrainTriangle(pt, prev, b);
2849 if (tris & S)
2850 DrawTerrainTriangle(a, prev, pt);
2852 prev = prevcol[y];
2853 prevcol[y].assign(pt);
2856 EndTriangles();
2857 SetAlpha(1.0);
2860 // Plot blobs.
2861 void GfxCore::GenerateBlobsDisplayList()
2863 if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2864 m_Parent->GetNumHighlightedPts()))
2865 return;
2867 // Plot blobs.
2868 gla_colour prev_col = col_BLACK; // not a colour used for blobs
2869 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2870 BeginBlobs();
2871 while (pos != m_Parent->GetLabelsEnd()) {
2872 const LabelInfo* label = *pos++;
2874 // When more than one flag is set on a point:
2875 // search results take priority over entrance highlighting
2876 // which takes priority over fixed point
2877 // highlighting, which in turn takes priority over exported
2878 // point highlighting.
2880 if (!((m_Surface && label->IsSurface()) ||
2881 (m_Legs && label->IsUnderground()) ||
2882 (!label->IsSurface() && !label->IsUnderground()))) {
2883 // if this station isn't to be displayed, skip to the next
2884 // (last case is for stns with no legs attached)
2885 continue;
2888 gla_colour col;
2890 if (label->IsHighLighted()) {
2891 col = col_YELLOW;
2892 } else if (m_Entrances && label->IsEntrance()) {
2893 col = col_GREEN;
2894 } else if (m_FixedPts && label->IsFixedPt()) {
2895 col = col_RED;
2896 } else if (m_ExportedPts && label->IsExportedPt()) {
2897 col = col_TURQUOISE;
2898 } else {
2899 continue;
2902 // Stations are sorted by blob type, so colour changes are infrequent.
2903 if (col != prev_col) {
2904 SetColour(col);
2905 prev_col = col;
2907 DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2909 EndBlobs();
2912 void GfxCore::DrawIndicators()
2914 // Draw colour key.
2915 if (m_ColourKey) {
2916 drawing_list key_list = LIST_LIMIT_;
2917 switch (m_ColourBy) {
2918 case COLOUR_BY_DEPTH:
2919 key_list = LIST_DEPTH_KEY; break;
2920 case COLOUR_BY_DATE:
2921 key_list = LIST_DATE_KEY; break;
2922 case COLOUR_BY_ERROR:
2923 key_list = LIST_ERROR_KEY; break;
2924 case COLOUR_BY_GRADIENT:
2925 key_list = LIST_GRADIENT_KEY; break;
2926 case COLOUR_BY_LENGTH:
2927 key_list = LIST_LENGTH_KEY; break;
2929 if (key_list != LIST_LIMIT_) {
2930 DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
2931 GetYSize() - KEY_OFFSET_Y, 0);
2935 // Draw compass or elevation/heading indicators.
2936 if (m_Compass || m_Clino) {
2937 if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2940 // Draw scalebar.
2941 if (m_Scalebar) {
2942 DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2946 void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2947 glaTexCoord tex_x, glaTexCoord tex_y,
2948 Double factor)
2950 SetColour(col_WHITE, factor);
2951 PlaceVertex(v, tex_x, tex_y);
2954 void GfxCore::SetDepthColour(Double z, Double factor) {
2955 // Set the drawing colour based on the altitude.
2956 Double z_ext = m_Parent->GetDepthExtent();
2958 z -= m_Parent->GetDepthMin();
2959 // points arising from tubes may be slightly outside the limits...
2960 if (z < 0) z = 0;
2961 if (z > z_ext) z = z_ext;
2963 if (z == 0) {
2964 SetColour(GetPen(0), factor);
2965 return;
2968 assert(z_ext > 0.0);
2969 Double how_far = z / z_ext;
2970 assert(how_far >= 0.0);
2971 assert(how_far <= 1.0);
2973 int band = int(floor(how_far * (GetNumColourBands() - 1)));
2974 GLAPen pen1 = GetPen(band);
2975 if (band < GetNumColourBands() - 1) {
2976 const GLAPen& pen2 = GetPen(band + 1);
2978 Double interval = z_ext / (GetNumColourBands() - 1);
2979 Double into_band = z / interval - band;
2981 // printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2982 // z_offset, interval, band);
2983 // FIXME: why do we need to clamp here? Is it because the walls can
2984 // extend further up/down than the centre-line?
2985 if (into_band < 0.0) into_band = 0.0;
2986 if (into_band > 1.0) into_band = 1.0;
2987 assert(into_band >= 0.0);
2988 assert(into_band <= 1.0);
2990 pen1.Interpolate(pen2, into_band);
2992 SetColour(pen1, factor);
2995 void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2997 SetDepthColour(v.GetZ(), factor);
2998 PlaceVertex(v);
3001 void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
3002 glaTexCoord tex_x, glaTexCoord tex_y,
3003 Double factor)
3005 SetDepthColour(v.GetZ(), factor);
3006 PlaceVertex(v, tex_x, tex_y);
3009 void GfxCore::SplitLineAcrossBands(int band, int band2,
3010 const Vector3 &p, const Vector3 &q,
3011 Double factor)
3013 const int step = (band < band2) ? 1 : -1;
3014 for (int i = band; i != band2; i += step) {
3015 const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3017 // Find the intersection point of the line p -> q
3018 // with the plane parallel to the xy-plane with z-axis intersection z.
3019 assert(q.GetZ() - p.GetZ() != 0.0);
3021 const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3022 // assert(0.0 <= t && t <= 1.0); FIXME: rounding problems!
3024 const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3025 const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3027 PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
3031 int GfxCore::GetDepthColour(Double z) const
3033 // Return the (0-based) depth colour band index for a z-coordinate.
3034 Double z_ext = m_Parent->GetDepthExtent();
3035 z -= m_Parent->GetDepthMin();
3036 // We seem to get rounding differences causing z to sometimes be slightly
3037 // less than GetDepthMin() here, and it can certainly be true for passage
3038 // tubes, so just clamp the value to 0.
3039 if (z <= 0) return 0;
3040 // We seem to get rounding differences causing z to sometimes exceed z_ext
3041 // by a small amount here (see: http://trac.survex.com/ticket/26) and it
3042 // can certainly be true for passage tubes, so just clamp the value.
3043 if (z >= z_ext) return GetNumColourBands() - 1;
3044 return int(z / z_ext * (GetNumColourBands() - 1));
3047 Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
3049 // Return the z-coordinate of the depth colour boundary between
3050 // two adjacent depth colour bands (specified by 0-based indices).
3052 assert((a == b - 1) || (a == b + 1));
3053 if (GetNumColourBands() == 1) return 0;
3055 int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
3056 Double z_ext = m_Parent->GetDepthExtent();
3057 return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
3060 void GfxCore::AddPolyline(const traverse & centreline)
3062 BeginPolyline();
3063 SetColour(col_WHITE);
3064 vector<PointInfo>::const_iterator i = centreline.begin();
3065 PlaceVertex(*i);
3066 ++i;
3067 while (i != centreline.end()) {
3068 PlaceVertex(*i);
3069 ++i;
3071 EndPolyline();
3074 void GfxCore::AddPolylineShadow(const traverse & centreline)
3076 BeginPolyline();
3077 const double z = -0.5 * m_Parent->GetZExtent();
3078 vector<PointInfo>::const_iterator i = centreline.begin();
3079 PlaceVertex(i->GetX(), i->GetY(), z);
3080 ++i;
3081 while (i != centreline.end()) {
3082 PlaceVertex(i->GetX(), i->GetY(), z);
3083 ++i;
3085 EndPolyline();
3088 void GfxCore::AddPolylineDepth(const traverse & centreline)
3090 BeginPolyline();
3091 vector<PointInfo>::const_iterator i, prev_i;
3092 i = centreline.begin();
3093 int band0 = GetDepthColour(i->GetZ());
3094 PlaceVertexWithDepthColour(*i);
3095 prev_i = i;
3096 ++i;
3097 while (i != centreline.end()) {
3098 int band = GetDepthColour(i->GetZ());
3099 if (band != band0) {
3100 SplitLineAcrossBands(band0, band, *prev_i, *i);
3101 band0 = band;
3103 PlaceVertexWithDepthColour(*i);
3104 prev_i = i;
3105 ++i;
3107 EndPolyline();
3110 void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3111 const Vector3 &c, const Vector3 &d)
3113 Vector3 normal = (a - c) * (d - b);
3114 normal.normalise();
3115 Double factor = dot(normal, light) * .3 + .7;
3116 glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3117 glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3118 // FIXME: should plot triangles instead to avoid rendering glitches.
3119 BeginQuadrilaterals();
3120 PlaceVertexWithColour(a, 0, 0, factor);
3121 PlaceVertexWithColour(b, w, 0, factor);
3122 PlaceVertexWithColour(c, w, h, factor);
3123 PlaceVertexWithColour(d, 0, h, factor);
3124 EndQuadrilaterals();
3127 void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3128 const Vector3 &c, const Vector3 &d)
3130 Vector3 normal = (a - c) * (d - b);
3131 normal.normalise();
3132 Double factor = dot(normal, light) * .3 + .7;
3133 int a_band, b_band, c_band, d_band;
3134 a_band = GetDepthColour(a.GetZ());
3135 a_band = min(max(a_band, 0), GetNumColourBands());
3136 b_band = GetDepthColour(b.GetZ());
3137 b_band = min(max(b_band, 0), GetNumColourBands());
3138 c_band = GetDepthColour(c.GetZ());
3139 c_band = min(max(c_band, 0), GetNumColourBands());
3140 d_band = GetDepthColour(d.GetZ());
3141 d_band = min(max(d_band, 0), GetNumColourBands());
3142 // All this splitting is incorrect - we need to make a separate polygon
3143 // for each depth band...
3144 glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3145 glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3146 BeginPolygon();
3147 //// PlaceNormal(normal);
3148 PlaceVertexWithDepthColour(a, 0, 0, factor);
3149 if (a_band != b_band) {
3150 SplitLineAcrossBands(a_band, b_band, a, b, factor);
3152 PlaceVertexWithDepthColour(b, w, 0, factor);
3153 if (b_band != c_band) {
3154 SplitLineAcrossBands(b_band, c_band, b, c, factor);
3156 PlaceVertexWithDepthColour(c, w, h, factor);
3157 if (c_band != d_band) {
3158 SplitLineAcrossBands(c_band, d_band, c, d, factor);
3160 PlaceVertexWithDepthColour(d, 0, h, factor);
3161 if (d_band != a_band) {
3162 SplitLineAcrossBands(d_band, a_band, d, a, factor);
3164 EndPolygon();
3167 void GfxCore::SetColourFromDate(int date, Double factor)
3169 // Set the drawing colour based on a date.
3171 if (date == -1) {
3172 // Undated.
3173 SetColour(col_WHITE, factor);
3174 return;
3177 int date_offset = date - m_Parent->GetDateMin();
3178 if (date_offset == 0) {
3179 // Earliest date - handle as a special case for the single date case.
3180 SetColour(GetPen(0), factor);
3181 return;
3184 int date_ext = m_Parent->GetDateExtent();
3185 Double how_far = (Double)date_offset / date_ext;
3186 assert(how_far >= 0.0);
3187 assert(how_far <= 1.0);
3188 SetColourFrom01(how_far, factor);
3191 void GfxCore::AddPolylineDate(const traverse & centreline)
3193 BeginPolyline();
3194 vector<PointInfo>::const_iterator i, prev_i;
3195 i = centreline.begin();
3196 int date = i->GetDate();
3197 SetColourFromDate(date, 1.0);
3198 PlaceVertex(*i);
3199 prev_i = i;
3200 while (++i != centreline.end()) {
3201 int newdate = i->GetDate();
3202 if (newdate != date) {
3203 EndPolyline();
3204 BeginPolyline();
3205 date = newdate;
3206 SetColourFromDate(date, 1.0);
3207 PlaceVertex(*prev_i);
3209 PlaceVertex(*i);
3210 prev_i = i;
3212 EndPolyline();
3215 static int static_date_hack; // FIXME
3217 void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3218 const Vector3 &c, const Vector3 &d)
3220 Vector3 normal = (a - c) * (d - b);
3221 normal.normalise();
3222 Double factor = dot(normal, light) * .3 + .7;
3223 int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3224 int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3225 // FIXME: should plot triangles instead to avoid rendering glitches.
3226 BeginQuadrilaterals();
3227 //// PlaceNormal(normal);
3228 SetColourFromDate(static_date_hack, factor);
3229 PlaceVertex(a, 0, 0);
3230 PlaceVertex(b, w, 0);
3231 PlaceVertex(c, w, h);
3232 PlaceVertex(d, 0, h);
3233 EndQuadrilaterals();
3236 static double static_E_hack; // FIXME
3238 void GfxCore::SetColourFromError(double E, Double factor)
3240 // Set the drawing colour based on an error value.
3242 if (E < 0) {
3243 SetColour(col_WHITE, factor);
3244 return;
3247 Double how_far = E / MAX_ERROR;
3248 assert(how_far >= 0.0);
3249 if (how_far > 1.0) how_far = 1.0;
3250 SetColourFrom01(how_far, factor);
3253 void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3254 const Vector3 &c, const Vector3 &d)
3256 Vector3 normal = (a - c) * (d - b);
3257 normal.normalise();
3258 Double factor = dot(normal, light) * .3 + .7;
3259 int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3260 int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3261 // FIXME: should plot triangles instead to avoid rendering glitches.
3262 BeginQuadrilaterals();
3263 //// PlaceNormal(normal);
3264 SetColourFromError(static_E_hack, factor);
3265 PlaceVertex(a, 0, 0);
3266 PlaceVertex(b, w, 0);
3267 PlaceVertex(c, w, h);
3268 PlaceVertex(d, 0, h);
3269 EndQuadrilaterals();
3272 void GfxCore::AddPolylineError(const traverse & centreline)
3274 BeginPolyline();
3275 SetColourFromError(centreline.E, 1.0);
3276 vector<PointInfo>::const_iterator i;
3277 for(i = centreline.begin(); i != centreline.end(); ++i) {
3278 PlaceVertex(*i);
3280 EndPolyline();
3283 // gradient is in *radians*.
3284 void GfxCore::SetColourFromGradient(double gradient, Double factor)
3286 // Set the drawing colour based on the gradient of the leg.
3288 const Double GRADIENT_MAX = M_PI_2;
3289 gradient = fabs(gradient);
3290 Double how_far = gradient / GRADIENT_MAX;
3291 SetColourFrom01(how_far, factor);
3294 void GfxCore::AddPolylineGradient(const traverse & centreline)
3296 vector<PointInfo>::const_iterator i, prev_i;
3297 i = centreline.begin();
3298 prev_i = i;
3299 while (++i != centreline.end()) {
3300 BeginPolyline();
3301 SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3302 PlaceVertex(*prev_i);
3303 PlaceVertex(*i);
3304 prev_i = i;
3305 EndPolyline();
3309 static double static_gradient_hack; // FIXME
3311 void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3312 const Vector3 &c, const Vector3 &d)
3314 Vector3 normal = (a - c) * (d - b);
3315 normal.normalise();
3316 Double factor = dot(normal, light) * .3 + .7;
3317 int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3318 int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3319 // FIXME: should plot triangles instead to avoid rendering glitches.
3320 BeginQuadrilaterals();
3321 //// PlaceNormal(normal);
3322 SetColourFromGradient(static_gradient_hack, factor);
3323 PlaceVertex(a, 0, 0);
3324 PlaceVertex(b, w, 0);
3325 PlaceVertex(c, w, h);
3326 PlaceVertex(d, 0, h);
3327 EndQuadrilaterals();
3330 void GfxCore::SetColourFromLength(double length, Double factor)
3332 // Set the drawing colour based on log(length_of_leg).
3334 Double log_len = log10(length);
3335 Double how_far = log_len / LOG_LEN_MAX;
3336 how_far = max(how_far, 0.0);
3337 how_far = min(how_far, 1.0);
3338 SetColourFrom01(how_far, factor);
3341 void GfxCore::SetColourFrom01(double how_far, Double factor)
3343 double b;
3344 double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3345 int band(b);
3346 GLAPen pen1 = GetPen(band);
3347 // With 24bit colour, interpolating by less than this can have no effect.
3348 if (into_band >= 1.0 / 512.0) {
3349 const GLAPen& pen2 = GetPen(band + 1);
3350 pen1.Interpolate(pen2, into_band);
3352 SetColour(pen1, factor);
3355 void GfxCore::AddPolylineLength(const traverse & centreline)
3357 vector<PointInfo>::const_iterator i, prev_i;
3358 i = centreline.begin();
3359 prev_i = i;
3360 while (++i != centreline.end()) {
3361 BeginPolyline();
3362 SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3363 PlaceVertex(*prev_i);
3364 PlaceVertex(*i);
3365 prev_i = i;
3366 EndPolyline();
3370 static double static_length_hack; // FIXME
3372 void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3373 const Vector3 &c, const Vector3 &d)
3375 Vector3 normal = (a - c) * (d - b);
3376 normal.normalise();
3377 Double factor = dot(normal, light) * .3 + .7;
3378 int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3379 int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3380 // FIXME: should plot triangles instead to avoid rendering glitches.
3381 BeginQuadrilaterals();
3382 //// PlaceNormal(normal);
3383 SetColourFromLength(static_length_hack, factor);
3384 PlaceVertex(a, 0, 0);
3385 PlaceVertex(b, w, 0);
3386 PlaceVertex(c, w, h);
3387 PlaceVertex(d, 0, h);
3388 EndQuadrilaterals();
3391 void
3392 GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3394 assert(centreline.size() > 1);
3395 Vector3 U[4];
3396 XSect prev_pt_v;
3397 Vector3 last_right(1.0, 0.0, 0.0);
3399 // FIXME: it's not simple to set the colour of a tube based on error...
3400 // static_E_hack = something...
3401 vector<XSect>::iterator i = centreline.begin();
3402 vector<XSect>::size_type segment = 0;
3403 while (i != centreline.end()) {
3404 // get the coordinates of this vertex
3405 XSect & pt_v = *i++;
3407 bool cover_end = false;
3409 Vector3 right, up;
3411 const Vector3 up_v(0.0, 0.0, 1.0);
3413 if (segment == 0) {
3414 assert(i != centreline.end());
3415 // first segment
3417 // get the coordinates of the next vertex
3418 const XSect & next_pt_v = *i;
3420 // calculate vector from this pt to the next one
3421 Vector3 leg_v = next_pt_v - pt_v;
3423 // obtain a vector in the LRUD plane
3424 right = leg_v * up_v;
3425 if (right.magnitude() == 0) {
3426 right = last_right;
3427 // Obtain a second vector in the LRUD plane,
3428 // perpendicular to the first.
3429 //up = right * leg_v;
3430 up = up_v;
3431 } else {
3432 last_right = right;
3433 up = up_v;
3436 cover_end = true;
3437 static_date_hack = next_pt_v.GetDate();
3438 } else if (segment + 1 == centreline.size()) {
3439 // last segment
3441 // Calculate vector from the previous pt to this one.
3442 Vector3 leg_v = pt_v - prev_pt_v;
3444 // Obtain a horizontal vector in the LRUD plane.
3445 right = leg_v * up_v;
3446 if (right.magnitude() == 0) {
3447 right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3448 // Obtain a second vector in the LRUD plane,
3449 // perpendicular to the first.
3450 //up = right * leg_v;
3451 up = up_v;
3452 } else {
3453 last_right = right;
3454 up = up_v;
3457 cover_end = true;
3458 static_date_hack = pt_v.GetDate();
3459 } else {
3460 assert(i != centreline.end());
3461 // Intermediate segment.
3463 // Get the coordinates of the next vertex.
3464 const XSect & next_pt_v = *i;
3466 // Calculate vectors from this vertex to the
3467 // next vertex, and from the previous vertex to
3468 // this one.
3469 Vector3 leg1_v = pt_v - prev_pt_v;
3470 Vector3 leg2_v = next_pt_v - pt_v;
3472 // Obtain horizontal vectors perpendicular to
3473 // both legs, then normalise and average to get
3474 // a horizontal bisector.
3475 Vector3 r1 = leg1_v * up_v;
3476 Vector3 r2 = leg2_v * up_v;
3477 r1.normalise();
3478 r2.normalise();
3479 right = r1 + r2;
3480 if (right.magnitude() == 0) {
3481 // This is the "mid-pitch" case...
3482 right = last_right;
3484 if (r1.magnitude() == 0) {
3485 up = up_v;
3487 // Rotate pitch section to minimise the
3488 // "tortional stress" - FIXME: use
3489 // triangles instead of rectangles?
3490 int shift = 0;
3491 Double maxdotp = 0;
3493 // Scale to unit vectors in the LRUD plane.
3494 right.normalise();
3495 up.normalise();
3496 Vector3 vec = up - right;
3497 for (int orient = 0; orient <= 3; ++orient) {
3498 Vector3 tmp = U[orient] - prev_pt_v;
3499 tmp.normalise();
3500 Double dotp = dot(vec, tmp);
3501 if (dotp > maxdotp) {
3502 maxdotp = dotp;
3503 shift = orient;
3506 if (shift) {
3507 if (shift != 2) {
3508 Vector3 temp(U[0]);
3509 U[0] = U[shift];
3510 U[shift] = U[2];
3511 U[2] = U[shift ^ 2];
3512 U[shift ^ 2] = temp;
3513 } else {
3514 swap(U[0], U[2]);
3515 swap(U[1], U[3]);
3518 #if 0
3519 // Check that the above code actually permuted
3520 // the vertices correctly.
3521 shift = 0;
3522 maxdotp = 0;
3523 for (int j = 0; j <= 3; ++j) {
3524 Vector3 tmp = U[j] - prev_pt_v;
3525 tmp.normalise();
3526 Double dotp = dot(vec, tmp);
3527 if (dotp > maxdotp) {
3528 maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3529 shift = j;
3532 if (shift) {
3533 printf("New shift = %d!\n", shift);
3534 shift = 0;
3535 maxdotp = 0;
3536 for (int j = 0; j <= 3; ++j) {
3537 Vector3 tmp = U[j] - prev_pt_v;
3538 tmp.normalise();
3539 Double dotp = dot(vec, tmp);
3540 printf(" %d : %.8f\n", j, dotp);
3543 #endif
3544 } else {
3545 up = up_v;
3547 last_right = right;
3548 static_date_hack = pt_v.GetDate();
3551 // Scale to unit vectors in the LRUD plane.
3552 right.normalise();
3553 up.normalise();
3555 Double l = fabs(pt_v.GetL());
3556 Double r = fabs(pt_v.GetR());
3557 Double u = fabs(pt_v.GetU());
3558 Double d = fabs(pt_v.GetD());
3560 // Produce coordinates of the corners of the LRUD "plane".
3561 Vector3 v[4];
3562 v[0] = pt_v - right * l + up * u;
3563 v[1] = pt_v + right * r + up * u;
3564 v[2] = pt_v + right * r - up * d;
3565 v[3] = pt_v - right * l - up * d;
3567 if (draw) {
3568 const Vector3 & delta = pt_v - prev_pt_v;
3569 static_length_hack = delta.magnitude();
3570 static_gradient_hack = delta.gradient();
3571 if (segment > 0) {
3572 (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3573 (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3574 (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3575 (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3578 if (cover_end) {
3579 if (segment == 0) {
3580 (this->*AddQuad)(v[0], v[1], v[2], v[3]);
3581 } else {
3582 (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3587 prev_pt_v = pt_v;
3588 U[0] = v[0];
3589 U[1] = v[1];
3590 U[2] = v[2];
3591 U[3] = v[3];
3593 pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3595 ++segment;
3599 void GfxCore::FullScreenMode()
3601 m_Parent->ViewFullScreen();
3604 bool GfxCore::IsFullScreen() const
3606 return m_Parent->IsFullScreen();
3609 bool GfxCore::FullScreenModeShowingMenus() const
3611 return m_Parent->FullScreenModeShowingMenus();
3614 void GfxCore::FullScreenModeShowMenus(bool show)
3616 m_Parent->FullScreenModeShowMenus(show);
3619 void
3620 GfxCore::MoveViewer(double forward, double up, double right)
3622 double cT = cos(rad(m_TiltAngle));
3623 double sT = sin(rad(m_TiltAngle));
3624 double cP = cos(rad(m_PanAngle));
3625 double sP = sin(rad(m_PanAngle));
3626 Vector3 v_forward(cT * sP, cT * cP, sT);
3627 Vector3 v_up(sT * sP, sT * cP, -cT);
3628 Vector3 v_right(-cP, sP, 0);
3629 assert(fabs(dot(v_forward, v_up)) < 1e-6);
3630 assert(fabs(dot(v_forward, v_right)) < 1e-6);
3631 assert(fabs(dot(v_right, v_up)) < 1e-6);
3632 Vector3 move = v_forward * forward + v_up * up + v_right * right;
3633 AddTranslation(-move);
3634 // Show current position.
3635 m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3636 ForceRefresh();
3639 PresentationMark GfxCore::GetView() const
3641 return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3642 m_PanAngle, -m_TiltAngle, m_Scale);
3645 void GfxCore::SetView(const PresentationMark & p)
3647 m_SwitchingTo = 0;
3648 SetTranslation(p - m_Parent->GetOffset());
3649 m_PanAngle = p.angle;
3650 m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3651 SetRotation(m_PanAngle, m_TiltAngle);
3652 SetScale(p.scale);
3653 ForceRefresh();
3656 void GfxCore::PlayPres(double speed, bool change_speed) {
3657 if (!change_speed || presentation_mode == 0) {
3658 if (speed == 0.0) {
3659 presentation_mode = 0;
3660 return;
3662 presentation_mode = PLAYING;
3663 next_mark = m_Parent->GetPresMark(MARK_FIRST);
3664 SetView(next_mark);
3665 next_mark_time = 0; // There already!
3666 this_mark_total = 0;
3667 pres_reverse = (speed < 0);
3670 if (change_speed) pres_speed = speed;
3672 if (speed != 0.0) {
3673 bool new_pres_reverse = (speed < 0);
3674 if (new_pres_reverse != pres_reverse) {
3675 pres_reverse = new_pres_reverse;
3676 if (pres_reverse) {
3677 next_mark = m_Parent->GetPresMark(MARK_PREV);
3678 } else {
3679 next_mark = m_Parent->GetPresMark(MARK_NEXT);
3681 swap(this_mark_total, next_mark_time);
3686 void GfxCore::SetColourBy(int colour_by) {
3687 m_ColourBy = colour_by;
3688 switch (colour_by) {
3689 case COLOUR_BY_DEPTH:
3690 AddQuad = &GfxCore::AddQuadrilateralDepth;
3691 AddPoly = &GfxCore::AddPolylineDepth;
3692 break;
3693 case COLOUR_BY_DATE:
3694 AddQuad = &GfxCore::AddQuadrilateralDate;
3695 AddPoly = &GfxCore::AddPolylineDate;
3696 break;
3697 case COLOUR_BY_ERROR:
3698 AddQuad = &GfxCore::AddQuadrilateralError;
3699 AddPoly = &GfxCore::AddPolylineError;
3700 break;
3701 case COLOUR_BY_GRADIENT:
3702 AddQuad = &GfxCore::AddQuadrilateralGradient;
3703 AddPoly = &GfxCore::AddPolylineGradient;
3704 break;
3705 case COLOUR_BY_LENGTH:
3706 AddQuad = &GfxCore::AddQuadrilateralLength;
3707 AddPoly = &GfxCore::AddPolylineLength;
3708 break;
3709 default: // case COLOUR_BY_NONE:
3710 AddQuad = &GfxCore::AddQuadrilateral;
3711 AddPoly = &GfxCore::AddPolyline;
3712 break;
3715 InvalidateList(LIST_UNDERGROUND_LEGS);
3716 InvalidateList(LIST_SURFACE_LEGS);
3717 InvalidateList(LIST_TUBES);
3719 ForceRefresh();
3722 bool GfxCore::ExportMovie(const wxString & fnm)
3724 int width;
3725 int height;
3726 GetSize(&width, &height);
3727 // Round up to next multiple of 2 (required by ffmpeg).
3728 width += (width & 1);
3729 height += (height & 1);
3731 movie = new MovieMaker();
3733 // FIXME: This should really use fn_str() - currently we probably can't
3734 // save to a Unicode path on wxmsw.
3735 if (!movie->Open(fnm.mb_str(), width, height)) {
3736 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3737 delete movie;
3738 movie = NULL;
3739 return false;
3742 PlayPres(1);
3743 return true;
3746 void
3747 GfxCore::OnPrint(const wxString &filename, const wxString &title,
3748 const wxString &datestamp, time_t datestamp_numeric,
3749 const wxString &cs_proj,
3750 bool close_after_print)
3752 svxPrintDlg * p;
3753 p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3754 datestamp, datestamp_numeric,
3755 m_PanAngle, m_TiltAngle,
3756 m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3757 m_Entrances, m_FixedPts, m_ExportedPts,
3758 true, close_after_print);
3759 p->Show(true);
3762 void
3763 GfxCore::OnExport(const wxString &filename, const wxString &title,
3764 const wxString &datestamp, time_t datestamp_numeric,
3765 const wxString &cs_proj)
3767 // Fill in "right_bearing" for each cross-section.
3768 list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3769 list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3770 while (trav != tend) {
3771 SkinPassage(*trav, false);
3772 ++trav;
3775 svxPrintDlg * p;
3776 p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3777 datestamp, datestamp_numeric,
3778 m_PanAngle, m_TiltAngle,
3779 m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3780 m_Entrances, m_FixedPts, m_ExportedPts,
3781 false);
3782 p->Show(true);
3785 static wxCursor
3786 make_cursor(const unsigned char * bits, const unsigned char * mask,
3787 int hotx, int hoty)
3789 #if defined __WXMSW__ || defined __WXMAC__
3790 # ifdef __WXMAC__
3791 // The default Mac cursor is black with a white edge, so
3792 // invert our custom cursors to match.
3793 char b[128];
3794 for (int i = 0; i < 128; ++i)
3795 b[i] = bits[i] ^ 0xff;
3796 # else
3797 const char * b = reinterpret_cast<const char *>(bits);
3798 # endif
3799 wxBitmap cursor_bitmap(b, 32, 32);
3800 wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3801 cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3802 wxImage cursor_image = cursor_bitmap.ConvertToImage();
3803 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3804 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3805 return wxCursor(cursor_image);
3806 #else
3807 return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3808 (const char *)mask, wxBLACK, wxWHITE);
3809 #endif
3812 const
3813 #include "hand.xbm"
3814 const
3815 #include "handmask.xbm"
3817 const
3818 #include "brotate.xbm"
3819 const
3820 #include "brotatemask.xbm"
3822 const
3823 #include "vrotate.xbm"
3824 const
3825 #include "vrotatemask.xbm"
3827 const
3828 #include "rotate.xbm"
3829 const
3830 #include "rotatemask.xbm"
3832 const
3833 #include "rotatezoom.xbm"
3834 const
3835 #include "rotatezoommask.xbm"
3837 void
3838 GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
3840 // Check if we're already showing that cursor.
3841 if (current_cursor == new_cursor) return;
3843 current_cursor = new_cursor;
3844 switch (current_cursor) {
3845 case GfxCore::CURSOR_DEFAULT:
3846 GLACanvas::SetCursor(wxNullCursor);
3847 break;
3848 case GfxCore::CURSOR_POINTING_HAND:
3849 GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3850 break;
3851 case GfxCore::CURSOR_DRAGGING_HAND:
3852 GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3853 break;
3854 case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3855 GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3856 break;
3857 case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3858 GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3859 break;
3860 case GfxCore::CURSOR_ROTATE_VERTICALLY:
3861 GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3862 break;
3863 case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3864 GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3865 break;
3866 case GfxCore::CURSOR_ZOOM:
3867 GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3868 break;
3869 case GfxCore::CURSOR_ZOOM_ROTATE:
3870 GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3871 break;
3875 bool GfxCore::MeasuringLineActive() const
3877 if (Animating()) return false;
3878 return HereIsReal() || m_there;
3881 bool GfxCore::HandleRClick(wxPoint point)
3883 if (PointWithinCompass(point)) {
3884 // Pop up menu.
3885 wxMenu menu;
3886 /* TRANSLATORS: View *looking* North */
3887 menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3888 /* TRANSLATORS: View *looking* East */
3889 menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3890 /* TRANSLATORS: View *looking* South */
3891 menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3892 /* TRANSLATORS: View *looking* West */
3893 menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3894 menu.AppendSeparator();
3895 /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
3896 menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
3897 /* TRANSLATORS: tickable menu item in View menu.
3899 * Degrees are the angular measurement where there are 360 in a full
3900 * circle. */
3901 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3902 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3903 PopupMenu(&menu);
3904 return true;
3907 if (PointWithinClino(point)) {
3908 // Pop up menu.
3909 wxMenu menu;
3910 menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3911 menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3912 menu.AppendSeparator();
3913 /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
3914 menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3915 /* TRANSLATORS: tickable menu item in View menu.
3917 * Degrees are the angular measurement where there are 360 in a full
3918 * circle. */
3919 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3920 /* TRANSLATORS: tickable menu item in View menu.
3922 * Show the tilt of the survey as a percentage gradient (100% = 45
3923 * degrees = 50 grad). */
3924 menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
3925 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3926 PopupMenu(&menu);
3927 return true;
3930 if (PointWithinScaleBar(point)) {
3931 // Pop up menu.
3932 wxMenu menu;
3933 /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
3934 menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3935 /* TRANSLATORS: tickable menu item in View menu.
3937 * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3939 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3940 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3941 PopupMenu(&menu);
3942 return true;
3945 if (PointWithinColourKey(point)) {
3946 // Pop up menu.
3947 wxMenu menu;
3948 menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3949 menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3950 menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
3951 menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
3952 menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
3953 menu.AppendSeparator();
3954 /* TRANSLATORS: Menu item which turns off the colour key.
3955 * The "Colour Key" is the thing in aven showing which colour
3956 * corresponds to which depth, date, survey closure error, etc. */
3957 menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3958 if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
3959 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3960 else if (m_ColourBy == COLOUR_BY_GRADIENT)
3961 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3962 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3963 PopupMenu(&menu);
3964 return true;
3967 return false;
3970 void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3972 if (centred) {
3973 p1.x = p2.x + (p1.x - p2.x) * 2;
3974 p1.y = p2.y + (p1.y - p2.y) * 2;
3976 if (aspect) {
3977 #if 0 // FIXME: This needs more work.
3978 int sx = GetXSize();
3979 int sy = GetYSize();
3980 int dx = p1.x - p2.x;
3981 int dy = p1.y - p2.y;
3982 int dy_new = dx * sy / sx;
3983 if (abs(dy_new) >= abs(dy)) {
3984 p1.y += (dy_new - dy) / 2;
3985 p2.y -= (dy_new - dy) / 2;
3986 } else {
3987 int dx_new = dy * sx / sy;
3988 p1.x += (dx_new - dx) / 2;
3989 p2.x -= (dx_new - dx) / 2;
3991 #endif
3993 zoombox.set(p1, p2);
3994 ForceRefresh();
3997 void GfxCore::ZoomBoxGo()
3999 if (!zoombox.active()) return;
4001 int width = GetXSize();
4002 int height = GetYSize();
4004 TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
4005 -0.5 * (zoombox.y1 + zoombox.y2 - height));
4006 int box_w = abs(zoombox.x1 - zoombox.x2);
4007 int box_h = abs(zoombox.y1 - zoombox.y2);
4009 double factor = min(double(width) / box_w, double(height) / box_h);
4011 zoombox.unset();
4013 SetScale(GetScale() * factor);