Fix comment typo
[survex.git] / src / gfxcore.cc
blobd6a522be06802e93bd8e67288204ec25efb924bb
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,2016,2017,2018 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 "aventreectrl.h"
34 #include "date.h"
35 #include "filename.h"
36 #include "gfxcore.h"
37 #include "hash.h"
38 #include "mainfrm.h"
39 #include "message.h"
40 #include "useful.h"
41 #include "printing.h"
42 #include "guicontrol.h"
43 #include "moviemaker.h"
45 #include <wx/confbase.h>
46 #include <wx/wfstream.h>
47 #include <wx/image.h>
48 #include <wx/zipstrm.h>
50 #include <proj_api.h>
52 const unsigned long DEFAULT_HGT_DIM = 3601;
53 const unsigned long DEFAULT_HGT_SIZE = sqrd(DEFAULT_HGT_DIM) * 2;
55 // Values for m_SwitchingTo
56 #define PLAN 1
57 #define ELEVATION 2
58 #define NORTH 3
59 #define EAST 4
60 #define SOUTH 5
61 #define WEST 6
63 // Any error value higher than this is clamped to this.
64 #define MAX_ERROR 12.0
66 // Any length greater than pow(10, LOG_LEN_MAX) will be clamped to this.
67 const Double LOG_LEN_MAX = 1.5;
69 // How many bins per letter height to use when working out non-overlapping
70 // labels.
71 const unsigned int QUANTISE_FACTOR = 2;
73 #include "avenpal.h"
75 static const int INDICATOR_BOX_SIZE = 60;
76 static const int INDICATOR_GAP = 2;
77 static const int INDICATOR_MARGIN = 5;
78 static const int INDICATOR_OFFSET_X = 15;
79 static const int INDICATOR_OFFSET_Y = 15;
80 static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
81 static const int KEY_OFFSET_X = 10;
82 static const int KEY_OFFSET_Y = 10;
83 static const int KEY_EXTRA_LEFT_MARGIN = 2;
84 static const int KEY_BLOCK_WIDTH = 20;
85 static const int KEY_BLOCK_HEIGHT = 16;
86 static const int TICK_LENGTH = 4;
87 static const int SCALE_BAR_OFFSET_X = 15;
88 static const int SCALE_BAR_OFFSET_Y = 12;
89 static const int SCALE_BAR_HEIGHT = 12;
91 static const gla_colour TEXT_COLOUR = col_GREEN;
92 static const gla_colour HERE_COLOUR = col_WHITE;
93 static const gla_colour NAME_COLOUR = col_GREEN;
94 static const gla_colour SEL_COLOUR = col_WHITE;
95 // Used with colour by date for legs without date information and with colour
96 // by error for legs not in a loop.
97 static const gla_colour NODATA_COLOUR = col_LIGHT_GREY_2;
99 // Number of entries across and down the hit-test grid:
100 #define HITTEST_SIZE 20
102 // How close the pointer needs to be to a station to be considered:
103 #define MEASURE_THRESHOLD 7
105 // vector for lighting angle
106 static const Vector3 light(.577, .577, .577);
108 BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
109 EVT_PAINT(GfxCore::OnPaint)
110 EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
111 EVT_LEFT_UP(GfxCore::OnLButtonUp)
112 EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
113 EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
114 EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
115 EVT_RIGHT_UP(GfxCore::OnRButtonUp)
116 EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
117 EVT_MOTION(GfxCore::OnMouseMove)
118 EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
119 EVT_SIZE(GfxCore::OnSize)
120 EVT_IDLE(GfxCore::OnIdle)
121 EVT_CHAR(GfxCore::OnKeyPress)
122 END_EVENT_TABLE()
124 GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
125 GLACanvas(parent_win, 100),
126 m_Scale(0.0),
127 initial_scale(1.0),
128 m_ScaleBarWidth(0),
129 m_Control(control),
130 m_LabelGrid(NULL),
131 m_Parent(parent),
132 m_DoneFirstShow(false),
133 m_TiltAngle(0.0),
134 m_PanAngle(0.0),
135 m_Rotating(false),
136 m_RotationStep(0.0),
137 m_SwitchingTo(0),
138 m_Crosses(false),
139 m_Legs(true),
140 m_Splays(SHOW_FADED),
141 m_Dupes(SHOW_DASHED),
142 m_Names(false),
143 m_Scalebar(true),
144 m_ColourKey(true),
145 m_OverlappingNames(false),
146 m_Compass(true),
147 m_Clino(true),
148 m_Tubes(false),
149 m_ColourBy(COLOUR_BY_DEPTH),
150 m_HaveData(false),
151 m_HaveTerrain(true),
152 m_MouseOutsideCompass(false),
153 m_MouseOutsideElev(false),
154 m_Surface(false),
155 m_Entrances(false),
156 m_FixedPts(false),
157 m_ExportedPts(false),
158 m_Grid(false),
159 m_BoundingBox(false),
160 m_Terrain(false),
161 m_Degrees(false),
162 m_Metric(false),
163 m_Percent(false),
164 m_HitTestDebug(false),
165 m_RenderStats(false),
166 m_PointGrid(NULL),
167 m_HitTestGridValid(false),
168 m_here(NULL),
169 m_there(NULL),
170 presentation_mode(0),
171 pres_reverse(false),
172 pres_speed(0.0),
173 movie(NULL),
174 current_cursor(GfxCore::CURSOR_DEFAULT),
175 sqrd_measure_threshold(sqrd(MEASURE_THRESHOLD)),
176 dem(NULL),
177 last_time(0),
178 n_tris(0)
180 AddQuad = &GfxCore::AddQuadrilateralDepth;
181 AddPoly = &GfxCore::AddPolylineDepth;
182 wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
183 wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
184 wxConfigBase::Get()->Read(wxT("percent"), &m_Percent, false);
186 for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
187 m_Pens[pen].SetColour(REDS[pen] / 255.0,
188 GREENS[pen] / 255.0,
189 BLUES[pen] / 255.0);
192 timer.Start();
195 GfxCore::~GfxCore()
197 TryToFreeArrays();
199 delete[] m_PointGrid;
202 void GfxCore::TryToFreeArrays()
204 // Free up any memory allocated for arrays.
205 delete[] m_LabelGrid;
206 m_LabelGrid = NULL;
210 // Initialisation methods
213 void GfxCore::Initialise(bool same_file)
215 // Initialise the view from the parent holding the survey data.
217 TryToFreeArrays();
219 m_DoneFirstShow = false;
221 m_HitTestGridValid = false;
222 m_here = NULL;
223 m_there = NULL;
225 m_MouseOutsideCompass = m_MouseOutsideElev = false;
227 if (!same_file) {
228 // Apply default parameters unless reloading the same file.
229 DefaultParameters();
232 m_HaveData = true;
234 // Clear any cached OpenGL lists which depend on the data.
235 InvalidateList(LIST_SCALE_BAR);
236 InvalidateList(LIST_DEPTH_KEY);
237 InvalidateList(LIST_DATE_KEY);
238 InvalidateList(LIST_ERROR_KEY);
239 InvalidateList(LIST_GRADIENT_KEY);
240 InvalidateList(LIST_LENGTH_KEY);
241 InvalidateList(LIST_UNDERGROUND_LEGS);
242 InvalidateList(LIST_TUBES);
243 InvalidateList(LIST_SURFACE_LEGS);
244 InvalidateList(LIST_BLOBS);
245 InvalidateList(LIST_CROSSES);
246 InvalidateList(LIST_GRID);
247 InvalidateList(LIST_SHADOW);
248 InvalidateList(LIST_TERRAIN);
250 // Set diameter of the viewing volume.
251 auto ext = m_Parent->GetExtent();
252 double cave_diameter = sqrt(sqrd(ext.GetX()) +
253 sqrd(ext.GetY()) +
254 sqrd(ext.GetZ()));
256 // Allow for terrain.
257 double diameter = max(1000.0 * 2, cave_diameter * 2);
259 if (!same_file) {
260 SetVolumeDiameter(diameter);
262 // Set initial scale based on the size of the cave.
263 initial_scale = diameter / cave_diameter;
264 SetScale(initial_scale);
265 } else {
266 // Adjust the position when restricting the view to a subsurvey (or
267 // expanding the view to show the whole survey).
268 AddTranslation(m_Parent->GetOffset() - offsets);
270 // Try to keep the same scale, allowing for the
271 // cave having grown (or shrunk).
272 double rescale = GetVolumeDiameter() / diameter;
273 SetVolumeDiameter(diameter);
274 SetScale(GetScale() / rescale); // ?
275 initial_scale = initial_scale * rescale;
278 offsets = m_Parent->GetOffset();
280 ForceRefresh();
283 void GfxCore::FirstShow()
285 GLACanvas::FirstShow();
287 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
288 list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
289 while (pos != m_Parent->GetLabelsNCEnd()) {
290 LabelInfo* label = *pos++;
291 // Calculate and set the label width for use when plotting
292 // none-overlapping labels.
293 int ext_x;
294 GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
295 label->set_width(unsigned(ext_x) / quantise + 1);
298 m_DoneFirstShow = true;
302 // Recalculating methods
305 void GfxCore::SetScale(Double scale)
307 if (scale < 0.05) {
308 scale = 0.05;
309 } else if (scale > GetVolumeDiameter()) {
310 scale = GetVolumeDiameter();
313 m_Scale = scale;
314 m_HitTestGridValid = false;
315 if (m_here && m_here == &temp_here) SetHere();
317 GLACanvas::SetScale(scale);
320 bool GfxCore::HasUndergroundLegs() const
322 return m_Parent->HasUndergroundLegs();
325 bool GfxCore::HasSplays() const
327 return m_Parent->HasSplays();
330 bool GfxCore::HasDupes() const
332 return m_Parent->HasDupes();
335 bool GfxCore::HasSurfaceLegs() const
337 return m_Parent->HasSurfaceLegs();
340 bool GfxCore::HasTubes() const
342 return m_Parent->HasTubes();
345 void GfxCore::UpdateBlobs()
347 InvalidateList(LIST_BLOBS);
351 // Event handlers
354 void GfxCore::OnLeaveWindow(wxMouseEvent&) {
355 SetHere();
356 ClearCoords();
359 void GfxCore::OnIdle(wxIdleEvent& event)
361 // Handle an idle event.
362 if (Animating()) {
363 Animate();
364 // If still animating, we want more idle events.
365 if (Animating())
366 event.RequestMore();
367 } else {
368 // If we're idle, don't show a bogus FPS next time we render.
369 last_time = 0;
373 void GfxCore::OnPaint(wxPaintEvent&)
375 // Redraw the window.
377 // Get a graphics context.
378 wxPaintDC dc(this);
380 if (m_HaveData) {
381 // Make sure we're initialised.
382 bool first_time = !m_DoneFirstShow;
383 if (first_time) {
384 FirstShow();
387 StartDrawing();
389 // Clear the background.
390 Clear();
392 // Set up model transformation matrix.
393 SetDataTransform();
395 if (m_Legs || m_Tubes) {
396 if (m_Tubes) {
397 EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
398 DrawList(LIST_TUBES);
399 DisableSmoothPolygons();
402 // Draw the underground legs. Do this last so that anti-aliasing
403 // works over polygons.
404 SetColour(col_GREEN);
405 DrawList(LIST_UNDERGROUND_LEGS);
408 if (m_Surface) {
409 // Draw the surface legs.
410 DrawList(LIST_SURFACE_LEGS);
413 if (m_BoundingBox) {
414 DrawShadowedBoundingBox();
416 if (m_Grid) {
417 // Draw the grid.
418 DrawList(LIST_GRID);
421 DrawList(LIST_BLOBS);
423 if (m_Crosses) {
424 DrawList(LIST_CROSSES);
427 if (m_Terrain) {
428 // Disable texturing while drawing terrain.
429 bool texturing = GetTextured();
430 if (texturing) GLACanvas::ToggleTextured();
432 // This is needed if blobs and/or crosses are drawn using lines -
433 // otherwise the terrain doesn't appear when they are enabled.
434 SetDataTransform();
436 // We don't want to be able to see the terrain through itself, so
437 // do a "Z-prepass" - plot the terrain once only updating the
438 // Z-buffer, then again with Z-clipping only plotting where the
439 // depth matches the value in the Z-buffer.
440 DrawListZPrepass(LIST_TERRAIN);
442 if (texturing) GLACanvas::ToggleTextured();
445 SetIndicatorTransform();
447 // Draw station names.
448 if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
449 SetColour(NAME_COLOUR);
451 if (m_OverlappingNames) {
452 SimpleDrawNames();
453 } else {
454 NattyDrawNames();
458 if (!highlighted_survey.empty()) {
459 HighlightSurvey();
462 if (m_HitTestDebug) {
463 // Show the hit test grid bucket sizes...
464 SetColour(m_HitTestGridValid ? col_LIGHT_GREY : col_DARK_GREY);
465 if (m_PointGrid) {
466 for (int i = 0; i != HITTEST_SIZE; ++i) {
467 int x = (GetXSize() + 1) * i / HITTEST_SIZE + 2;
468 for (int j = 0; j != HITTEST_SIZE; ++j) {
469 int square = i + j * HITTEST_SIZE;
470 unsigned long bucket_size = m_PointGrid[square].size();
471 if (bucket_size) {
472 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
473 DrawIndicatorText(x, y, wxString::Format(wxT("%lu"), bucket_size));
479 EnableDashedLines();
480 BeginLines();
481 for (int i = 0; i != HITTEST_SIZE; ++i) {
482 int x = (GetXSize() + 1) * i / HITTEST_SIZE;
483 PlaceIndicatorVertex(x, 0);
484 PlaceIndicatorVertex(x, GetYSize());
486 for (int j = 0; j != HITTEST_SIZE; ++j) {
487 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
488 PlaceIndicatorVertex(0, y);
489 PlaceIndicatorVertex(GetXSize(), y);
491 EndLines();
492 DisableDashedLines();
495 long now = timer.Time();
496 if (m_RenderStats) {
497 // Show stats about rendering.
498 SetColour(col_TURQUOISE);
499 int y = GetYSize() - GetFontSize();
500 if (last_time != 0.0) {
501 // timer.Time() measure in milliseconds.
502 double fps = 1000.0 / (now - last_time);
503 DrawIndicatorText(1, y, wxString::Format(wxT("FPS:% 5.1f"), fps));
505 y -= GetFontSize();
506 DrawIndicatorText(1, y, wxString::Format(wxT("▲:%lu"), (unsigned long)n_tris));
508 last_time = now;
510 // Draw indicators.
512 // There's no advantage in generating an OpenGL list for the
513 // indicators since they change with almost every redraw (and
514 // sometimes several times between redraws). This way we avoid
515 // the need to track when to update the indicator OpenGL list,
516 // and also avoid indicator update bugs when we don't quite get this
517 // right...
518 DrawIndicators();
520 if (zoombox.active()) {
521 SetColour(SEL_COLOUR);
522 EnableDashedLines();
523 BeginPolyline();
524 glaCoord Y = GetYSize();
525 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
526 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y2);
527 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y2);
528 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y1);
529 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
530 EndPolyline();
531 DisableDashedLines();
532 } else if (MeasuringLineActive()) {
533 // Draw "here" and "there".
534 double hx, hy;
535 SetColour(HERE_COLOUR);
536 if (m_here) {
537 double dummy;
538 Transform(*m_here, &hx, &hy, &dummy);
539 if (m_here != &temp_here) DrawRing(hx, hy);
541 if (m_there) {
542 double tx, ty;
543 double dummy;
544 Transform(*m_there, &tx, &ty, &dummy);
545 if (m_here) {
546 BeginLines();
547 PlaceIndicatorVertex(hx, hy);
548 PlaceIndicatorVertex(tx, ty);
549 EndLines();
551 BeginBlobs();
552 DrawBlob(tx, ty);
553 EndBlobs();
557 FinishDrawing();
558 } else {
559 dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
560 dc.Clear();
564 void GfxCore::DrawBoundingBox()
566 const Vector3 v = 0.5 * m_Parent->GetExtent();
568 SetColour(col_BLUE);
569 EnableDashedLines();
570 BeginPolyline();
571 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
572 PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
573 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
574 PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
575 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
576 EndPolyline();
577 BeginPolyline();
578 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
579 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
580 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
581 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
582 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
583 EndPolyline();
584 BeginLines();
585 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
586 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
587 PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
588 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
589 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
590 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
591 PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
592 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
593 EndLines();
594 DisableDashedLines();
597 void GfxCore::DrawShadowedBoundingBox()
599 const Vector3 v = 0.5 * m_Parent->GetExtent();
601 DrawBoundingBox();
603 PolygonOffset(true);
604 SetColour(col_DARK_GREY);
605 BeginQuadrilaterals();
606 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
607 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
608 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
609 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
610 EndQuadrilaterals();
611 PolygonOffset(false);
613 DrawList(LIST_SHADOW);
616 void GfxCore::DrawGrid()
618 // Draw the grid.
619 SetColour(col_RED);
621 // Calculate the extent of the survey, in metres across the screen plane.
622 Double m_across_screen = SurveyUnitsAcrossViewport();
623 // Calculate the length of the scale bar in metres.
624 //--move this elsewhere
625 Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
626 Double t = m_across_screen * 0.75 / size_snap;
627 if (t >= 5.0) {
628 size_snap *= 5.0;
630 else if (t >= 2.0) {
631 size_snap *= 2.0;
634 Double grid_size = size_snap * 0.1;
635 Double edge = grid_size * 2.0;
636 auto ext = m_Parent->GetExtent();
637 Double grid_z = -ext.GetZ() * 0.5 - grid_size;
638 Double left = -ext.GetX() * 0.5 - edge;
639 Double right = ext.GetX() * 0.5 + edge;
640 Double bottom = -ext.GetY() * 0.5 - edge;
641 Double top = ext.GetY() * 0.5 + edge;
642 int count_x = (int) ceil((right - left) / grid_size);
643 int count_y = (int) ceil((top - bottom) / grid_size);
644 Double actual_right = left + count_x*grid_size;
645 Double actual_top = bottom + count_y*grid_size;
647 BeginLines();
649 for (int xc = 0; xc <= count_x; xc++) {
650 Double x = left + xc*grid_size;
652 PlaceVertex(x, bottom, grid_z);
653 PlaceVertex(x, actual_top, grid_z);
656 for (int yc = 0; yc <= count_y; yc++) {
657 Double y = bottom + yc*grid_size;
658 PlaceVertex(left, y, grid_z);
659 PlaceVertex(actual_right, y, grid_z);
662 EndLines();
665 int GfxCore::GetClinoOffset() const
667 int result = INDICATOR_OFFSET_X;
668 if (m_Compass) {
669 result += 6 + GetCompassWidth() + INDICATOR_GAP;
671 return result;
674 void GfxCore::DrawTick(int angle_cw)
676 const Double theta = rad(angle_cw);
677 const wxCoord length1 = INDICATOR_RADIUS;
678 const wxCoord length0 = length1 + TICK_LENGTH;
679 wxCoord x0 = wxCoord(length0 * sin(theta));
680 wxCoord y0 = wxCoord(length0 * cos(theta));
681 wxCoord x1 = wxCoord(length1 * sin(theta));
682 wxCoord y1 = wxCoord(length1 * cos(theta));
684 PlaceIndicatorVertex(x0, y0);
685 PlaceIndicatorVertex(x1, y1);
688 void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
689 Vector3 p1(0, INDICATOR_RADIUS, 0);
690 Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
691 Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
692 Vector3 pc(0, 0, 0);
694 DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
695 DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
698 void GfxCore::DrawCompass() {
699 // Ticks.
700 BeginLines();
701 for (int angle = 315; angle > 0; angle -= 45) {
702 DrawTick(angle);
704 SetColour(col_GREEN);
705 DrawTick(0);
706 EndLines();
708 // Compass background.
709 DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
711 // Compass arrow.
712 DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
715 // Draw the non-rotating background to the clino.
716 void GfxCore::DrawClinoBack() {
717 BeginLines();
718 for (int angle = 0; angle <= 180; angle += 90) {
719 DrawTick(angle);
722 SetColour(col_GREY);
723 PlaceIndicatorVertex(0, INDICATOR_RADIUS);
724 PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
725 PlaceIndicatorVertex(0, 0);
726 PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
728 EndLines();
731 void GfxCore::DrawClino() {
732 // Ticks.
733 SetColour(col_GREEN);
734 BeginLines();
735 DrawTick(0);
736 EndLines();
738 // Clino background.
739 DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
741 // Elevation arrow.
742 DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
745 void GfxCore::Draw2dIndicators()
747 // Draw the compass and elevation indicators.
749 const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
751 const int comp_centre_x = GetCompassXPosition();
753 if (m_Compass && !m_Parent->IsExtendedElevation()) {
754 // If the user is dragging the compass with the pointer outside the
755 // compass, we snap to 45 degree multiples, and the ticks go white.
756 SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
757 DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
760 const int elev_centre_x = GetClinoXPosition();
762 if (m_Clino) {
763 // If the user is dragging the clino with the pointer outside the
764 // clino, we snap to 90 degree multiples, and the ticks go white.
765 SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
766 DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
767 DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
770 SetColour(TEXT_COLOUR);
772 static int triple_zero_width = 0;
773 static int height = 0;
774 if (!triple_zero_width) {
775 GetTextExtent(wxT("000"), &triple_zero_width, &height);
777 const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
779 if (m_Compass && !m_Parent->IsExtendedElevation()) {
780 wxString str;
781 int value;
782 int brg_unit;
783 if (m_Degrees) {
784 value = int(m_PanAngle);
785 /* TRANSLATORS: degree symbol - probably should be translated to
786 * itself. */
787 brg_unit = /*°*/344;
788 } else {
789 value = int(m_PanAngle * 200.0 / 180.0);
790 /* TRANSLATORS: symbol for grad (400 grad = 360 degrees = full
791 * circle). */
792 brg_unit = /*ᵍ*/345;
794 str.Printf(wxT("%03d"), value);
795 str += wmsg(brg_unit);
796 DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
798 // TRANSLATORS: Used in aven above the compass indicator at the lower
799 // right of the display, with a bearing below "Facing". This indicates the
800 // direction the viewer is "facing" in.
802 // Try to keep this translation short - ideally at most 10 characters -
803 // as otherwise the compass and clino will be moved further apart to
804 // make room. */
805 str = wmsg(/*Facing*/203);
806 int w;
807 GetTextExtent(str, &w, NULL);
808 DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
811 if (m_Clino) {
812 if (m_TiltAngle == -90.0) {
813 // TRANSLATORS: Label used for "clino" in Aven when the view is
814 // from directly above.
816 // Try to keep this translation short - ideally at most 10
817 // characters - as otherwise the compass and clino will be moved
818 // further apart to make room. */
819 wxString str = wmsg(/*Plan*/432);
820 static int width = 0;
821 if (!width) {
822 GetTextExtent(str, &width, NULL);
824 int x = elev_centre_x - width / 2;
825 DrawIndicatorText(x, y_off + height / 2, str);
826 } else if (m_TiltAngle == 90.0) {
827 // TRANSLATORS: Label used for "clino" in Aven when the view is
828 // from directly below.
830 // Try to keep this translation short - ideally at most 10
831 // characters - as otherwise the compass and clino will be moved
832 // further apart to make room. */
833 wxString str = wmsg(/*Kiwi Plan*/433);
834 static int width = 0;
835 if (!width) {
836 GetTextExtent(str, &width, NULL);
838 int x = elev_centre_x - width / 2;
839 DrawIndicatorText(x, y_off + height / 2, str);
840 } else {
841 int angle;
842 wxString str;
843 int width;
844 int unit;
845 if (m_Percent) {
846 static int zero_width = 0;
847 if (!zero_width) {
848 GetTextExtent(wxT("0"), &zero_width, NULL);
850 width = zero_width;
851 if (m_TiltAngle > 89.99) {
852 angle = 1000000;
853 } else if (m_TiltAngle < -89.99) {
854 angle = -1000000;
855 } else {
856 angle = int(100 * tan(rad(m_TiltAngle)));
858 if (angle > 99999 || angle < -99999) {
859 str = angle > 0 ? wxT("+") : wxT("-");
860 /* TRANSLATORS: infinity symbol - used for the percentage gradient on
861 * vertical angles. */
862 str += wmsg(/*∞*/431);
863 } else {
864 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("0");
866 /* TRANSLATORS: symbol for percentage gradient (100% = 45
867 * degrees = 50 grad). */
868 unit = /*%*/96;
869 } else if (m_Degrees) {
870 static int zero_zero_width = 0;
871 if (!zero_zero_width) {
872 GetTextExtent(wxT("00"), &zero_zero_width, NULL);
874 width = zero_zero_width;
875 angle = int(m_TiltAngle);
876 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
877 unit = /*°*/344;
878 } else {
879 width = triple_zero_width;
880 angle = int(m_TiltAngle * 200.0 / 180.0);
881 str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
882 unit = /*ᵍ*/345;
885 int sign_offset = 0;
886 if (unit == /*%*/96) {
887 // Right align % since the width changes so much.
888 GetTextExtent(str, &sign_offset, NULL);
889 sign_offset -= width;
890 } else if (angle < 0) {
891 // Adjust horizontal position so the left of the first digit is
892 // always in the same place.
893 static int minus_width = 0;
894 if (!minus_width) {
895 GetTextExtent(wxT("-"), &minus_width, NULL);
897 sign_offset = minus_width;
898 } else if (angle > 0) {
899 // Adjust horizontal position so the left of the first digit is
900 // always in the same place.
901 static int plus_width = 0;
902 if (!plus_width) {
903 GetTextExtent(wxT("+"), &plus_width, NULL);
905 sign_offset = plus_width;
908 str += wmsg(unit);
909 DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
911 // TRANSLATORS: Label used for "clino" in Aven when the view is
912 // neither from directly above nor from directly below. It is
913 // also used in the dialog for editing a marked position in a
914 // presentation.
916 // Try to keep this translation short - ideally at most 10
917 // characters - as otherwise the compass and clino will be moved
918 // further apart to make room. */
919 str = wmsg(/*Elevation*/118);
920 static int elevation_width = 0;
921 if (!elevation_width) {
922 GetTextExtent(str, &elevation_width, NULL);
924 int x = elev_centre_x - elevation_width / 2;
925 DrawIndicatorText(x, y_off + height, str);
930 void GfxCore::NattyDrawNames()
932 // Draw station names, without overlapping.
934 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
935 const unsigned int quantised_x = GetXSize() / quantise;
936 const unsigned int quantised_y = GetYSize() / quantise;
937 const size_t buffer_size = quantised_x * quantised_y;
939 if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
941 memset((void*) m_LabelGrid, 0, buffer_size);
943 const SurveyFilter* filter = m_Parent->GetTreeFilter();
944 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
945 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
946 if (!((m_Surface && (*label)->IsSurface()) ||
947 (m_Legs && (*label)->IsUnderground()) ||
948 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
949 // if this station isn't to be displayed, skip to the next
950 // (last case is for stns with no legs attached)
951 continue;
953 if (filter && !filter->CheckVisible((*label)->GetText()))
954 continue;
956 double x, y, z;
958 Transform(**label, &x, &y, &z);
959 // Check if the label is behind us (in perspective view).
960 if (z <= 0.0 || z >= 1.0) continue;
962 // Apply a small shift so that translating the view doesn't make which
963 // labels are displayed change as the resulting twinkling effect is
964 // distracting.
965 double tx, ty, tz;
966 Transform(Vector3(), &tx, &ty, &tz);
967 tx -= floor(tx / quantise) * quantise;
968 ty -= floor(ty / quantise) * quantise;
970 tx = x - tx;
971 if (tx < 0) continue;
973 ty = y - ty;
974 if (ty < 0) continue;
976 unsigned int iy = unsigned(ty) / quantise;
977 if (iy >= quantised_y) continue;
978 unsigned int width = (*label)->get_width();
979 unsigned int ix = unsigned(tx) / quantise;
980 if (ix + width >= quantised_x) continue;
982 char * test = m_LabelGrid + ix + iy * quantised_x;
983 if (memchr(test, 1, width)) continue;
985 x += 3;
986 y -= GetFontSize() / 2;
987 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
989 if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
990 test -= quantised_x * iy;
991 iy += 4;
992 while (--iy && test < m_LabelGrid + buffer_size) {
993 memset(test, 1, width);
994 test += quantised_x;
999 void GfxCore::SimpleDrawNames()
1001 const SurveyFilter* filter = m_Parent->GetTreeFilter();
1002 // Draw all station names, without worrying about overlaps
1003 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
1004 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
1005 if (!((m_Surface && (*label)->IsSurface()) ||
1006 (m_Legs && (*label)->IsUnderground()) ||
1007 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
1008 // if this station isn't to be displayed, skip to the next
1009 // (last case is for stns with no legs attached)
1010 continue;
1012 if (filter && !filter->CheckVisible((*label)->GetText()))
1013 continue;
1015 double x, y, z;
1016 Transform(**label, &x, &y, &z);
1018 // Check if the label is behind us (in perspective view).
1019 if (z <= 0) continue;
1021 x += 3;
1022 y -= GetFontSize() / 2;
1023 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
1027 void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
1029 int total_block_height =
1030 KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
1031 if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
1032 if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
1034 const int bottom = -total_block_height;
1036 int size = 0;
1037 if (!other.empty()) GetTextExtent(other, &size, NULL);
1038 int band;
1039 for (band = 0; band < num_bands; ++band) {
1040 int x;
1041 GetTextExtent(key_legends[band], &x, NULL);
1042 if (x > size) size = x;
1045 int left = -KEY_BLOCK_WIDTH - size;
1047 key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
1048 key_lowerleft[m_ColourBy].y = bottom;
1050 int y = bottom;
1051 if (!units.empty()) y += KEY_BLOCK_HEIGHT;
1053 if (!other.empty()) {
1054 DrawRectangle(NODATA_COLOUR, col_BLACK,
1055 left, y,
1056 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1057 y += KEY_BLOCK_HEIGHT * 2;
1060 int start = y;
1061 if (num_bands == 1) {
1062 DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
1063 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1064 y += KEY_BLOCK_HEIGHT;
1065 } else {
1066 for (band = 0; band < num_bands - 1; ++band) {
1067 DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
1068 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1069 y += KEY_BLOCK_HEIGHT;
1073 SetColour(col_BLACK);
1074 BeginPolyline();
1075 PlaceIndicatorVertex(left, y);
1076 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1077 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
1078 PlaceIndicatorVertex(left, start);
1079 PlaceIndicatorVertex(left, y);
1080 EndPolyline();
1082 SetColour(TEXT_COLOUR);
1084 y = bottom;
1085 if (!units.empty()) {
1086 GetTextExtent(units, &size, NULL);
1087 DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
1088 y += KEY_BLOCK_HEIGHT;
1090 y -= GetFontSize() / 2;
1091 left += KEY_BLOCK_WIDTH + 5;
1093 if (!other.empty()) {
1094 y += KEY_BLOCK_HEIGHT / 2;
1095 DrawIndicatorText(left, y, other);
1096 y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
1099 if (num_bands == 1) {
1100 y += KEY_BLOCK_HEIGHT / 2;
1101 DrawIndicatorText(left, y, key_legends[0]);
1102 } else {
1103 for (band = 0; band < num_bands; ++band) {
1104 DrawIndicatorText(left, y, key_legends[band]);
1105 y += KEY_BLOCK_HEIGHT;
1110 void GfxCore::DrawDepthKey()
1112 Double z_ext = m_Parent->GetDepthExtent();
1113 int num_bands = 1;
1114 int sf = 0;
1115 if (z_ext > 0.0) {
1116 num_bands = GetNumColourBands();
1117 Double z_range = z_ext;
1118 if (!m_Metric) z_range /= METRES_PER_FOOT;
1119 sf = max(0, 1 - (int)floor(log10(z_range)));
1122 Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
1123 for (int band = 0; band < num_bands; ++band) {
1124 Double z = z_min;
1125 if (band)
1126 z += z_ext * band / (num_bands - 1);
1128 if (!m_Metric)
1129 z /= METRES_PER_FOOT;
1131 key_legends[band].Printf(wxT("%.*f"), sf, z);
1134 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1137 void GfxCore::DrawDateKey()
1139 int num_bands;
1140 if (!HasDateInformation()) {
1141 num_bands = 0;
1142 } else {
1143 int date_ext = m_Parent->GetDateExtent();
1144 if (date_ext == 0) {
1145 num_bands = 1;
1146 } else {
1147 num_bands = GetNumColourBands();
1149 for (int band = 0; band < num_bands; ++band) {
1150 int y, m, d;
1151 int days = m_Parent->GetDateMin();
1152 if (band)
1153 days += date_ext * band / (num_bands - 1);
1154 ymd_from_days_since_1900(days, &y, &m, &d);
1155 key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
1159 wxString other;
1160 if (!m_Parent->HasCompleteDateInfo()) {
1161 /* TRANSLATORS: Used in the "colour key" for "colour by date" if there
1162 * are surveys without date information. Try to keep this fairly short.
1164 other = wmsg(/*Undated*/221);
1167 DrawColourKey(num_bands, other, wxString());
1170 void GfxCore::DrawErrorKey()
1172 int num_bands;
1173 if (HasErrorInformation()) {
1174 // Use fixed colours for each error factor so it's directly visually
1175 // comparable between surveys.
1176 num_bands = GetNumColourBands();
1177 for (int band = 0; band < num_bands; ++band) {
1178 double E = MAX_ERROR * band / (num_bands - 1);
1179 key_legends[band].Printf(wxT("%.2f"), E);
1181 } else {
1182 num_bands = 0;
1185 // Always show the "Not in loop" legend for now (FIXME).
1186 /* TRANSLATORS: Used in the "colour key" for "colour by error" for surveys
1187 * which aren’t part of a loop and so have no error information. Try to keep
1188 * this fairly short. */
1189 DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
1192 void GfxCore::DrawGradientKey()
1194 int num_bands;
1195 // Use fixed colours for each gradient so it's directly visually comparable
1196 // between surveys.
1197 num_bands = GetNumColourBands();
1198 wxString units = wmsg(m_Degrees ? /*°*/344 : /*ᵍ*/345);
1199 for (int band = 0; band < num_bands; ++band) {
1200 double gradient = double(band) / (num_bands - 1);
1201 if (m_Degrees) {
1202 gradient *= 90.0;
1203 } else {
1204 gradient *= 100.0;
1206 key_legends[band].Printf(wxT("%.f%s"), gradient, units);
1209 DrawColourKey(num_bands, wxString(), wxString());
1212 void GfxCore::DrawLengthKey()
1214 int num_bands;
1215 // Use fixed colours for each length so it's directly visually comparable
1216 // between surveys.
1217 num_bands = GetNumColourBands();
1218 for (int band = 0; band < num_bands; ++band) {
1219 double len = pow(10, LOG_LEN_MAX * band / (num_bands - 1));
1220 if (!m_Metric) {
1221 len /= METRES_PER_FOOT;
1223 key_legends[band].Printf(wxT("%.1f"), len);
1226 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1229 void GfxCore::DrawScaleBar()
1231 // Calculate how many metres of survey are currently displayed across the
1232 // screen.
1233 Double across_screen = SurveyUnitsAcrossViewport();
1235 double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
1236 if (f > 0.75) {
1237 f = 0.75;
1238 } else if (f < 0.5) {
1239 // Stop it getting squeezed to nothing.
1240 // FIXME: In this case we should probably move the compass and clino up
1241 // to make room rather than letting stuff overlap.
1242 f = 0.5;
1245 // Convert to imperial measurements if required.
1246 Double multiplier = 1.0;
1247 if (!m_Metric) {
1248 across_screen /= METRES_PER_FOOT;
1249 multiplier = METRES_PER_FOOT;
1250 if (across_screen >= 5280.0 / f) {
1251 across_screen /= 5280.0;
1252 multiplier *= 5280.0;
1256 // Calculate the length of the scale bar.
1257 Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1258 Double t = across_screen * f / size_snap;
1259 if (t >= 5.0) {
1260 size_snap *= 5.0;
1261 } else if (t >= 2.0) {
1262 size_snap *= 2.0;
1265 if (!m_Metric) size_snap *= multiplier;
1267 // Actual size of the thing in pixels:
1268 int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1269 m_ScaleBarWidth = size;
1271 // Draw it...
1272 const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1273 int interval = size / 10;
1275 gla_colour col = col_WHITE;
1276 for (int ix = 0; ix < 10; ix++) {
1277 int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1279 DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1281 col = (col == col_WHITE) ? col_GREY : col_WHITE;
1284 // Add labels.
1285 wxString str;
1286 int units;
1287 if (m_Metric) {
1288 Double km = size_snap * 1e-3;
1289 if (km >= 1.0) {
1290 size_snap = km;
1291 /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1292 * used e.g. "5km".
1294 * If there should be a space between the number and this, include
1295 * one in the translation. */
1296 units = /*km*/423;
1297 } else if (size_snap >= 1.0) {
1298 /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1299 * e.g. "10m".
1301 * If there should be a space between the number and this, include
1302 * one in the translation. */
1303 units = /*m*/424;
1304 } else {
1305 size_snap *= 1e2;
1306 /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1307 * used e.g. "50cm".
1309 * If there should be a space between the number and this, include
1310 * one in the translation. */
1311 units = /*cm*/425;
1313 } else {
1314 size_snap /= METRES_PER_FOOT;
1315 Double miles = size_snap / 5280.0;
1316 if (miles >= 1.0) {
1317 size_snap = miles;
1318 if (size_snap >= 2.0) {
1319 /* TRANSLATORS: abbreviation for "miles" (unit of length,
1320 * plural), used e.g. "2 miles".
1322 * If there should be a space between the number and this,
1323 * include one in the translation. */
1324 units = /* miles*/426;
1325 } else {
1326 /* TRANSLATORS: abbreviation for "mile" (unit of length,
1327 * singular), used e.g. "1 mile".
1329 * If there should be a space between the number and this,
1330 * include one in the translation. */
1331 units = /* mile*/427;
1333 } else if (size_snap >= 1.0) {
1334 /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1335 * as "10ft".
1337 * If there should be a space between the number and this, include
1338 * one in the translation. */
1339 units = /*ft*/428;
1340 } else {
1341 size_snap *= 12.0;
1342 /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1343 * e.g. as "6in".
1345 * If there should be a space between the number and this, include
1346 * one in the translation. */
1347 units = /*in*/429;
1350 if (size_snap >= 1.0) {
1351 str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1352 } else {
1353 int sf = -(int)floor(log10(size_snap));
1354 str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1357 int text_width, text_height;
1358 GetTextExtent(str, &text_width, &text_height);
1359 const int text_y = end_y - text_height + 1;
1360 SetColour(TEXT_COLOUR);
1361 DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1362 DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1365 bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1367 if (Animating()) return false;
1369 if (point.x < 0 || point.x >= GetXSize() ||
1370 point.y < 0 || point.y >= GetYSize()) {
1371 return false;
1374 SetDataTransform();
1376 if (!m_HitTestGridValid) CreateHitTestGrid();
1378 int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1379 int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
1381 LabelInfo *best = NULL;
1382 int dist_sqrd = sqrd_measure_threshold;
1383 int square = grid_x + grid_y * HITTEST_SIZE;
1384 list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1386 while (iter != m_PointGrid[square].end()) {
1387 LabelInfo *pt = *iter++;
1389 double cx, cy, cz;
1391 Transform(*pt, &cx, &cy, &cz);
1393 cy = GetYSize() - cy;
1395 int dx = point.x - int(cx);
1396 int ds = dx * dx;
1397 if (ds >= dist_sqrd) continue;
1398 int dy = point.y - int(cy);
1400 ds += dy * dy;
1401 if (ds >= dist_sqrd) continue;
1403 dist_sqrd = ds;
1404 best = pt;
1406 if (ds == 0) break;
1409 if (best) {
1410 m_Parent->ShowInfo(best, m_there);
1411 if (centre) {
1412 // FIXME: allow Ctrl-Click to not set there or something?
1413 CentreOn(*best);
1414 WarpPointer(GetXSize() / 2, GetYSize() / 2);
1415 SetThere(best);
1416 m_Parent->SelectTreeItem(best);
1418 } else {
1419 // Left-clicking not on a survey cancels the measuring line.
1420 if (centre) {
1421 ClearTreeSelection();
1422 } else {
1423 m_Parent->ShowInfo(best, m_there);
1424 double x, y, z;
1425 ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1426 temp_here.assign(Vector3(x, y, z));
1427 SetHere(&temp_here);
1431 return best;
1434 void GfxCore::OnSize(wxSizeEvent& event)
1436 // Handle a change in window size.
1437 wxSize size = event.GetSize();
1439 if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1440 // Before things are fully initialised, we sometimes get a bogus
1441 // resize message...
1442 // FIXME have changes in MainFrm cured this? It still happens with
1443 // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1444 // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1445 // is resized such that the GfxCore window isn't visible.
1446 //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1447 return;
1450 event.Skip();
1452 if (m_DoneFirstShow) {
1453 TryToFreeArrays();
1455 m_HitTestGridValid = false;
1457 ForceRefresh();
1461 void GfxCore::DefaultParameters()
1463 // Set default viewing parameters.
1465 m_Surface = false;
1466 if (!m_Parent->HasUndergroundLegs()) {
1467 if (m_Parent->HasSurfaceLegs()) {
1468 // If there are surface legs, but no underground legs, turn
1469 // surface surveys on.
1470 m_Surface = true;
1471 } else {
1472 // If there are no legs (e.g. after loading a .pos file), turn
1473 // crosses on.
1474 m_Crosses = true;
1478 m_PanAngle = 0.0;
1479 if (m_Parent->IsExtendedElevation()) {
1480 m_TiltAngle = 0.0;
1481 } else {
1482 m_TiltAngle = -90.0;
1485 SetRotation(m_PanAngle, m_TiltAngle);
1486 SetTranslation(Vector3());
1488 m_RotationStep = 30.0;
1489 m_Rotating = false;
1490 m_SwitchingTo = 0;
1491 m_Entrances = false;
1492 m_FixedPts = false;
1493 m_ExportedPts = false;
1494 m_Grid = false;
1495 m_BoundingBox = false;
1496 m_Tubes = false;
1497 if (GetPerspective()) TogglePerspective();
1499 // Set the initial scale.
1500 SetScale(initial_scale);
1503 void GfxCore::Defaults()
1505 // Restore default scale, rotation and translation parameters.
1506 DefaultParameters();
1508 // Invalidate all the cached lists.
1509 GLACanvas::FirstShow();
1511 ForceRefresh();
1514 void GfxCore::Animate()
1516 // Don't show pointer coordinates while animating.
1517 // FIXME : only do this when we *START* animating! Use a static copy
1518 // of the value of "Animating()" last time we were here to track this?
1519 // MainFrm now checks if we're trying to clear already cleared labels
1520 // and just returns, but it might be simpler to check here!
1521 ClearCoords();
1522 m_Parent->ShowInfo();
1524 long t;
1525 if (movie) {
1526 ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1527 if (!movie->AddFrame()) {
1528 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1529 delete movie;
1530 movie = NULL;
1531 presentation_mode = 0;
1532 return;
1534 t = 1000 / 25; // 25 frames per second
1535 } else {
1536 static long t_prev = 0;
1537 t = timer.Time();
1538 // Avoid redrawing twice in the same frame.
1539 long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1540 if (delta_t < 1000 / MAX_FRAMERATE)
1541 return;
1542 t_prev = t;
1543 if (presentation_mode == PLAYING && pres_speed != 0.0)
1544 t = delta_t;
1547 if (presentation_mode == PLAYING && pres_speed != 0.0) {
1548 // FIXME: It would probably be better to work relative to the time we
1549 // passed the last mark, but that's complicated by the speed
1550 // potentially changing (or even the direction of playback reversing)
1551 // at any point during playback.
1552 Double tick = t * 0.001 * fabs(pres_speed);
1553 while (tick >= next_mark_time) {
1554 tick -= next_mark_time;
1555 this_mark_total = 0;
1556 PresentationMark prev_mark = next_mark;
1557 if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1558 else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1559 if (pres_reverse)
1560 next_mark = m_Parent->GetPresMark(MARK_PREV);
1561 else
1562 next_mark = m_Parent->GetPresMark(MARK_NEXT);
1563 if (!next_mark.is_valid()) {
1564 SetView(prev_mark);
1565 presentation_mode = 0;
1566 if (movie && !movie->Close()) {
1567 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1569 delete movie;
1570 movie = NULL;
1571 break;
1574 double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1575 if (tmp > 0) {
1576 next_mark_time = tmp;
1577 } else {
1578 double d = (next_mark - prev_mark).magnitude();
1579 // FIXME: should ignore component of d which is unseen in
1580 // non-perspective mode?
1581 next_mark_time = sqrd(d / 30.0);
1582 double a = next_mark.angle - prev_mark.angle;
1583 if (a > 180.0) {
1584 next_mark.angle -= 360.0;
1585 a = 360.0 - a;
1586 } else if (a < -180.0) {
1587 next_mark.angle += 360.0;
1588 a += 360.0;
1589 } else {
1590 a = fabs(a);
1592 next_mark_time += sqrd(a / 60.0);
1593 double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1594 next_mark_time += sqrd(ta / 60.0);
1595 double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1596 next_mark_time += sqrd(s / 2.0);
1597 next_mark_time = sqrt(next_mark_time);
1598 // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1599 //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1600 // next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1601 if (tmp < 0) next_mark_time /= -tmp;
1605 if (presentation_mode) {
1606 // Advance position towards next_mark
1607 double p = tick / next_mark_time;
1608 double q = 1 - p;
1609 PresentationMark here = GetView();
1610 if (next_mark.angle < 0) {
1611 if (here.angle >= next_mark.angle + 360.0)
1612 here.angle -= 360.0;
1613 } else if (next_mark.angle >= 360.0) {
1614 if (here.angle <= next_mark.angle - 360.0)
1615 here.angle += 360.0;
1617 here.assign(q * here + p * next_mark);
1618 here.angle = q * here.angle + p * next_mark.angle;
1619 if (here.angle < 0) here.angle += 360.0;
1620 else if (here.angle >= 360.0) here.angle -= 360.0;
1621 here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1622 here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1623 SetView(here);
1624 this_mark_total += tick;
1625 next_mark_time -= tick;
1628 ForceRefresh();
1629 return;
1632 // When rotating...
1633 if (m_Rotating) {
1634 Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1635 TurnCave(step);
1638 if (m_SwitchingTo == PLAN) {
1639 // When switching to plan view...
1640 Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1641 TiltCave(step);
1642 if (m_TiltAngle == -90.0) {
1643 m_SwitchingTo = 0;
1645 } else if (m_SwitchingTo == ELEVATION) {
1646 // When switching to elevation view...
1647 Double step;
1648 if (m_TiltAngle > 0.0) {
1649 step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1650 } else {
1651 step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1653 if (fabs(step) >= fabs(m_TiltAngle)) {
1654 m_SwitchingTo = 0;
1655 step = -m_TiltAngle;
1657 TiltCave(step);
1658 } else if (m_SwitchingTo) {
1659 // Rotate the shortest way around to the destination angle. If we're
1660 // 180 off, we favour turning anticlockwise, as auto-rotation does by
1661 // default.
1662 Double target = (m_SwitchingTo - NORTH) * 90;
1663 Double diff = target - m_PanAngle;
1664 diff = fmod(diff, 360);
1665 if (diff <= -180)
1666 diff += 360;
1667 else if (diff > 180)
1668 diff -= 360;
1669 if (m_RotationStep < 0 && diff == 180.0)
1670 diff = -180.0;
1671 Double step = base_pan - m_PanAngle;
1672 Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1673 if (diff > 0) {
1674 step += delta;
1675 } else {
1676 step -= delta;
1678 step = fmod(step, 360);
1679 if (step <= -180)
1680 step += 360;
1681 else if (step > 180)
1682 step -= 360;
1683 if (fabs(step) >= fabs(diff)) {
1684 m_SwitchingTo = 0;
1685 step = diff;
1687 TurnCave(step);
1690 ForceRefresh();
1693 // How much to allow around the box - this is because of the ring shape
1694 // at one end of the line.
1695 static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1696 #define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1697 void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
1699 #ifdef __WXMSW__
1700 (void)a;
1701 (void)b;
1702 (void)c;
1703 // FIXME: We get odd redraw artifacts if we just update the line, and
1704 // redrawing the whole scene doesn't actually seem to be measurably
1705 // slower. That may not be true with software rendering though...
1706 ForceRefresh();
1707 #else
1708 // Best of all might be to copy the window contents before we draw the
1709 // line, then replace each time we redraw.
1711 // Calculate the minimum rectangle which includes the old and new
1712 // measuring lines to minimise the redraw time
1713 int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1714 double X, Y, Z;
1715 if (a) {
1716 if (!Transform(*a, &X, &Y, &Z)) {
1717 printf("oops\n");
1718 } else {
1719 int x = int(X);
1720 int y = GetYSize() - 1 - int(Y);
1721 l = x;
1722 r = x;
1723 u = y;
1724 d = y;
1727 if (b) {
1728 if (!Transform(*b, &X, &Y, &Z)) {
1729 printf("oops\n");
1730 } else {
1731 int x = int(X);
1732 int y = GetYSize() - 1 - int(Y);
1733 l = min(l, x);
1734 r = max(r, x);
1735 u = max(u, y);
1736 d = min(d, y);
1739 if (c) {
1740 if (!Transform(*c, &X, &Y, &Z)) {
1741 printf("oops\n");
1742 } else {
1743 int x = int(X);
1744 int y = GetYSize() - 1 - int(Y);
1745 l = min(l, x);
1746 r = max(r, x);
1747 u = max(u, y);
1748 d = min(d, y);
1751 l -= MARGIN;
1752 r += MARGIN;
1753 u += MARGIN;
1754 d -= MARGIN;
1755 RefreshRect(wxRect(l, d, r - l, u - d), false);
1756 #endif
1759 void GfxCore::HighlightSurvey()
1761 SurveyFilter filter;
1762 filter.add(highlighted_survey);
1763 filter.SetSeparator(m_Parent->GetSeparator());
1765 double x_min = HUGE_VAL, x_max = -HUGE_VAL;
1766 double y_min = HUGE_VAL, y_max = -HUGE_VAL;
1767 double xpy_min = HUGE_VAL, xpy_max = -HUGE_VAL;
1768 double xmy_min = HUGE_VAL, xmy_max = -HUGE_VAL;
1769 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1770 double x_tot = 0, y_tot = 0;
1771 size_t c = 0;
1772 while (pos != m_Parent->GetLabelsEnd()) {
1773 const LabelInfo* label = *pos++;
1774 if (!filter.CheckVisible(label->GetText()))
1775 continue;
1777 double x, y, z;
1778 Transform(*label, &x, &y, &z);
1779 if (x < x_min) x_min = x;
1780 if (x > x_max) x_max = x;
1781 if (y < y_min) y_min = y;
1782 if (y > y_max) y_max = y;
1783 double xpy = x + y;
1784 if (xpy < xpy_min) xpy_min = xpy;
1785 if (xpy > xpy_max) xpy_max = xpy;
1786 double xmy = x - y;
1787 if (xmy < xmy_min) xmy_min = xmy;
1788 if (xmy > xmy_max) xmy_max = xmy;
1789 x_tot += x;
1790 y_tot += y;
1791 ++c;
1793 for (int f = 0; f != 8; ++f) {
1794 list<traverse>::const_iterator trav = m_Parent->traverses_begin(f, &filter);
1795 list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
1796 while (trav != tend) {
1797 for (auto&& p : *trav) {
1798 double x, y, z;
1799 Transform(p, &x, &y, &z);
1800 if (x < x_min) x_min = x;
1801 if (x > x_max) x_max = x;
1802 if (y < y_min) y_min = y;
1803 if (y > y_max) y_max = y;
1804 double xpy = x + y;
1805 if (xpy < xpy_min) xpy_min = xpy;
1806 if (xpy > xpy_max) xpy_max = xpy;
1807 double xmy = x - y;
1808 if (xmy < xmy_min) xmy_min = xmy;
1809 if (xmy > xmy_max) xmy_max = xmy;
1810 x_tot += x;
1811 y_tot += y;
1812 ++c;
1814 trav = m_Parent->traverses_next(f, &filter, trav);
1818 if (c == 0) return;
1820 // Minimum margin around survey.
1821 const double M = 4.0;
1822 // X/Y component when M measured diagonally.
1823 const double D = M * sqrt(2.0) / 2.0;
1825 SetColour(col_WHITE);
1826 BeginPolyloop();
1827 PlaceIndicatorVertex(xmy_max + y_min, y_min - M);
1828 PlaceIndicatorVertex(xmy_max + y_min + D, y_min - D);
1829 PlaceIndicatorVertex(x_max + D, x_max - xmy_max - D);
1830 PlaceIndicatorVertex(x_max + M, x_max - xmy_max);
1831 PlaceIndicatorVertex(x_max + M, xpy_max - x_max);
1832 PlaceIndicatorVertex(x_max + D, xpy_max - x_max + D);
1833 PlaceIndicatorVertex(xpy_max - y_max + D, y_max + D);
1834 PlaceIndicatorVertex(xpy_max - y_max, y_max + M);
1835 PlaceIndicatorVertex(xmy_min + y_max, y_max + M);
1836 PlaceIndicatorVertex(xmy_min + y_max - D, y_max + D);
1837 PlaceIndicatorVertex(x_min - D, x_min - xmy_min + D);
1838 PlaceIndicatorVertex(x_min - M, x_min - xmy_min);
1839 PlaceIndicatorVertex(x_min - M, xpy_min - x_min);
1840 PlaceIndicatorVertex(x_min - D, xpy_min - x_min - D);
1841 PlaceIndicatorVertex(xpy_min - y_min - D, y_min - D);
1842 PlaceIndicatorVertex(xpy_min - y_min, y_min - M);
1843 EndPolyloop();
1846 void GfxCore::ZoomToSurvey(const wxString& survey) {
1847 SurveyFilter filter;
1848 filter.add(survey);
1849 filter.SetSeparator(m_Parent->GetSeparator());
1851 Double xmin = DBL_MAX;
1852 Double xmax = -DBL_MAX;
1853 Double ymin = DBL_MAX;
1854 Double ymax = -DBL_MAX;
1855 Double zmin = DBL_MAX;
1856 Double zmax = -DBL_MAX;
1858 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1859 while (pos != m_Parent->GetLabelsEnd()) {
1860 LabelInfo* label = *pos++;
1862 if (!filter.CheckVisible(label->GetText()))
1863 continue;
1865 if (label->GetX() < xmin) xmin = label->GetX();
1866 if (label->GetX() > xmax) xmax = label->GetX();
1867 if (label->GetY() < ymin) ymin = label->GetY();
1868 if (label->GetY() > ymax) ymax = label->GetY();
1869 if (label->GetZ() < zmin) zmin = label->GetZ();
1870 if (label->GetZ() > zmax) zmax = label->GetZ();
1873 SetViewTo(xmin, xmax, ymin, ymax, zmin, zmax);
1876 void GfxCore::SetHereFromTree(const LabelInfo * p)
1878 SetHere(p);
1879 m_Parent->ShowInfo(m_here, m_there);
1880 SetHereSurvey(wxString());
1883 void GfxCore::SetHere(const LabelInfo *p)
1885 if (p == m_here) return;
1886 bool line_active = MeasuringLineActive();
1887 const LabelInfo * old = m_here;
1888 m_here = p;
1889 if (line_active || MeasuringLineActive())
1890 RefreshLine(old, m_there, m_here);
1893 void GfxCore::SetThere(const LabelInfo * p)
1895 if (p == m_there) return;
1896 const LabelInfo * old = m_there;
1897 m_there = p;
1898 RefreshLine(m_here, old, m_there);
1901 void GfxCore::CreateHitTestGrid()
1903 if (!m_PointGrid) {
1904 // Initialise hit-test grid.
1905 m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1906 } else {
1907 // Clear hit-test grid.
1908 for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1909 m_PointGrid[i].clear();
1913 const SurveyFilter* filter = m_Parent->GetTreeFilter();
1914 // Fill the grid.
1915 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1916 list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1917 while (pos != end) {
1918 LabelInfo* label = *pos++;
1920 if (!((m_Surface && label->IsSurface()) ||
1921 (m_Legs && label->IsUnderground()) ||
1922 (!label->IsSurface() && !label->IsUnderground()))) {
1923 // if this station isn't to be displayed, skip to the next
1924 // (last case is for stns with no legs attached)
1925 continue;
1927 if (filter && !filter->CheckVisible(label->GetText()))
1928 continue;
1930 // Calculate screen coordinates.
1931 double cx, cy, cz;
1932 Transform(*label, &cx, &cy, &cz);
1933 if (cx < 0 || cx >= GetXSize()) continue;
1934 if (cy < 0 || cy >= GetYSize()) continue;
1936 cy = GetYSize() - cy;
1938 // On-screen, so add to hit-test grid...
1939 int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1940 int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
1942 m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1945 m_HitTestGridValid = true;
1949 // Methods for controlling the orientation of the survey
1952 void GfxCore::TurnCave(Double angle)
1954 // Turn the cave around its z-axis by a given angle.
1956 m_PanAngle += angle;
1957 // Wrap to range [0, 360):
1958 m_PanAngle = fmod(m_PanAngle, 360.0);
1959 if (m_PanAngle < 0.0) {
1960 m_PanAngle += 360.0;
1963 m_HitTestGridValid = false;
1964 if (m_here && m_here == &temp_here) SetHere();
1966 SetRotation(m_PanAngle, m_TiltAngle);
1969 void GfxCore::TurnCaveTo(Double angle)
1971 if (m_Rotating) {
1972 // If we're rotating, jump to the specified angle.
1973 TurnCave(angle - m_PanAngle);
1974 SetPanBase();
1975 return;
1978 int new_switching_to = ((int)angle) / 90 + NORTH;
1979 if (new_switching_to == m_SwitchingTo) {
1980 // A second order to switch takes us there right away
1981 TurnCave(angle - m_PanAngle);
1982 m_SwitchingTo = 0;
1983 ForceRefresh();
1984 } else {
1985 SetPanBase();
1986 m_SwitchingTo = new_switching_to;
1990 void GfxCore::TiltCave(Double tilt_angle)
1992 // Tilt the cave by a given angle.
1993 if (m_TiltAngle + tilt_angle > 90.0) {
1994 m_TiltAngle = 90.0;
1995 } else if (m_TiltAngle + tilt_angle < -90.0) {
1996 m_TiltAngle = -90.0;
1997 } else {
1998 m_TiltAngle += tilt_angle;
2001 m_HitTestGridValid = false;
2002 if (m_here && m_here == &temp_here) SetHere();
2004 SetRotation(m_PanAngle, m_TiltAngle);
2007 void GfxCore::TranslateCave(int dx, int dy)
2009 AddTranslationScreenCoordinates(dx, dy);
2010 m_HitTestGridValid = false;
2012 if (m_here && m_here == &temp_here) SetHere();
2014 ForceRefresh();
2017 void GfxCore::DragFinished()
2019 m_MouseOutsideCompass = m_MouseOutsideElev = false;
2020 ForceRefresh();
2023 void GfxCore::ClearCoords()
2025 m_Parent->ClearCoords();
2028 void GfxCore::SetCoords(wxPoint point)
2030 // We can't work out 2D coordinates from a perspective view, and it
2031 // doesn't really make sense to show coordinates while we're animating.
2032 if (GetPerspective() || Animating()) return;
2034 // Update the coordinate or altitude display, given the (x, y) position in
2035 // window coordinates. The relevant display is updated depending on
2036 // whether we're in plan or elevation view.
2038 double cx, cy, cz;
2040 SetDataTransform();
2041 ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
2043 if (ShowingPlan()) {
2044 m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
2045 cy + m_Parent->GetOffset().GetY(),
2046 m_there);
2047 } else if (ShowingElevation()) {
2048 m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
2049 m_there);
2050 } else {
2051 m_Parent->ClearCoords();
2055 int GfxCore::GetCompassWidth() const
2057 static int result = 0;
2058 if (result == 0) {
2059 result = INDICATOR_BOX_SIZE;
2060 int width;
2061 const wxString & msg = wmsg(/*Facing*/203);
2062 GetTextExtent(msg, &width, NULL);
2063 if (width > result) result = width;
2065 return result;
2068 int GfxCore::GetClinoWidth() const
2070 static int result = 0;
2071 if (result == 0) {
2072 result = INDICATOR_BOX_SIZE;
2073 int width;
2074 const wxString & msg1 = wmsg(/*Plan*/432);
2075 GetTextExtent(msg1, &width, NULL);
2076 if (width > result) result = width;
2077 const wxString & msg2 = wmsg(/*Kiwi Plan*/433);
2078 GetTextExtent(msg2, &width, NULL);
2079 if (width > result) result = width;
2080 const wxString & msg3 = wmsg(/*Elevation*/118);
2081 GetTextExtent(msg3, &width, NULL);
2082 if (width > result) result = width;
2084 return result;
2087 int GfxCore::GetCompassXPosition() const
2089 // Return the x-coordinate of the centre of the compass in window
2090 // coordinates.
2091 return GetXSize() - INDICATOR_OFFSET_X - GetCompassWidth() / 2;
2094 int GfxCore::GetClinoXPosition() const
2096 // Return the x-coordinate of the centre of the compass in window
2097 // coordinates.
2098 return GetXSize() - GetClinoOffset() - GetClinoWidth() / 2;
2101 int GfxCore::GetIndicatorYPosition() const
2103 // Return the y-coordinate of the centre of the indicators in window
2104 // coordinates.
2105 return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
2108 int GfxCore::GetIndicatorRadius() const
2110 // Return the radius of each indicator.
2111 return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
2114 bool GfxCore::PointWithinCompass(wxPoint point) const
2116 // Determine whether a point (in window coordinates) lies within the
2117 // compass.
2118 if (!ShowingCompass()) return false;
2120 glaCoord dx = point.x - GetCompassXPosition();
2121 glaCoord dy = point.y - GetIndicatorYPosition();
2122 glaCoord radius = GetIndicatorRadius();
2124 return (dx * dx + dy * dy <= radius * radius);
2127 bool GfxCore::PointWithinClino(wxPoint point) const
2129 // Determine whether a point (in window coordinates) lies within the clino.
2130 if (!ShowingClino()) return false;
2132 glaCoord dx = point.x - GetClinoXPosition();
2133 glaCoord dy = point.y - GetIndicatorYPosition();
2134 glaCoord radius = GetIndicatorRadius();
2136 return (dx * dx + dy * dy <= radius * radius);
2139 bool GfxCore::PointWithinScaleBar(wxPoint point) const
2141 // Determine whether a point (in window coordinates) lies within the scale
2142 // bar.
2143 if (!ShowingScaleBar()) return false;
2145 return (point.x >= SCALE_BAR_OFFSET_X &&
2146 point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
2147 point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
2148 point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
2151 bool GfxCore::PointWithinColourKey(wxPoint point) const
2153 // Determine whether a point (in window coordinates) lies within the key.
2154 point.x -= GetXSize() - KEY_OFFSET_X;
2155 point.y = KEY_OFFSET_Y - point.y;
2156 return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
2157 point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
2160 void GfxCore::SetCompassFromPoint(wxPoint point)
2162 // Given a point in window coordinates, set the heading of the survey. If
2163 // the point is outside the compass, it snaps to 45 degree intervals;
2164 // otherwise it operates as normal.
2166 wxCoord dx = point.x - GetCompassXPosition();
2167 wxCoord dy = point.y - GetIndicatorYPosition();
2168 wxCoord radius = GetIndicatorRadius();
2170 double angle = deg(atan2(double(dx), double(dy))) - 180.0;
2171 if (dx * dx + dy * dy <= radius * radius) {
2172 TurnCave(angle - m_PanAngle);
2173 m_MouseOutsideCompass = false;
2174 } else {
2175 TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
2176 m_MouseOutsideCompass = true;
2179 ForceRefresh();
2182 void GfxCore::SetClinoFromPoint(wxPoint point)
2184 // Given a point in window coordinates, set the elevation of the survey.
2185 // If the point is outside the clino, it snaps to 90 degree intervals;
2186 // otherwise it operates as normal.
2188 glaCoord dx = point.x - GetClinoXPosition();
2189 glaCoord dy = point.y - GetIndicatorYPosition();
2190 glaCoord radius = GetIndicatorRadius();
2192 if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
2193 TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
2194 m_MouseOutsideElev = false;
2195 } else if (dy >= INDICATOR_MARGIN) {
2196 TiltCave(-90.0 - m_TiltAngle);
2197 m_MouseOutsideElev = true;
2198 } else if (dy <= -INDICATOR_MARGIN) {
2199 TiltCave(90.0 - m_TiltAngle);
2200 m_MouseOutsideElev = true;
2201 } else {
2202 TiltCave(-m_TiltAngle);
2203 m_MouseOutsideElev = true;
2206 ForceRefresh();
2209 void GfxCore::SetScaleBarFromOffset(wxCoord dx)
2211 // Set the scale of the survey, given an offset as to how much the mouse has
2212 // been dragged over the scalebar since the last scale change.
2214 SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
2215 ForceRefresh();
2218 void GfxCore::RedrawIndicators()
2220 // Redraw the compass and clino indicators.
2222 int total_width = GetCompassWidth() + INDICATOR_GAP + GetClinoWidth();
2223 RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - total_width,
2224 GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
2225 total_width,
2226 INDICATOR_BOX_SIZE), false);
2229 void GfxCore::StartRotation()
2231 // Start the survey rotating.
2233 if (m_SwitchingTo >= NORTH)
2234 m_SwitchingTo = 0;
2235 m_Rotating = true;
2236 SetPanBase();
2239 void GfxCore::ToggleRotation()
2241 // Toggle the survey rotation on/off.
2243 if (m_Rotating) {
2244 StopRotation();
2245 } else {
2246 StartRotation();
2250 void GfxCore::StopRotation()
2252 // Stop the survey rotating.
2254 m_Rotating = false;
2255 ForceRefresh();
2258 bool GfxCore::IsExtendedElevation() const
2260 return m_Parent->IsExtendedElevation();
2263 void GfxCore::ReverseRotation()
2265 // Reverse the direction of rotation.
2267 m_RotationStep = -m_RotationStep;
2268 if (m_Rotating)
2269 SetPanBase();
2272 void GfxCore::RotateSlower(bool accel)
2274 // Decrease the speed of rotation, optionally by an increased amount.
2275 if (fabs(m_RotationStep) == 1.0)
2276 return;
2278 m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2280 if (fabs(m_RotationStep) < 1.0) {
2281 m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
2283 if (m_Rotating)
2284 SetPanBase();
2287 void GfxCore::RotateFaster(bool accel)
2289 // Increase the speed of rotation, optionally by an increased amount.
2290 if (fabs(m_RotationStep) == 180.0)
2291 return;
2293 m_RotationStep *= accel ? 1.44 : 1.2;
2294 if (fabs(m_RotationStep) > 180.0) {
2295 m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
2297 if (m_Rotating)
2298 SetPanBase();
2301 void GfxCore::SwitchToElevation()
2303 // Perform an animated switch to elevation view.
2305 if (m_SwitchingTo != ELEVATION) {
2306 SetTiltBase();
2307 m_SwitchingTo = ELEVATION;
2308 } else {
2309 // A second order to switch takes us there right away
2310 TiltCave(-m_TiltAngle);
2311 m_SwitchingTo = 0;
2312 ForceRefresh();
2316 void GfxCore::SwitchToPlan()
2318 // Perform an animated switch to plan view.
2320 if (m_SwitchingTo != PLAN) {
2321 SetTiltBase();
2322 m_SwitchingTo = PLAN;
2323 } else {
2324 // A second order to switch takes us there right away
2325 TiltCave(-90.0 - m_TiltAngle);
2326 m_SwitchingTo = 0;
2327 ForceRefresh();
2331 void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2334 SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
2335 Double scale = HUGE_VAL;
2336 const Vector3 ext = m_Parent->GetExtent();
2337 if (xmax > xmin) {
2338 Double s = ext.GetX() / (xmax - xmin);
2339 if (s < scale) scale = s;
2341 if (ymax > ymin) {
2342 Double s = ext.GetY() / (ymax - ymin);
2343 if (s < scale) scale = s;
2345 if (!ShowingPlan() && zmax > zmin) {
2346 Double s = ext.GetZ() / (zmax - zmin);
2347 if (s < scale) scale = s;
2349 if (scale != HUGE_VAL) SetScale(scale);
2350 ForceRefresh();
2353 bool GfxCore::CanRaiseViewpoint() const
2355 // Determine if the survey can be viewed from a higher angle of elevation.
2357 return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
2360 bool GfxCore::CanLowerViewpoint() const
2362 // Determine if the survey can be viewed from a lower angle of elevation.
2364 return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
2367 bool GfxCore::HasDepth() const
2369 return m_Parent->GetDepthExtent() == 0.0;
2372 bool GfxCore::HasErrorInformation() const
2374 return m_Parent->HasErrorInformation();
2377 bool GfxCore::HasDateInformation() const
2379 return m_Parent->GetDateMin() >= 0;
2382 bool GfxCore::ShowingPlan() const
2384 // Determine if the survey is in plan view.
2386 return (m_TiltAngle == -90.0);
2389 bool GfxCore::ShowingElevation() const
2391 // Determine if the survey is in elevation view.
2393 return (m_TiltAngle == 0.0);
2396 bool GfxCore::ShowingMeasuringLine() const
2398 // Determine if the measuring line is being shown. Only check if "there"
2399 // is valid, since that means the measuring line anchor is out.
2401 return m_there;
2404 void GfxCore::ToggleFlag(bool* flag, int update)
2406 *flag = !*flag;
2407 if (update == UPDATE_BLOBS) {
2408 UpdateBlobs();
2409 } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2410 UpdateBlobs();
2411 InvalidateList(LIST_CROSSES);
2412 m_HitTestGridValid = false;
2414 ForceRefresh();
2417 int GfxCore::GetNumEntrances() const
2419 return m_Parent->GetNumEntrances();
2422 int GfxCore::GetNumFixedPts() const
2424 return m_Parent->GetNumFixedPts();
2427 int GfxCore::GetNumExportedPts() const
2429 return m_Parent->GetNumExportedPts();
2432 void GfxCore::ToggleTerrain()
2434 if (!m_Terrain && !dem) {
2435 // OnOpenTerrain() calls us if a file is selected.
2436 wxCommandEvent dummy;
2437 m_Parent->OnOpenTerrain(dummy);
2438 return;
2440 ToggleFlag(&m_Terrain);
2443 void GfxCore::ToggleFatFinger()
2445 if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2446 sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2447 wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2448 } else {
2449 sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2450 wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2454 void GfxCore::ClearTreeSelection()
2456 m_Parent->ClearTreeSelection();
2459 void GfxCore::CentreOn(const Point &p)
2461 SetTranslation(-p);
2462 m_HitTestGridValid = false;
2464 ForceRefresh();
2467 void GfxCore::ForceRefresh()
2469 Refresh(false);
2472 void GfxCore::GenerateList(unsigned int l)
2474 assert(m_HaveData);
2476 switch (l) {
2477 case LIST_COMPASS:
2478 DrawCompass();
2479 break;
2480 case LIST_CLINO:
2481 DrawClino();
2482 break;
2483 case LIST_CLINO_BACK:
2484 DrawClinoBack();
2485 break;
2486 case LIST_SCALE_BAR:
2487 DrawScaleBar();
2488 break;
2489 case LIST_DEPTH_KEY:
2490 DrawDepthKey();
2491 break;
2492 case LIST_DATE_KEY:
2493 DrawDateKey();
2494 break;
2495 case LIST_ERROR_KEY:
2496 DrawErrorKey();
2497 break;
2498 case LIST_GRADIENT_KEY:
2499 DrawGradientKey();
2500 break;
2501 case LIST_LENGTH_KEY:
2502 DrawLengthKey();
2503 break;
2504 case LIST_UNDERGROUND_LEGS:
2505 GenerateDisplayList(false);
2506 break;
2507 case LIST_TUBES:
2508 GenerateDisplayListTubes();
2509 break;
2510 case LIST_SURFACE_LEGS:
2511 GenerateDisplayList(true);
2512 break;
2513 case LIST_BLOBS:
2514 GenerateBlobsDisplayList();
2515 break;
2516 case LIST_CROSSES: {
2517 BeginCrosses();
2518 SetColour(col_LIGHT_GREY);
2519 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2520 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2521 while (pos != m_Parent->GetLabelsEnd()) {
2522 const LabelInfo* label = *pos++;
2524 if ((m_Surface && label->IsSurface()) ||
2525 (m_Legs && label->IsUnderground()) ||
2526 (!label->IsSurface() && !label->IsUnderground())) {
2527 // Check if this station should be displayed
2528 // (last case above is for stns with no legs attached)
2529 if (filter && !filter->CheckVisible(label->GetText()))
2530 continue;
2531 DrawCross(label->GetX(), label->GetY(), label->GetZ());
2534 EndCrosses();
2535 break;
2537 case LIST_GRID:
2538 DrawGrid();
2539 break;
2540 case LIST_SHADOW:
2541 GenerateDisplayListShadow();
2542 break;
2543 case LIST_TERRAIN:
2544 DrawTerrain();
2545 break;
2546 default:
2547 assert(false);
2548 break;
2552 void GfxCore::ToggleSmoothShading()
2554 GLACanvas::ToggleSmoothShading();
2555 InvalidateList(LIST_TUBES);
2556 ForceRefresh();
2559 void GfxCore::GenerateDisplayList(bool surface)
2561 unsigned surf_or_not = surface ? img_FLAG_SURFACE : 0;
2562 // Generate the display list for the surface or underground legs.
2563 for (int f = 0; f != 8; ++f) {
2564 if ((f & img_FLAG_SURFACE) != surf_or_not) continue;
2565 const unsigned SHOW_DASHED_AND_FADED = unsigned(-1);
2566 unsigned style = SHOW_NORMAL;
2567 if ((f & img_FLAG_SPLAY) && m_Splays != SHOW_NORMAL) {
2568 style = m_Splays;
2569 } else if (f & img_FLAG_DUPLICATE) {
2570 style = m_Dupes;
2572 if (f & img_FLAG_SURFACE) {
2573 if (style == SHOW_FADED) {
2574 style = SHOW_DASHED_AND_FADED;
2575 } else {
2576 style = SHOW_DASHED;
2580 switch (style) {
2581 case SHOW_HIDE:
2582 continue;
2583 case SHOW_FADED:
2584 SetAlpha(0.4);
2585 break;
2586 case SHOW_DASHED:
2587 EnableDashedLines();
2588 break;
2589 case SHOW_DASHED_AND_FADED:
2590 SetAlpha(0.4);
2591 EnableDashedLines();
2592 break;
2595 void (GfxCore::* add_poly)(const traverse&);
2596 if (surface) {
2597 if (m_ColourBy == COLOUR_BY_ERROR) {
2598 add_poly = &GfxCore::AddPolylineError;
2599 } else {
2600 add_poly = &GfxCore::AddPolyline;
2602 } else {
2603 add_poly = AddPoly;
2606 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2607 list<traverse>::const_iterator trav = m_Parent->traverses_begin(f, filter);
2608 list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2609 while (trav != tend) {
2610 (this->*add_poly)(*trav);
2611 trav = m_Parent->traverses_next(f, filter, trav);
2614 switch (style) {
2615 case SHOW_FADED:
2616 SetAlpha(1.0);
2617 break;
2618 case SHOW_DASHED:
2619 DisableDashedLines();
2620 break;
2621 case SHOW_DASHED_AND_FADED:
2622 DisableDashedLines();
2623 SetAlpha(1.0);
2624 break;
2629 void GfxCore::GenerateDisplayListTubes()
2631 // Generate the display list for the tubes.
2632 list<vector<XSect>>::iterator trav = m_Parent->tubes_begin();
2633 list<vector<XSect>>::iterator tend = m_Parent->tubes_end();
2634 while (trav != tend) {
2635 SkinPassage(*trav);
2636 ++trav;
2640 void GfxCore::GenerateDisplayListShadow()
2642 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2643 SetColour(col_BLACK);
2644 for (int f = 0; f != 8; ++f) {
2645 // Only include underground legs in the shadow.
2646 if ((f & img_FLAG_SURFACE) != 0) continue;
2647 list<traverse>::const_iterator trav = m_Parent->traverses_begin(f, filter);
2648 list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2649 while (trav != tend) {
2650 AddPolylineShadow(*trav);
2651 trav = m_Parent->traverses_next(f, filter, trav);
2656 void
2657 GfxCore::parse_hgt_filename(const wxString & lc_name)
2659 char * leaf = leaf_from_fnm(lc_name.utf8_str());
2660 const char * p = leaf;
2661 char * q;
2662 char dirn = *p++;
2663 o_y = strtoul(p, &q, 10);
2664 p = q;
2665 if (dirn == 's')
2666 o_y = -o_y;
2667 ++o_y;
2668 dirn = *p++;
2669 o_x = strtoul(p, &q, 10);
2670 if (dirn == 'w')
2671 o_x = -o_x;
2672 bigendian = true;
2673 nodata_value = -32768;
2674 osfree(leaf);
2677 size_t
2678 GfxCore::parse_hdr(wxInputStream & is, unsigned long & skipbytes)
2680 // ESRI docs say NBITS defaults to 8.
2681 unsigned long nbits = 8;
2682 // ESRI docs say NBANDS defaults to 1.
2683 unsigned long nbands = 1;
2684 unsigned long bandrowbytes = 0;
2685 unsigned long totalrowbytes = 0;
2686 // ESRI docs say ULXMAP defaults to 0.
2687 o_x = 0.0;
2688 // ESRI docs say ULYMAP defaults to NROWS - 1.
2689 o_y = HUGE_VAL;
2690 // ESRI docs say XDIM and YDIM default to 1.
2691 step_x = step_y = 1.0;
2692 while (!is.Eof()) {
2693 wxString line;
2694 int ch;
2695 while ((ch = is.GetC()) != wxEOF) {
2696 if (ch == '\n' || ch == '\r') break;
2697 line += wxChar(ch);
2699 #define CHECK(X, COND) \
2700 } else if (line.StartsWith(wxT(X " "))) { \
2701 size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2702 if (v == line.npos || !(COND)) { \
2703 err += wxT("Unexpected value for " X); \
2705 wxString err;
2706 if (false) {
2707 // I = little-endian; M = big-endian
2708 CHECK("BYTEORDER", (bigendian = (line[v] == 'M')) || line[v] == 'I')
2709 // ESRI docs say LAYOUT defaults to BIL if not specified.
2710 CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2711 CHECK("NROWS", line.substr(v).ToCULong(&dem_height))
2712 CHECK("NCOLS", line.substr(v).ToCULong(&dem_width))
2713 // ESRI docs say NBANDS defaults to 1 if not specified.
2714 CHECK("NBANDS", line.substr(v).ToCULong(&nbands) && nbands == 1)
2715 CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2716 CHECK("BANDROWBYTES", line.substr(v).ToCULong(&bandrowbytes))
2717 CHECK("TOTALROWBYTES", line.substr(v).ToCULong(&totalrowbytes))
2718 // PIXELTYPE is a GDAL extension, so may not be present.
2719 CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2720 CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2721 CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2722 CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2723 CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2724 CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2725 CHECK("SKIPBYTES", line.substr(v).ToCULong(&skipbytes))
2727 if (!err.empty()) {
2728 wxMessageBox(err);
2731 if (o_y == HUGE_VAL) {
2732 o_y = dem_height - 1;
2734 if (bandrowbytes != 0) {
2735 if (nbits * dem_width != bandrowbytes * 8) {
2736 wxMessageBox("BANDROWBYTES setting indicates unused bits after each band - not currently supported");
2739 if (totalrowbytes != 0) {
2740 // This is the ESRI default for BIL, for BIP it would be
2741 // nbands * bandrowbytes.
2742 if (nbands * nbits * dem_width != totalrowbytes * 8) {
2743 wxMessageBox("TOTALROWBYTES setting indicates unused bits after "
2744 "each row - not currently supported");
2747 return ((nbits * dem_width + 7) / 8) * dem_height;
2750 bool
2751 GfxCore::read_bil(wxInputStream & is, size_t size, unsigned long skipbytes)
2753 bool know_size = true;
2754 if (!size) {
2755 // If the stream doesn't know its size, GetSize() returns 0.
2756 size = is.GetSize();
2757 if (!size) {
2758 size = DEFAULT_HGT_SIZE;
2759 know_size = false;
2762 dem = new unsigned short[size / 2];
2763 if (skipbytes) {
2764 if (is.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2765 while (skipbytes) {
2766 unsigned long to_read = skipbytes;
2767 if (size < to_read) to_read = size;
2768 is.Read(reinterpret_cast<char *>(dem), to_read);
2769 size_t c = is.LastRead();
2770 if (c == 0) {
2771 wxMessageBox(wxT("Failed to skip terrain data header"));
2772 break;
2774 skipbytes -= c;
2779 #if wxCHECK_VERSION(2,9,5)
2780 if (!is.ReadAll(dem, size)) {
2781 if (know_size) {
2782 // FIXME: On __WXMSW__ currently we fail to
2783 // read any data from files in zips.
2784 delete [] dem;
2785 dem = NULL;
2786 wxMessageBox(wxT("Failed to read terrain data"));
2787 return false;
2789 size = is.LastRead();
2791 #else
2792 char * p = reinterpret_cast<char *>(dem);
2793 while (size) {
2794 is.Read(p, size);
2795 size_t c = is.LastRead();
2796 if (c == 0) {
2797 if (!know_size) {
2798 size = DEFAULT_HGT_SIZE - size;
2799 if (size)
2800 break;
2802 delete [] dem;
2803 dem = NULL;
2804 wxMessageBox(wxT("Failed to read terrain data"));
2805 return false;
2807 p += c;
2808 size -= c;
2810 #endif
2812 if (dem_width == 0 && dem_height == 0) {
2813 dem_width = dem_height = sqrt(size / 2);
2814 if (dem_width * dem_height * 2 != size) {
2815 delete [] dem;
2816 dem = NULL;
2817 wxMessageBox(wxT("HGT format data doesn't form a square"));
2818 return false;
2820 step_x = step_y = 1.0 / dem_width;
2823 return true;
2826 bool GfxCore::LoadDEM(const wxString & file)
2828 if (m_Parent->GetCSProj().empty()) {
2829 wxMessageBox(wxT("No coordinate system specified in survey data"));
2830 return false;
2833 delete [] dem;
2834 dem = NULL;
2836 size_t size = 0;
2837 // Default is to not skip any bytes.
2838 unsigned long skipbytes = 0;
2839 // For .hgt files, default to using filesize to determine.
2840 dem_width = dem_height = 0;
2841 // ESRI say "The default byte order is the same as that of the host machine
2842 // executing the software", but that's stupid so we default to
2843 // little-endian.
2844 bigendian = false;
2846 wxFileInputStream fs(file);
2847 if (!fs.IsOk()) {
2848 wxMessageBox(wxT("Failed to open DEM file"));
2849 return false;
2852 const wxString & lc_file = file.Lower();
2853 if (lc_file.EndsWith(wxT(".hgt"))) {
2854 parse_hgt_filename(lc_file);
2855 read_bil(fs, size, skipbytes);
2856 } else if (lc_file.EndsWith(wxT(".bil"))) {
2857 wxString hdr_file = file;
2858 hdr_file.replace(file.size() - 4, 4, wxT(".hdr"));
2859 wxFileInputStream hdr_is(hdr_file);
2860 if (!hdr_is.IsOk()) {
2861 wxMessageBox(wxT("Failed to open HDR file '") + hdr_file + wxT("'"));
2862 return false;
2864 size = parse_hdr(hdr_is, skipbytes);
2865 read_bil(fs, size, skipbytes);
2866 } else if (lc_file.EndsWith(wxT(".zip"))) {
2867 wxZipEntry * ze_data = NULL;
2868 wxZipInputStream zs(fs);
2869 wxZipEntry * ze;
2870 while ((ze = zs.GetNextEntry()) != NULL) {
2871 if (!ze->IsDir()) {
2872 const wxString & lc_name = ze->GetName().Lower();
2873 if (!ze_data && lc_name.EndsWith(wxT(".hgt"))) {
2874 // SRTM .hgt files are raw binary data, with the filename
2875 // encoding the coordinates.
2876 parse_hgt_filename(lc_name);
2877 read_bil(zs, size, skipbytes);
2878 delete ze;
2879 break;
2882 if (!ze_data && lc_name.EndsWith(wxT(".bil"))) {
2883 if (size) {
2884 read_bil(zs, size, skipbytes);
2885 break;
2887 ze_data = ze;
2888 continue;
2891 if (lc_name.EndsWith(wxT(".hdr"))) {
2892 size = parse_hdr(zs, skipbytes);
2893 if (ze_data) {
2894 if (!zs.OpenEntry(*ze_data)) {
2895 wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2896 break;
2898 read_bil(zs, size, skipbytes);
2900 } else if (lc_name.EndsWith(wxT(".prj"))) {
2901 //FIXME: check this matches the datum string we use
2902 //Projection GEOGRAPHIC
2903 //Datum WGS84
2904 //Zunits METERS
2905 //Units DD
2906 //Spheroid WGS84
2907 //Xshift 0.0000000000
2908 //Yshift 0.0000000000
2909 //Parameters
2912 delete ze;
2914 delete ze_data;
2917 if (!dem) {
2918 return false;
2921 InvalidateList(LIST_TERRAIN);
2922 ForceRefresh();
2923 return true;
2926 void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2928 Vector3 n = (b - a) * (c - a);
2929 n.normalise();
2930 Double factor = dot(n, light) * .95 + .05;
2931 SetColour(col_WHITE, factor);
2932 PlaceVertex(a);
2933 PlaceVertex(b);
2934 PlaceVertex(c);
2935 ++n_tris;
2938 // Like wxBusyCursor, but you can cancel it early.
2939 class AvenBusyCursor {
2940 bool active;
2942 public:
2943 AvenBusyCursor() : active(true) {
2944 wxBeginBusyCursor();
2947 void stop() {
2948 if (active) {
2949 active = false;
2950 wxEndBusyCursor();
2954 ~AvenBusyCursor() {
2955 stop();
2959 void GfxCore::DrawTerrain()
2961 if (!dem) return;
2963 AvenBusyCursor hourglass;
2965 // Draw terrain to twice the extent, or at least 1km.
2966 double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2967 #define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2968 static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2969 if (!pj_in) {
2970 ToggleTerrain();
2971 delete [] dem;
2972 dem = NULL;
2973 hourglass.stop();
2974 error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2975 return;
2977 static projPJ pj_out = pj_init_plus(m_Parent->GetCSProj().c_str());
2978 if (!pj_out) {
2979 ToggleTerrain();
2980 delete [] dem;
2981 dem = NULL;
2982 hourglass.stop();
2983 error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->GetCSProj().c_str());
2984 return;
2986 n_tris = 0;
2987 SetAlpha(0.3);
2988 BeginTriangles();
2989 const Vector3 & off = m_Parent->GetOffset();
2990 vector<Vector3> prevcol(dem_height + 1);
2991 for (size_t x = 0; x < dem_width; ++x) {
2992 double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2993 Vector3 prev;
2994 for (size_t y = 0; y < dem_height; ++y) {
2995 unsigned short elev = dem[x + y * dem_width];
2996 #ifdef WORDS_BIGENDIAN
2997 const bool MACHINE_BIGENDIAN = true;
2998 #else
2999 const bool MACHINE_BIGENDIAN = false;
3000 #endif
3001 if (bigendian != MACHINE_BIGENDIAN) {
3002 #if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
3003 elev = __builtin_bswap16(elev);
3004 #else
3005 elev = (elev >> 8) | (elev << 8);
3006 #endif
3008 double Z = (short)elev;
3009 Vector3 pt;
3010 if (Z == nodata_value) {
3011 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
3012 } else {
3013 double X = X_;
3014 double Y = (o_y - y * step_y) * DEG_TO_RAD;
3015 pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
3016 pt = Vector3(X, Y, Z) - off;
3017 double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
3018 if (dist_2 > r_sqrd) {
3019 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
3022 if (x > 0 && y > 0) {
3023 const Vector3 & a = prevcol[y - 1];
3024 const Vector3 & b = prevcol[y];
3025 // If all points are valid, split the quadrilateral into
3026 // triangles along the shorter 3D diagonal, which typically
3027 // looks better:
3029 // ----->
3030 // prev---a x prev---a
3031 // | |P /| |\ S|
3032 // y | | / | or | \ |
3033 // V | / | | \ |
3034 // |/ Q| |R \|
3035 // b----pt b----pt
3037 // FORWARD BACKWARD
3038 enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
3039 int valid =
3040 ((prev.GetZ() != DBL_MAX)) |
3041 ((a.GetZ() != DBL_MAX) << 1) |
3042 ((b.GetZ() != DBL_MAX) << 2) |
3043 ((pt.GetZ() != DBL_MAX) << 3);
3044 static const int tris_map[16] = {
3045 NONE, // nothing valid
3046 NONE, // prev
3047 NONE, // a
3048 NONE, // a, prev
3049 NONE, // b
3050 NONE, // b, prev
3051 NONE, // b, a
3052 P, // b, a, prev
3053 NONE, // pt
3054 NONE, // pt, prev
3055 NONE, // pt, a
3056 S, // pt, a, prev
3057 NONE, // pt, b
3058 R, // pt, b, prev
3059 Q, // pt, b, a
3060 ALL, // pt, b, a, prev
3062 int tris = tris_map[valid];
3063 if (tris == ALL) {
3064 // All points valid.
3065 if ((a - b).magnitude() < (prev - pt).magnitude()) {
3066 tris = P | Q;
3067 } else {
3068 tris = R | S;
3071 if (tris & P)
3072 DrawTerrainTriangle(a, prev, b);
3073 if (tris & Q)
3074 DrawTerrainTriangle(a, b, pt);
3075 if (tris & R)
3076 DrawTerrainTriangle(pt, prev, b);
3077 if (tris & S)
3078 DrawTerrainTriangle(a, prev, pt);
3080 prev = prevcol[y];
3081 prevcol[y].assign(pt);
3084 EndTriangles();
3085 SetAlpha(1.0);
3086 if (n_tris == 0) {
3087 ToggleTerrain();
3088 delete [] dem;
3089 dem = NULL;
3090 hourglass.stop();
3091 /* TRANSLATORS: Aven shows a circle of terrain covering the area
3092 * of the survey plus a bit, but the terrain data file didn't
3093 * contain any data inside that circle.
3095 error(/*No terrain data near area of survey*/161);
3099 // Plot blobs.
3100 void GfxCore::GenerateBlobsDisplayList()
3102 if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
3103 m_Parent->GetNumHighlightedPts()))
3104 return;
3106 // Plot blobs.
3107 const SurveyFilter* filter = m_Parent->GetTreeFilter();
3108 gla_colour prev_col = col_BLACK; // not a colour used for blobs
3109 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
3110 BeginBlobs();
3111 while (pos != m_Parent->GetLabelsEnd()) {
3112 const LabelInfo* label = *pos++;
3114 // When more than one flag is set on a point:
3115 // search results take priority over entrance highlighting
3116 // which takes priority over fixed point
3117 // highlighting, which in turn takes priority over exported
3118 // point highlighting.
3120 if (!((m_Surface && label->IsSurface()) ||
3121 (m_Legs && label->IsUnderground()) ||
3122 (!label->IsSurface() && !label->IsUnderground()))) {
3123 // if this station isn't to be displayed, skip to the next
3124 // (last case is for stns with no legs attached)
3125 continue;
3127 if (filter && !filter->CheckVisible(label->GetText()))
3128 continue;
3130 gla_colour col;
3132 if (label->IsHighLighted()) {
3133 col = col_YELLOW;
3134 } else if (m_Entrances && label->IsEntrance()) {
3135 col = col_GREEN;
3136 } else if (m_FixedPts && label->IsFixedPt()) {
3137 col = col_RED;
3138 } else if (m_ExportedPts && label->IsExportedPt()) {
3139 col = col_TURQUOISE;
3140 } else {
3141 continue;
3144 // Stations are sorted by blob type, so colour changes are infrequent.
3145 if (col != prev_col) {
3146 SetColour(col);
3147 prev_col = col;
3149 DrawBlob(label->GetX(), label->GetY(), label->GetZ());
3151 EndBlobs();
3154 void GfxCore::DrawIndicators()
3156 // Draw colour key.
3157 if (m_ColourKey) {
3158 drawing_list key_list = LIST_LIMIT_;
3159 switch (m_ColourBy) {
3160 case COLOUR_BY_DEPTH:
3161 key_list = LIST_DEPTH_KEY; break;
3162 case COLOUR_BY_DATE:
3163 key_list = LIST_DATE_KEY; break;
3164 case COLOUR_BY_ERROR:
3165 key_list = LIST_ERROR_KEY; break;
3166 case COLOUR_BY_GRADIENT:
3167 key_list = LIST_GRADIENT_KEY; break;
3168 case COLOUR_BY_LENGTH:
3169 key_list = LIST_LENGTH_KEY; break;
3170 #if 0 // FIXME Key for survey colours?
3171 case COLOUR_BY_SURVEY:
3172 key_list = LIST_SURVEY_KEY; break;
3173 #endif
3175 if (key_list != LIST_LIMIT_) {
3176 DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
3177 GetYSize() - KEY_OFFSET_Y, 0);
3181 // Draw compass or elevation/heading indicators.
3182 if (m_Compass || m_Clino) {
3183 if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
3186 // Draw scalebar.
3187 if (m_Scalebar && !GetPerspective()) {
3188 DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
3192 void GfxCore::PlaceVertexWithColour(const Vector3 & v,
3193 glaTexCoord tex_x, glaTexCoord tex_y,
3194 Double factor)
3196 SetColour(col_WHITE, factor);
3197 PlaceVertex(v, tex_x, tex_y);
3200 void GfxCore::SetDepthColour(Double z, Double factor) {
3201 // Set the drawing colour based on the altitude.
3202 Double z_ext = m_Parent->GetDepthExtent();
3204 z -= m_Parent->GetDepthMin();
3205 // points arising from tubes may be slightly outside the limits...
3206 if (z < 0) z = 0;
3207 if (z > z_ext) z = z_ext;
3209 if (z == 0) {
3210 SetColour(GetPen(0), factor);
3211 return;
3214 assert(z_ext > 0.0);
3215 Double how_far = z / z_ext;
3216 assert(how_far >= 0.0);
3217 assert(how_far <= 1.0);
3219 int band = int(floor(how_far * (GetNumColourBands() - 1)));
3220 GLAPen pen1 = GetPen(band);
3221 if (band < GetNumColourBands() - 1) {
3222 const GLAPen& pen2 = GetPen(band + 1);
3224 Double interval = z_ext / (GetNumColourBands() - 1);
3225 Double into_band = z / interval - band;
3227 // printf("%g z_offset=%g interval=%g band=%d\n", into_band,
3228 // z_offset, interval, band);
3229 // FIXME: why do we need to clamp here? Is it because the walls can
3230 // extend further up/down than the centre-line?
3231 if (into_band < 0.0) into_band = 0.0;
3232 if (into_band > 1.0) into_band = 1.0;
3233 assert(into_band >= 0.0);
3234 assert(into_band <= 1.0);
3236 pen1.Interpolate(pen2, into_band);
3238 SetColour(pen1, factor);
3241 void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
3243 SetDepthColour(v.GetZ(), factor);
3244 PlaceVertex(v);
3247 void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
3248 glaTexCoord tex_x, glaTexCoord tex_y,
3249 Double factor)
3251 SetDepthColour(v.GetZ(), factor);
3252 PlaceVertex(v, tex_x, tex_y);
3255 void GfxCore::SplitLineAcrossBands(int band, int band2,
3256 const Vector3 &p, const Vector3 &q,
3257 Double factor)
3259 const int step = (band < band2) ? 1 : -1;
3260 for (int i = band; i != band2; i += step) {
3261 const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3263 // Find the intersection point of the line p -> q
3264 // with the plane parallel to the xy-plane with z-axis intersection z.
3265 assert(q.GetZ() - p.GetZ() != 0.0);
3267 const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3268 // assert(0.0 <= t && t <= 1.0); FIXME: rounding problems!
3270 const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3271 const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3273 PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
3277 void GfxCore::SplitPolyAcrossBands(vector<vector<Split>>& splits,
3278 int band, int band2,
3279 const Vector3 &p, const Vector3 &q,
3280 glaTexCoord ptx, glaTexCoord pty,
3281 glaTexCoord w, glaTexCoord h)
3283 const int step = (band < band2) ? 1 : -1;
3284 for (int i = band; i != band2; i += step) {
3285 const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3287 // Find the intersection point of the line p -> q
3288 // with the plane parallel to the xy-plane with z-axis intersection z.
3289 assert(q.GetZ() - p.GetZ() != 0.0);
3291 const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3292 // assert(0.0 <= t && t <= 1.0); FIXME: rounding problems!
3294 const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3295 const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3296 glaTexCoord tx = ptx, ty = pty;
3297 if (w) tx += t * w;
3298 if (h) ty += t * h;
3300 splits[i].push_back(Split(Vector3(x, y, z), tx, ty));
3301 splits[i + step].push_back(Split(Vector3(x, y, z), tx, ty));
3305 int GfxCore::GetDepthColour(Double z) const
3307 // Return the (0-based) depth colour band index for a z-coordinate.
3308 Double z_ext = m_Parent->GetDepthExtent();
3309 z -= m_Parent->GetDepthMin();
3310 // We seem to get rounding differences causing z to sometimes be slightly
3311 // less than GetDepthMin() here, and it can certainly be true for passage
3312 // tubes, so just clamp the value to 0.
3313 if (z <= 0) return 0;
3314 // We seem to get rounding differences causing z to sometimes exceed z_ext
3315 // by a small amount here (see: https://trac.survex.com/ticket/26) and it
3316 // can certainly be true for passage tubes, so just clamp the value.
3317 if (z >= z_ext) return GetNumColourBands() - 1;
3318 return int(z / z_ext * (GetNumColourBands() - 1));
3321 Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
3323 // Return the z-coordinate of the depth colour boundary between
3324 // two adjacent depth colour bands (specified by 0-based indices).
3326 assert((a == b - 1) || (a == b + 1));
3327 if (GetNumColourBands() == 1) return 0;
3329 int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
3330 Double z_ext = m_Parent->GetDepthExtent();
3331 return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
3334 void GfxCore::AddPolyline(const traverse & centreline)
3336 BeginPolyline();
3337 SetColour(col_WHITE);
3338 vector<PointInfo>::const_iterator i = centreline.begin();
3339 PlaceVertex(*i);
3340 ++i;
3341 while (i != centreline.end()) {
3342 PlaceVertex(*i);
3343 ++i;
3345 EndPolyline();
3348 void GfxCore::AddPolylineShadow(const traverse & centreline)
3350 BeginPolyline();
3351 const double z = -0.5 * m_Parent->GetExtent().GetZ();
3352 vector<PointInfo>::const_iterator i = centreline.begin();
3353 PlaceVertex(i->GetX(), i->GetY(), z);
3354 ++i;
3355 while (i != centreline.end()) {
3356 PlaceVertex(i->GetX(), i->GetY(), z);
3357 ++i;
3359 EndPolyline();
3362 void GfxCore::AddPolylineDepth(const traverse & centreline)
3364 BeginPolyline();
3365 vector<PointInfo>::const_iterator i, prev_i;
3366 i = centreline.begin();
3367 int band0 = GetDepthColour(i->GetZ());
3368 PlaceVertexWithDepthColour(*i);
3369 prev_i = i;
3370 ++i;
3371 while (i != centreline.end()) {
3372 int band = GetDepthColour(i->GetZ());
3373 if (band != band0) {
3374 SplitLineAcrossBands(band0, band, *prev_i, *i);
3375 band0 = band;
3377 PlaceVertexWithDepthColour(*i);
3378 prev_i = i;
3379 ++i;
3381 EndPolyline();
3384 void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3385 const Vector3 &c, const Vector3 &d)
3387 Vector3 normal = (a - c) * (d - b);
3388 normal.normalise();
3389 Double factor = dot(normal, light) * .3 + .7;
3390 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3391 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3392 // FIXME: should plot triangles instead to avoid rendering glitches.
3393 BeginQuadrilaterals();
3394 PlaceVertexWithColour(a, 0, 0, factor);
3395 PlaceVertexWithColour(b, w, 0, factor);
3396 PlaceVertexWithColour(c, w, h, factor);
3397 PlaceVertexWithColour(d, 0, h, factor);
3398 EndQuadrilaterals();
3401 void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3402 const Vector3 &c, const Vector3 &d)
3404 Vector3 normal = (a - c) * (d - b);
3405 normal.normalise();
3406 Double factor = dot(normal, light) * .3 + .7;
3407 int a_band, b_band, c_band, d_band;
3408 a_band = GetDepthColour(a.GetZ());
3409 a_band = min(max(a_band, 0), GetNumColourBands());
3410 b_band = GetDepthColour(b.GetZ());
3411 b_band = min(max(b_band, 0), GetNumColourBands());
3412 c_band = GetDepthColour(c.GetZ());
3413 c_band = min(max(c_band, 0), GetNumColourBands());
3414 d_band = GetDepthColour(d.GetZ());
3415 d_band = min(max(d_band, 0), GetNumColourBands());
3416 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3417 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3418 int min_band = min(min(a_band, b_band), min(c_band, d_band));
3419 int max_band = max(max(a_band, b_band), max(c_band, d_band));
3420 if (min_band == max_band) {
3421 // Simple case - the polygon is entirely within one band.
3422 BeginPolygon();
3423 //// PlaceNormal(normal);
3424 PlaceVertexWithDepthColour(a, 0, 0, factor);
3425 PlaceVertexWithDepthColour(b, w, 0, factor);
3426 PlaceVertexWithDepthColour(c, w, h, factor);
3427 PlaceVertexWithDepthColour(d, 0, h, factor);
3428 EndPolygon();
3429 } else {
3430 // We need to make a separate polygon for each depth band...
3431 vector<vector<Split>> splits;
3432 splits.resize(max_band + 1);
3433 splits[a_band].push_back(Split(a, 0, 0));
3434 if (a_band != b_band) {
3435 SplitPolyAcrossBands(splits, a_band, b_band, a, b, 0, 0, w, 0);
3437 splits[b_band].push_back(Split(b, w, 0));
3438 if (b_band != c_band) {
3439 SplitPolyAcrossBands(splits, b_band, c_band, b, c, w, 0, 0, h);
3441 splits[c_band].push_back(Split(c, w, h));
3442 if (c_band != d_band) {
3443 SplitPolyAcrossBands(splits, c_band, d_band, c, d, w, h, -w, 0);
3445 splits[d_band].push_back(Split(d, 0, h));
3446 if (d_band != a_band) {
3447 SplitPolyAcrossBands(splits, d_band, a_band, d, a, 0, h, 0, -h);
3449 for (int band = min_band; band <= max_band; ++band) {
3450 BeginPolygon();
3451 for (auto&& item : splits[band]) {
3452 PlaceVertexWithDepthColour(item.vec, item.tx, item.ty, factor);
3454 EndPolygon();
3459 void GfxCore::SetColourFromDate(int date, Double factor)
3461 // Set the drawing colour based on a date.
3463 if (date == -1) {
3464 // Undated.
3465 SetColour(NODATA_COLOUR, factor);
3466 return;
3469 int date_offset = date - m_Parent->GetDateMin();
3470 if (date_offset == 0) {
3471 // Earliest date - handle as a special case for the single date case.
3472 SetColour(GetPen(0), factor);
3473 return;
3476 int date_ext = m_Parent->GetDateExtent();
3477 Double how_far = (Double)date_offset / date_ext;
3478 assert(how_far >= 0.0);
3479 assert(how_far <= 1.0);
3480 SetColourFrom01(how_far, factor);
3483 void GfxCore::AddPolylineDate(const traverse & centreline)
3485 BeginPolyline();
3486 vector<PointInfo>::const_iterator i, prev_i;
3487 i = centreline.begin();
3488 int date = i->GetDate();
3489 SetColourFromDate(date, 1.0);
3490 PlaceVertex(*i);
3491 prev_i = i;
3492 while (++i != centreline.end()) {
3493 int newdate = i->GetDate();
3494 if (newdate != date) {
3495 EndPolyline();
3496 BeginPolyline();
3497 date = newdate;
3498 SetColourFromDate(date, 1.0);
3499 PlaceVertex(*prev_i);
3501 PlaceVertex(*i);
3502 prev_i = i;
3504 EndPolyline();
3507 static int static_date_hack; // FIXME
3509 void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3510 const Vector3 &c, const Vector3 &d)
3512 Vector3 normal = (a - c) * (d - b);
3513 normal.normalise();
3514 Double factor = dot(normal, light) * .3 + .7;
3515 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3516 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3517 // FIXME: should plot triangles instead to avoid rendering glitches.
3518 BeginQuadrilaterals();
3519 //// PlaceNormal(normal);
3520 SetColourFromDate(static_date_hack, factor);
3521 PlaceVertex(a, 0, 0);
3522 PlaceVertex(b, w, 0);
3523 PlaceVertex(c, w, h);
3524 PlaceVertex(d, 0, h);
3525 EndQuadrilaterals();
3528 static double static_E_hack; // FIXME
3530 void GfxCore::SetColourFromError(double E, Double factor)
3532 // Set the drawing colour based on an error value.
3534 if (E < 0) {
3535 SetColour(NODATA_COLOUR, factor);
3536 return;
3539 Double how_far = E / MAX_ERROR;
3540 assert(how_far >= 0.0);
3541 if (how_far > 1.0) how_far = 1.0;
3542 SetColourFrom01(how_far, factor);
3545 void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3546 const Vector3 &c, const Vector3 &d)
3548 Vector3 normal = (a - c) * (d - b);
3549 normal.normalise();
3550 Double factor = dot(normal, light) * .3 + .7;
3551 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3552 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3553 // FIXME: should plot triangles instead to avoid rendering glitches.
3554 BeginQuadrilaterals();
3555 //// PlaceNormal(normal);
3556 SetColourFromError(static_E_hack, factor);
3557 PlaceVertex(a, 0, 0);
3558 PlaceVertex(b, w, 0);
3559 PlaceVertex(c, w, h);
3560 PlaceVertex(d, 0, h);
3561 EndQuadrilaterals();
3564 void GfxCore::AddPolylineError(const traverse & centreline)
3566 BeginPolyline();
3567 SetColourFromError(centreline.E, 1.0);
3568 vector<PointInfo>::const_iterator i;
3569 for(i = centreline.begin(); i != centreline.end(); ++i) {
3570 PlaceVertex(*i);
3572 EndPolyline();
3575 // gradient is in *radians*.
3576 void GfxCore::SetColourFromGradient(double gradient, Double factor)
3578 // Set the drawing colour based on the gradient of the leg.
3580 const Double GRADIENT_MAX = M_PI_2;
3581 gradient = fabs(gradient);
3582 Double how_far = gradient / GRADIENT_MAX;
3583 SetColourFrom01(how_far, factor);
3586 void GfxCore::AddPolylineGradient(const traverse & centreline)
3588 vector<PointInfo>::const_iterator i, prev_i;
3589 i = centreline.begin();
3590 prev_i = i;
3591 while (++i != centreline.end()) {
3592 BeginPolyline();
3593 SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3594 PlaceVertex(*prev_i);
3595 PlaceVertex(*i);
3596 prev_i = i;
3597 EndPolyline();
3601 static double static_gradient_hack; // FIXME
3603 void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3604 const Vector3 &c, const Vector3 &d)
3606 Vector3 normal = (a - c) * (d - b);
3607 normal.normalise();
3608 Double factor = dot(normal, light) * .3 + .7;
3609 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3610 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3611 // FIXME: should plot triangles instead to avoid rendering glitches.
3612 BeginQuadrilaterals();
3613 //// PlaceNormal(normal);
3614 SetColourFromGradient(static_gradient_hack, factor);
3615 PlaceVertex(a, 0, 0);
3616 PlaceVertex(b, w, 0);
3617 PlaceVertex(c, w, h);
3618 PlaceVertex(d, 0, h);
3619 EndQuadrilaterals();
3622 void GfxCore::SetColourFromLength(double length, Double factor)
3624 // Set the drawing colour based on log(length_of_leg).
3626 Double log_len = log10(length);
3627 Double how_far = log_len / LOG_LEN_MAX;
3628 how_far = max(how_far, 0.0);
3629 how_far = min(how_far, 1.0);
3630 SetColourFrom01(how_far, factor);
3633 void GfxCore::SetColourFromSurvey(const wxString& survey)
3635 // Set the drawing colour based on hash of name.
3636 int hash = hash_string(survey.utf8_str());
3637 wxImage::HSVValue hsv((hash & 0xff) / 256.0, (((hash >> 8) & 0x7f) | 0x80) / 256.0, 0.9);
3638 wxImage::RGBValue rgb = wxImage::HSVtoRGB(hsv);
3639 GLAPen pen;
3640 pen.SetColour(rgb.red / 256.0, rgb.green / 256.0, rgb.blue / 256.0);
3641 SetColour(pen);
3644 void GfxCore::SetColourFromSurveyStation(const wxString& name, Double factor)
3646 // Set the drawing colour based on hash of survey name.
3647 const char* p = name.utf8_str();
3648 const char* q = strrchr(p, m_Parent->GetSeparator());
3649 size_t len = q ? (q - p) : strlen(p);
3650 int hash = hash_data(p, len);
3651 wxImage::HSVValue hsv((hash & 0xff) / 256.0, (((hash >> 8) & 0x7f) | 0x80) / 256.0, 0.9);
3652 wxImage::RGBValue rgb = wxImage::HSVtoRGB(hsv);
3653 GLAPen pen;
3654 pen.SetColour(rgb.red / 256.0, rgb.green / 256.0, rgb.blue / 256.0);
3655 SetColour(pen, factor);
3658 void GfxCore::SetColourFrom01(double how_far, Double factor)
3660 double b;
3661 double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3662 int band(b);
3663 GLAPen pen1 = GetPen(band);
3664 // With 24bit colour, interpolating by less than this can have no effect.
3665 if (into_band >= 1.0 / 512.0) {
3666 const GLAPen& pen2 = GetPen(band + 1);
3667 pen1.Interpolate(pen2, into_band);
3669 SetColour(pen1, factor);
3672 void GfxCore::AddPolylineLength(const traverse & centreline)
3674 vector<PointInfo>::const_iterator i, prev_i;
3675 i = centreline.begin();
3676 prev_i = i;
3677 while (++i != centreline.end()) {
3678 BeginPolyline();
3679 SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3680 PlaceVertex(*prev_i);
3681 PlaceVertex(*i);
3682 prev_i = i;
3683 EndPolyline();
3687 static double static_length_hack; // FIXME
3689 void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3690 const Vector3 &c, const Vector3 &d)
3692 Vector3 normal = (a - c) * (d - b);
3693 normal.normalise();
3694 Double factor = dot(normal, light) * .3 + .7;
3695 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3696 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3697 // FIXME: should plot triangles instead to avoid rendering glitches.
3698 BeginQuadrilaterals();
3699 //// PlaceNormal(normal);
3700 SetColourFromLength(static_length_hack, factor);
3701 PlaceVertex(a, 0, 0);
3702 PlaceVertex(b, w, 0);
3703 PlaceVertex(c, w, h);
3704 PlaceVertex(d, 0, h);
3705 EndQuadrilaterals();
3708 void GfxCore::AddPolylineSurvey(const traverse & centreline)
3710 SetColourFromSurvey(centreline.name);
3711 vector<PointInfo>::const_iterator i, prev_i;
3712 i = centreline.begin();
3713 prev_i = i;
3714 while (++i != centreline.end()) {
3715 BeginPolyline();
3716 PlaceVertex(*prev_i);
3717 PlaceVertex(*i);
3718 prev_i = i;
3719 EndPolyline();
3723 static const wxString* static_survey_hack;
3725 void GfxCore::AddQuadrilateralSurvey(const Vector3 &a, const Vector3 &b,
3726 const Vector3 &c, const Vector3 &d)
3728 Vector3 normal = (a - c) * (d - b);
3729 normal.normalise();
3730 Double factor = dot(normal, light) * .3 + .7;
3731 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3732 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3733 // FIXME: should plot triangles instead to avoid rendering glitches.
3734 BeginQuadrilaterals();
3735 //// PlaceNormal(normal);
3736 SetColourFromSurveyStation(*static_survey_hack, factor);
3737 PlaceVertex(a, 0, 0);
3738 PlaceVertex(b, w, 0);
3739 PlaceVertex(c, w, h);
3740 PlaceVertex(d, 0, h);
3741 EndQuadrilaterals();
3744 void
3745 GfxCore::SkinPassage(vector<XSect> & centreline)
3747 const SurveyFilter* filter = m_Parent->GetTreeFilter();
3748 assert(centreline.size() > 1);
3749 Vector3 U[4];
3750 XSect* prev_pt_v = NULL;
3751 Vector3 last_right(1.0, 0.0, 0.0);
3753 // FIXME: it's not simple to set the colour of a tube based on error...
3754 // static_E_hack = something...
3755 vector<XSect>::iterator i = centreline.begin();
3756 vector<XSect>::size_type segment = 0;
3757 while (i != centreline.end()) {
3758 // get the coordinates of this vertex
3759 XSect & pt_v = *i++;
3761 bool cover_end = false;
3763 Vector3 right, up;
3765 const Vector3 up_v(0.0, 0.0, 1.0);
3767 static_survey_hack = &(pt_v.GetLabel());
3768 if (segment == 0) {
3769 assert(i != centreline.end());
3770 // first segment
3772 // get the coordinates of the next vertex
3773 const XSect & next_pt_v = *i;
3775 // calculate vector from this pt to the next one
3776 Vector3 leg_v = next_pt_v - pt_v;
3778 // obtain a vector in the LRUD plane
3779 right = leg_v * up_v;
3780 if (right.magnitude() == 0) {
3781 right = last_right;
3782 // Obtain a second vector in the LRUD plane,
3783 // perpendicular to the first.
3784 //up = right * leg_v;
3785 up = up_v;
3786 } else {
3787 last_right = right;
3788 up = up_v;
3791 cover_end = true;
3792 static_date_hack = next_pt_v.GetDate();
3793 } else if (segment + 1 == centreline.size()) {
3794 // last segment
3796 // Calculate vector from the previous pt to this one.
3797 Vector3 leg_v = pt_v - *prev_pt_v;
3799 // Obtain a horizontal vector in the LRUD plane.
3800 right = leg_v * up_v;
3801 if (right.magnitude() == 0) {
3802 right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3803 // Obtain a second vector in the LRUD plane,
3804 // perpendicular to the first.
3805 //up = right * leg_v;
3806 up = up_v;
3807 } else {
3808 last_right = right;
3809 up = up_v;
3812 cover_end = true;
3813 static_date_hack = pt_v.GetDate();
3814 } else {
3815 assert(i != centreline.end());
3816 // Intermediate segment.
3818 // Get the coordinates of the next vertex.
3819 const XSect & next_pt_v = *i;
3821 // Calculate vectors from this vertex to the
3822 // next vertex, and from the previous vertex to
3823 // this one.
3824 Vector3 leg1_v = pt_v - *prev_pt_v;
3825 Vector3 leg2_v = next_pt_v - pt_v;
3827 // Obtain horizontal vectors perpendicular to
3828 // both legs, then normalise and average to get
3829 // a horizontal bisector.
3830 Vector3 r1 = leg1_v * up_v;
3831 Vector3 r2 = leg2_v * up_v;
3832 r1.normalise();
3833 r2.normalise();
3834 right = r1 + r2;
3835 if (right.magnitude() == 0) {
3836 // This is the "mid-pitch" case...
3837 right = last_right;
3839 if (r1.magnitude() == 0) {
3840 up = up_v;
3842 // Rotate pitch section to minimise the
3843 // "torsional stress" - FIXME: use
3844 // triangles instead of rectangles?
3845 int shift = 0;
3846 Double maxdotp = 0;
3848 // Scale to unit vectors in the LRUD plane.
3849 right.normalise();
3850 up.normalise();
3851 Vector3 vec = up - right;
3852 for (int orient = 0; orient <= 3; ++orient) {
3853 Vector3 tmp = U[orient] - prev_pt_v->GetPoint();
3854 tmp.normalise();
3855 Double dotp = dot(vec, tmp);
3856 if (dotp > maxdotp) {
3857 maxdotp = dotp;
3858 shift = orient;
3861 if (shift) {
3862 if (shift != 2) {
3863 Vector3 temp(U[0]);
3864 U[0] = U[shift];
3865 U[shift] = U[2];
3866 U[2] = U[shift ^ 2];
3867 U[shift ^ 2] = temp;
3868 } else {
3869 swap(U[0], U[2]);
3870 swap(U[1], U[3]);
3873 #if 0
3874 // Check that the above code actually permuted
3875 // the vertices correctly.
3876 shift = 0;
3877 maxdotp = 0;
3878 for (int j = 0; j <= 3; ++j) {
3879 Vector3 tmp = U[j] - *prev_pt_v;
3880 tmp.normalise();
3881 Double dotp = dot(vec, tmp);
3882 if (dotp > maxdotp) {
3883 maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3884 shift = j;
3887 if (shift) {
3888 printf("New shift = %d!\n", shift);
3889 shift = 0;
3890 maxdotp = 0;
3891 for (int j = 0; j <= 3; ++j) {
3892 Vector3 tmp = U[j] - *prev_pt_v;
3893 tmp.normalise();
3894 Double dotp = dot(vec, tmp);
3895 printf(" %d : %.8f\n", j, dotp);
3898 #endif
3899 } else {
3900 up = up_v;
3902 last_right = right;
3903 static_date_hack = pt_v.GetDate();
3906 // Scale to unit vectors in the LRUD plane.
3907 right.normalise();
3908 up.normalise();
3910 Double l = fabs(pt_v.GetL());
3911 Double r = fabs(pt_v.GetR());
3912 Double u = fabs(pt_v.GetU());
3913 Double d = fabs(pt_v.GetD());
3915 // Produce coordinates of the corners of the LRUD "plane".
3916 Vector3 v[4];
3917 v[0] = pt_v.GetPoint() - right * l + up * u;
3918 v[1] = pt_v.GetPoint() + right * r + up * u;
3919 v[2] = pt_v.GetPoint() + right * r - up * d;
3920 v[3] = pt_v.GetPoint() - right * l - up * d;
3922 if (segment > 0) {
3923 if (!filter || (filter->CheckVisible(pt_v.GetLabel()) &&
3924 filter->CheckVisible(prev_pt_v->GetLabel()))) {
3925 const Vector3 & delta = pt_v - *prev_pt_v;
3926 static_length_hack = delta.magnitude();
3927 static_gradient_hack = delta.gradient();
3928 (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3929 (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3930 (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3931 (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3935 if (cover_end) {
3936 if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
3937 if (segment == 0) {
3938 (this->*AddQuad)(v[0], v[1], v[2], v[3]);
3939 } else {
3940 (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3945 prev_pt_v = &pt_v;
3946 U[0] = v[0];
3947 U[1] = v[1];
3948 U[2] = v[2];
3949 U[3] = v[3];
3951 ++segment;
3955 void GfxCore::FullScreenMode()
3957 m_Parent->ViewFullScreen();
3960 bool GfxCore::IsFullScreen() const
3962 return m_Parent->IsFullScreen();
3965 bool GfxCore::FullScreenModeShowingMenus() const
3967 return m_Parent->FullScreenModeShowingMenus();
3970 void GfxCore::FullScreenModeShowMenus(bool show)
3972 m_Parent->FullScreenModeShowMenus(show);
3975 void
3976 GfxCore::MoveViewer(double forward, double up, double right)
3978 double cT = cos(rad(m_TiltAngle));
3979 double sT = sin(rad(m_TiltAngle));
3980 double cP = cos(rad(m_PanAngle));
3981 double sP = sin(rad(m_PanAngle));
3982 Vector3 v_forward(cT * sP, cT * cP, sT);
3983 Vector3 v_up(sT * sP, sT * cP, -cT);
3984 Vector3 v_right(-cP, sP, 0);
3985 assert(fabs(dot(v_forward, v_up)) < 1e-6);
3986 assert(fabs(dot(v_forward, v_right)) < 1e-6);
3987 assert(fabs(dot(v_right, v_up)) < 1e-6);
3988 Vector3 move = v_forward * forward + v_up * up + v_right * right;
3989 AddTranslation(-move);
3990 // Show current position.
3991 m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3992 ForceRefresh();
3995 PresentationMark GfxCore::GetView() const
3997 return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3998 m_PanAngle, -m_TiltAngle, m_Scale);
4001 void GfxCore::SetView(const PresentationMark & p)
4003 m_SwitchingTo = 0;
4004 SetTranslation(p - m_Parent->GetOffset());
4005 m_PanAngle = p.angle;
4006 m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
4007 SetRotation(m_PanAngle, m_TiltAngle);
4008 SetScale(p.scale);
4009 ForceRefresh();
4012 void GfxCore::PlayPres(double speed, bool change_speed) {
4013 if (!change_speed || presentation_mode == 0) {
4014 if (speed == 0.0) {
4015 presentation_mode = 0;
4016 return;
4018 presentation_mode = PLAYING;
4019 next_mark = m_Parent->GetPresMark(MARK_FIRST);
4020 SetView(next_mark);
4021 next_mark_time = 0; // There already!
4022 this_mark_total = 0;
4023 pres_reverse = (speed < 0);
4026 if (change_speed) pres_speed = speed;
4028 if (speed != 0.0) {
4029 bool new_pres_reverse = (speed < 0);
4030 if (new_pres_reverse != pres_reverse) {
4031 pres_reverse = new_pres_reverse;
4032 if (pres_reverse) {
4033 next_mark = m_Parent->GetPresMark(MARK_PREV);
4034 } else {
4035 next_mark = m_Parent->GetPresMark(MARK_NEXT);
4037 swap(this_mark_total, next_mark_time);
4042 void GfxCore::SetColourBy(int colour_by) {
4043 m_ColourBy = colour_by;
4044 switch (colour_by) {
4045 case COLOUR_BY_DEPTH:
4046 AddQuad = &GfxCore::AddQuadrilateralDepth;
4047 AddPoly = &GfxCore::AddPolylineDepth;
4048 break;
4049 case COLOUR_BY_DATE:
4050 AddQuad = &GfxCore::AddQuadrilateralDate;
4051 AddPoly = &GfxCore::AddPolylineDate;
4052 break;
4053 case COLOUR_BY_ERROR:
4054 AddQuad = &GfxCore::AddQuadrilateralError;
4055 AddPoly = &GfxCore::AddPolylineError;
4056 break;
4057 case COLOUR_BY_GRADIENT:
4058 AddQuad = &GfxCore::AddQuadrilateralGradient;
4059 AddPoly = &GfxCore::AddPolylineGradient;
4060 break;
4061 case COLOUR_BY_LENGTH:
4062 AddQuad = &GfxCore::AddQuadrilateralLength;
4063 AddPoly = &GfxCore::AddPolylineLength;
4064 break;
4065 case COLOUR_BY_SURVEY:
4066 AddQuad = &GfxCore::AddQuadrilateralSurvey;
4067 AddPoly = &GfxCore::AddPolylineSurvey;
4068 break;
4069 default: // case COLOUR_BY_NONE:
4070 AddQuad = &GfxCore::AddQuadrilateral;
4071 AddPoly = &GfxCore::AddPolyline;
4072 break;
4075 InvalidateList(LIST_UNDERGROUND_LEGS);
4076 InvalidateList(LIST_SURFACE_LEGS);
4077 InvalidateList(LIST_TUBES);
4079 ForceRefresh();
4082 bool GfxCore::ExportMovie(const wxString & fnm)
4084 FILE* fh = wxFopen(fnm.fn_str(), wxT("wb"));
4085 if (fh == NULL) {
4086 wxGetApp().ReportError(wxString::Format(wmsg(/*Failed to open output file “%s”*/47), fnm.c_str()));
4087 return false;
4090 wxString ext;
4091 wxFileName::SplitPath(fnm, NULL, NULL, NULL, &ext, wxPATH_NATIVE);
4093 int width;
4094 int height;
4095 GetSize(&width, &height);
4096 // Round up to next multiple of 2 (required by ffmpeg).
4097 width += (width & 1);
4098 height += (height & 1);
4100 movie = new MovieMaker();
4102 // movie takes ownership of fh.
4103 if (!movie->Open(fh, ext.utf8_str(), width, height)) {
4104 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
4105 delete movie;
4106 movie = NULL;
4107 return false;
4110 PlayPres(1);
4111 return true;
4114 void
4115 GfxCore::OnPrint(const wxString &filename, const wxString &title,
4116 const wxString &datestamp,
4117 bool close_after_print)
4119 svxPrintDlg * p;
4120 p = new svxPrintDlg(m_Parent, filename, title, datestamp,
4121 m_PanAngle, m_TiltAngle,
4122 m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
4123 m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
4124 true, close_after_print);
4125 p->Show(true);
4128 void
4129 GfxCore::OnExport(const wxString &filename, const wxString &title,
4130 const wxString &datestamp)
4132 svxPrintDlg * p;
4133 p = new svxPrintDlg(m_Parent, filename, title, datestamp,
4134 m_PanAngle, m_TiltAngle,
4135 m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
4136 m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
4137 false);
4138 p->Show(true);
4141 static wxCursor
4142 make_cursor(const unsigned char * bits, const unsigned char * mask,
4143 int hotx, int hoty)
4145 #if defined __WXGTK__ && !defined __WXGTK3__
4146 // Use this code for GTK < 3 only - it doesn't work properly with GTK3
4147 // (reported and should be fixed in wxWidgets 3.0.4 and 3.1.1, see:
4148 // https://trac.wxwidgets.org/ticket/17916)
4149 return wxCursor((const char *)bits, 32, 32, hotx, hoty,
4150 (const char *)mask, wxBLACK, wxWHITE);
4151 #else
4152 # ifdef __WXMAC__
4153 // The default Mac cursor is black with a white edge, so
4154 // invert our custom cursors to match.
4155 char b[128];
4156 for (int i = 0; i < 128; ++i)
4157 b[i] = bits[i] ^ 0xff;
4158 # else
4159 const char * b = reinterpret_cast<const char *>(bits);
4160 # endif
4161 wxBitmap cursor_bitmap(b, 32, 32);
4162 wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
4163 cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
4164 wxImage cursor_image = cursor_bitmap.ConvertToImage();
4165 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
4166 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
4167 return wxCursor(cursor_image);
4168 #endif
4171 const
4172 #include "hand.xbm"
4173 const
4174 #include "handmask.xbm"
4176 const
4177 #include "brotate.xbm"
4178 const
4179 #include "brotatemask.xbm"
4181 const
4182 #include "vrotate.xbm"
4183 const
4184 #include "vrotatemask.xbm"
4186 const
4187 #include "rotate.xbm"
4188 const
4189 #include "rotatemask.xbm"
4191 const
4192 #include "rotatezoom.xbm"
4193 const
4194 #include "rotatezoommask.xbm"
4196 void
4197 GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
4199 // Check if we're already showing that cursor.
4200 if (current_cursor == new_cursor) return;
4202 current_cursor = new_cursor;
4203 switch (current_cursor) {
4204 case GfxCore::CURSOR_DEFAULT:
4205 GLACanvas::SetCursor(wxNullCursor);
4206 break;
4207 case GfxCore::CURSOR_POINTING_HAND:
4208 GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
4209 break;
4210 case GfxCore::CURSOR_DRAGGING_HAND:
4211 GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
4212 break;
4213 case GfxCore::CURSOR_HORIZONTAL_RESIZE:
4214 GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
4215 break;
4216 case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
4217 GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
4218 break;
4219 case GfxCore::CURSOR_ROTATE_VERTICALLY:
4220 GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
4221 break;
4222 case GfxCore::CURSOR_ROTATE_EITHER_WAY:
4223 GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
4224 break;
4225 case GfxCore::CURSOR_ZOOM:
4226 GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
4227 break;
4228 case GfxCore::CURSOR_ZOOM_ROTATE:
4229 GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
4230 break;
4234 bool GfxCore::MeasuringLineActive() const
4236 if (Animating()) return false;
4237 return HereIsReal() || m_there;
4240 bool GfxCore::HandleRClick(wxPoint point)
4242 if (PointWithinCompass(point)) {
4243 // Pop up menu.
4244 wxMenu menu;
4245 /* TRANSLATORS: View *looking* North */
4246 menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
4247 /* TRANSLATORS: View *looking* East */
4248 menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
4249 /* TRANSLATORS: View *looking* South */
4250 menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
4251 /* TRANSLATORS: View *looking* West */
4252 menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
4253 menu.AppendSeparator();
4254 /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
4255 menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
4256 /* TRANSLATORS: tickable menu item in View menu.
4258 * Degrees are the angular measurement where there are 360 in a full
4259 * circle. */
4260 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4261 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4262 PopupMenu(&menu);
4263 return true;
4266 if (PointWithinClino(point)) {
4267 // Pop up menu.
4268 wxMenu menu;
4269 menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
4270 menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
4271 menu.AppendSeparator();
4272 /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
4273 menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
4274 /* TRANSLATORS: tickable menu item in View menu.
4276 * Degrees are the angular measurement where there are 360 in a full
4277 * circle. */
4278 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4279 /* TRANSLATORS: tickable menu item in View menu.
4281 * Show the tilt of the survey as a percentage gradient (100% = 45
4282 * degrees = 50 grad). */
4283 menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
4284 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4285 PopupMenu(&menu);
4286 return true;
4289 if (PointWithinScaleBar(point)) {
4290 // Pop up menu.
4291 wxMenu menu;
4292 /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
4293 menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
4294 /* TRANSLATORS: tickable menu item in View menu.
4296 * "Metric" here means metres, km, etc (rather than feet, miles, etc)
4298 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4299 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4300 PopupMenu(&menu);
4301 return true;
4304 if (PointWithinColourKey(point)) {
4305 // Pop up menu.
4306 wxMenu menu;
4307 menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
4308 menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
4309 menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
4310 menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
4311 menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
4312 menu.AppendCheckItem(menu_COLOUR_BY_SURVEY, wmsg(/*Colour by &Survey*/448));
4313 menu.AppendSeparator();
4314 /* TRANSLATORS: Menu item which turns off the colour key.
4315 * The "Colour Key" is the thing in aven showing which colour
4316 * corresponds to which depth, date, survey closure error, etc. */
4317 menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
4318 if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
4319 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4320 else if (m_ColourBy == COLOUR_BY_GRADIENT)
4321 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4322 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4323 PopupMenu(&menu);
4324 return true;
4327 return false;
4330 void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
4332 if (centred) {
4333 p1.x = p2.x + (p1.x - p2.x) * 2;
4334 p1.y = p2.y + (p1.y - p2.y) * 2;
4336 if (aspect) {
4337 #if 0 // FIXME: This needs more work.
4338 int sx = GetXSize();
4339 int sy = GetYSize();
4340 int dx = p1.x - p2.x;
4341 int dy = p1.y - p2.y;
4342 int dy_new = dx * sy / sx;
4343 if (abs(dy_new) >= abs(dy)) {
4344 p1.y += (dy_new - dy) / 2;
4345 p2.y -= (dy_new - dy) / 2;
4346 } else {
4347 int dx_new = dy * sx / sy;
4348 p1.x += (dx_new - dx) / 2;
4349 p2.x -= (dx_new - dx) / 2;
4351 #endif
4353 zoombox.set(p1, p2);
4354 ForceRefresh();
4357 void GfxCore::ZoomBoxGo()
4359 if (!zoombox.active()) return;
4361 int width = GetXSize();
4362 int height = GetYSize();
4364 TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
4365 -0.5 * (zoombox.y1 + zoombox.y2 - height));
4366 int box_w = abs(zoombox.x1 - zoombox.x2);
4367 int box_h = abs(zoombox.y1 - zoombox.y2);
4369 double factor = min(double(width) / box_w, double(height) / box_h);
4371 zoombox.unset();
4373 SetScale(GetScale() * factor);