source: git/src/gfxcore.cc@ 1a46879

RELEASE/1.2 debug-ci debug-ci-sanitisers faster-cavernlog log-select main stereo stereo-2025 walls-data walls-data-hanging-as-warning warn-only-for-hanging-survey
Last change on this file since 1a46879 was 1a46879, checked in by Olly Betts <olly@…>, 8 years ago

Hook up multi-survey filtering more

Multiple --survey options in survexport now engage the filtering (a
single option is as before), which required splitting out a
SurveyFilter object from AvenTreeCtrl.

Factor out code to filter traverses into a function which wraps
operator++ on the traverse iterator.

  • Property mode set to 100644
File size: 113.5 KB
Line 
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.
14//
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.
19//
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
23//
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include <assert.h>
30#include <float.h>
31
32#include "aven.h"
33#include "aventreectrl.h"
34#include "date.h"
35#include "filename.h"
36#include "gfxcore.h"
37#include "mainfrm.h"
38#include "message.h"
39#include "useful.h"
40#include "printing.h"
41#include "guicontrol.h"
42#include "moviemaker.h"
43
44#include <wx/confbase.h>
45#include <wx/wfstream.h>
46#include <wx/image.h>
47#include <wx/zipstrm.h>
48
49#include <proj_api.h>
50
51const unsigned long DEFAULT_HGT_DIM = 3601;
52const unsigned long DEFAULT_HGT_SIZE = sqrd(DEFAULT_HGT_DIM) * 2;
53
54// Values for m_SwitchingTo
55#define PLAN 1
56#define ELEVATION 2
57#define NORTH 3
58#define EAST 4
59#define SOUTH 5
60#define WEST 6
61
62// Any error value higher than this is clamped to this.
63#define MAX_ERROR 12.0
64
65// Any length greater than pow(10, LOG_LEN_MAX) will be clamped to this.
66const Double LOG_LEN_MAX = 1.5;
67
68// How many bins per letter height to use when working out non-overlapping
69// labels.
70const unsigned int QUANTISE_FACTOR = 2;
71
72#include "avenpal.h"
73
74static const int INDICATOR_BOX_SIZE = 60;
75static const int INDICATOR_GAP = 2;
76static const int INDICATOR_MARGIN = 5;
77static const int INDICATOR_OFFSET_X = 15;
78static const int INDICATOR_OFFSET_Y = 15;
79static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
80static const int KEY_OFFSET_X = 10;
81static const int KEY_OFFSET_Y = 10;
82static const int KEY_EXTRA_LEFT_MARGIN = 2;
83static const int KEY_BLOCK_WIDTH = 20;
84static const int KEY_BLOCK_HEIGHT = 16;
85static const int TICK_LENGTH = 4;
86static const int SCALE_BAR_OFFSET_X = 15;
87static const int SCALE_BAR_OFFSET_Y = 12;
88static const int SCALE_BAR_HEIGHT = 12;
89
90static const gla_colour TEXT_COLOUR = col_GREEN;
91static const gla_colour HERE_COLOUR = col_WHITE;
92static const gla_colour NAME_COLOUR = col_GREEN;
93static const gla_colour SEL_COLOUR = col_WHITE;
94// Used with colour by date for legs without date information and with colour
95// by error for legs not in a loop.
96static const gla_colour NODATA_COLOUR = col_LIGHT_GREY_2;
97
98// Number of entries across and down the hit-test grid:
99#define HITTEST_SIZE 20
100
101// How close the pointer needs to be to a station to be considered:
102#define MEASURE_THRESHOLD 7
103
104// vector for lighting angle
105static const Vector3 light(.577, .577, .577);
106
107BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
108 EVT_PAINT(GfxCore::OnPaint)
109 EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
110 EVT_LEFT_UP(GfxCore::OnLButtonUp)
111 EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
112 EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
113 EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
114 EVT_RIGHT_UP(GfxCore::OnRButtonUp)
115 EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
116 EVT_MOTION(GfxCore::OnMouseMove)
117 EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
118 EVT_SIZE(GfxCore::OnSize)
119 EVT_IDLE(GfxCore::OnIdle)
120 EVT_CHAR(GfxCore::OnKeyPress)
121END_EVENT_TABLE()
122
123GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
124 GLACanvas(parent_win, 100),
125 m_Scale(0.0),
126 initial_scale(1.0),
127 m_ScaleBarWidth(0),
128 m_Control(control),
129 m_LabelGrid(NULL),
130 m_Parent(parent),
131 m_DoneFirstShow(false),
132 m_TiltAngle(0.0),
133 m_PanAngle(0.0),
134 m_Rotating(false),
135 m_RotationStep(0.0),
136 m_SwitchingTo(0),
137 m_Crosses(false),
138 m_Legs(true),
139 m_Splays(SHOW_FADED),
140 m_Dupes(SHOW_DASHED),
141 m_Names(false),
142 m_Scalebar(true),
143 m_ColourKey(true),
144 m_OverlappingNames(false),
145 m_Compass(true),
146 m_Clino(true),
147 m_Tubes(false),
148 m_ColourBy(COLOUR_BY_DEPTH),
149 m_HaveData(false),
150 m_HaveTerrain(true),
151 m_MouseOutsideCompass(false),
152 m_MouseOutsideElev(false),
153 m_Surface(false),
154 m_Entrances(false),
155 m_FixedPts(false),
156 m_ExportedPts(false),
157 m_Grid(false),
158 m_BoundingBox(false),
159 m_Terrain(false),
160 m_Degrees(false),
161 m_Metric(false),
162 m_Percent(false),
163 m_HitTestDebug(false),
164 m_RenderStats(false),
165 m_PointGrid(NULL),
166 m_HitTestGridValid(false),
167 m_here(NULL),
168 m_there(NULL),
169 presentation_mode(0),
170 pres_reverse(false),
171 pres_speed(0.0),
172 movie(NULL),
173 current_cursor(GfxCore::CURSOR_DEFAULT),
174 sqrd_measure_threshold(sqrd(MEASURE_THRESHOLD)),
175 dem(NULL),
176 last_time(0),
177 n_tris(0)
178{
179 AddQuad = &GfxCore::AddQuadrilateralDepth;
180 AddPoly = &GfxCore::AddPolylineDepth;
181 wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
182 wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
183 wxConfigBase::Get()->Read(wxT("percent"), &m_Percent, false);
184
185 for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
186 m_Pens[pen].SetColour(REDS[pen] / 255.0,
187 GREENS[pen] / 255.0,
188 BLUES[pen] / 255.0);
189 }
190
191 timer.Start();
192}
193
194GfxCore::~GfxCore()
195{
196 TryToFreeArrays();
197
198 delete[] m_PointGrid;
199}
200
201void GfxCore::TryToFreeArrays()
202{
203 // Free up any memory allocated for arrays.
204 delete[] m_LabelGrid;
205 m_LabelGrid = NULL;
206}
207
208//
209// Initialisation methods
210//
211
212void GfxCore::Initialise(bool same_file)
213{
214 // Initialise the view from the parent holding the survey data.
215
216 TryToFreeArrays();
217
218 m_DoneFirstShow = false;
219
220 m_HitTestGridValid = false;
221 m_here = NULL;
222 m_there = NULL;
223
224 m_MouseOutsideCompass = m_MouseOutsideElev = false;
225
226 if (!same_file) {
227 // Apply default parameters unless reloading the same file.
228 DefaultParameters();
229 }
230
231 m_HaveData = true;
232
233 // Clear any cached OpenGL lists which depend on the data.
234 InvalidateList(LIST_SCALE_BAR);
235 InvalidateList(LIST_DEPTH_KEY);
236 InvalidateList(LIST_DATE_KEY);
237 InvalidateList(LIST_ERROR_KEY);
238 InvalidateList(LIST_GRADIENT_KEY);
239 InvalidateList(LIST_LENGTH_KEY);
240 InvalidateList(LIST_UNDERGROUND_LEGS);
241 InvalidateList(LIST_TUBES);
242 InvalidateList(LIST_SURFACE_LEGS);
243 InvalidateList(LIST_BLOBS);
244 InvalidateList(LIST_CROSSES);
245 InvalidateList(LIST_GRID);
246 InvalidateList(LIST_SHADOW);
247 InvalidateList(LIST_TERRAIN);
248
249 // Set diameter of the viewing volume.
250 auto ext = m_Parent->GetExtent();
251 double cave_diameter = sqrt(sqrd(ext.GetX()) +
252 sqrd(ext.GetY()) +
253 sqrd(ext.GetZ()));
254
255 // Allow for terrain.
256 double diameter = max(1000.0 * 2, cave_diameter * 2);
257
258 if (!same_file) {
259 SetVolumeDiameter(diameter);
260
261 // Set initial scale based on the size of the cave.
262 initial_scale = diameter / cave_diameter;
263 SetScale(initial_scale);
264 } else {
265 // Adjust the position when restricting the view to a subsurvey (or
266 // expanding the view to show the whole survey).
267 AddTranslation(m_Parent->GetOffset() - offsets);
268
269 // Try to keep the same scale, allowing for the
270 // cave having grown (or shrunk).
271 double rescale = GetVolumeDiameter() / diameter;
272 SetVolumeDiameter(diameter);
273 SetScale(GetScale() / rescale); // ?
274 initial_scale = initial_scale * rescale;
275 }
276
277 offsets = m_Parent->GetOffset();
278
279 ForceRefresh();
280}
281
282void GfxCore::FirstShow()
283{
284 GLACanvas::FirstShow();
285
286 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
287 list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
288 while (pos != m_Parent->GetLabelsNCEnd()) {
289 LabelInfo* label = *pos++;
290 // Calculate and set the label width for use when plotting
291 // none-overlapping labels.
292 int ext_x;
293 GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
294 label->set_width(unsigned(ext_x) / quantise + 1);
295 }
296
297 m_DoneFirstShow = true;
298}
299
300//
301// Recalculating methods
302//
303
304void GfxCore::SetScale(Double scale)
305{
306 if (scale < 0.05) {
307 scale = 0.05;
308 } else if (scale > GetVolumeDiameter()) {
309 scale = GetVolumeDiameter();
310 }
311
312 m_Scale = scale;
313 m_HitTestGridValid = false;
314 if (m_here && m_here == &temp_here) SetHere();
315
316 GLACanvas::SetScale(scale);
317}
318
319bool GfxCore::HasUndergroundLegs() const
320{
321 return m_Parent->HasUndergroundLegs();
322}
323
324bool GfxCore::HasSplays() const
325{
326 return m_Parent->HasSplays();
327}
328
329bool GfxCore::HasDupes() const
330{
331 return m_Parent->HasDupes();
332}
333
334bool GfxCore::HasSurfaceLegs() const
335{
336 return m_Parent->HasSurfaceLegs();
337}
338
339bool GfxCore::HasTubes() const
340{
341 return m_Parent->HasTubes();
342}
343
344void GfxCore::UpdateBlobs()
345{
346 InvalidateList(LIST_BLOBS);
347}
348
349//
350// Event handlers
351//
352
353void GfxCore::OnLeaveWindow(wxMouseEvent&) {
354 SetHere();
355 ClearCoords();
356}
357
358void GfxCore::OnIdle(wxIdleEvent& event)
359{
360 // Handle an idle event.
361 if (Animating()) {
362 Animate();
363 // If still animating, we want more idle events.
364 if (Animating())
365 event.RequestMore();
366 } else {
367 // If we're idle, don't show a bogus FPS next time we render.
368 last_time = 0;
369 }
370}
371
372void GfxCore::OnPaint(wxPaintEvent&)
373{
374 // Redraw the window.
375
376 // Get a graphics context.
377 wxPaintDC dc(this);
378
379 if (m_HaveData) {
380 // Make sure we're initialised.
381 bool first_time = !m_DoneFirstShow;
382 if (first_time) {
383 FirstShow();
384 }
385
386 StartDrawing();
387
388 // Clear the background.
389 Clear();
390
391 // Set up model transformation matrix.
392 SetDataTransform();
393
394 if (m_Legs || m_Tubes) {
395 if (m_Tubes) {
396 EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
397 DrawList(LIST_TUBES);
398 DisableSmoothPolygons();
399 }
400
401 // Draw the underground legs. Do this last so that anti-aliasing
402 // works over polygons.
403 SetColour(col_GREEN);
404 DrawList(LIST_UNDERGROUND_LEGS);
405 }
406
407 if (m_Surface) {
408 // Draw the surface legs.
409 DrawList(LIST_SURFACE_LEGS);
410 }
411
412 if (m_BoundingBox) {
413 DrawShadowedBoundingBox();
414 }
415 if (m_Grid) {
416 // Draw the grid.
417 DrawList(LIST_GRID);
418 }
419
420 DrawList(LIST_BLOBS);
421
422 if (m_Crosses) {
423 DrawList(LIST_CROSSES);
424 }
425
426 if (m_Terrain) {
427 // Disable texturing while drawing terrain.
428 bool texturing = GetTextured();
429 if (texturing) GLACanvas::ToggleTextured();
430
431 // This is needed if blobs and/or crosses are drawn using lines -
432 // otherwise the terrain doesn't appear when they are enabled.
433 SetDataTransform();
434
435 // We don't want to be able to see the terrain through itself, so
436 // do a "Z-prepass" - plot the terrain once only updating the
437 // Z-buffer, then again with Z-clipping only plotting where the
438 // depth matches the value in the Z-buffer.
439 DrawListZPrepass(LIST_TERRAIN);
440
441 if (texturing) GLACanvas::ToggleTextured();
442 }
443
444 SetIndicatorTransform();
445
446 // Draw station names.
447 if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
448 SetColour(NAME_COLOUR);
449
450 if (m_OverlappingNames) {
451 SimpleDrawNames();
452 } else {
453 NattyDrawNames();
454 }
455 }
456
457 if (m_HitTestDebug) {
458 // Show the hit test grid bucket sizes...
459 SetColour(m_HitTestGridValid ? col_LIGHT_GREY : col_DARK_GREY);
460 if (m_PointGrid) {
461 for (int i = 0; i != HITTEST_SIZE; ++i) {
462 int x = (GetXSize() + 1) * i / HITTEST_SIZE + 2;
463 for (int j = 0; j != HITTEST_SIZE; ++j) {
464 int square = i + j * HITTEST_SIZE;
465 unsigned long bucket_size = m_PointGrid[square].size();
466 if (bucket_size) {
467 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
468 DrawIndicatorText(x, y, wxString::Format(wxT("%lu"), bucket_size));
469 }
470 }
471 }
472 }
473
474 EnableDashedLines();
475 BeginLines();
476 for (int i = 0; i != HITTEST_SIZE; ++i) {
477 int x = (GetXSize() + 1) * i / HITTEST_SIZE;
478 PlaceIndicatorVertex(x, 0);
479 PlaceIndicatorVertex(x, GetYSize());
480 }
481 for (int j = 0; j != HITTEST_SIZE; ++j) {
482 int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
483 PlaceIndicatorVertex(0, y);
484 PlaceIndicatorVertex(GetXSize(), y);
485 }
486 EndLines();
487 DisableDashedLines();
488 }
489
490 long now = timer.Time();
491 if (m_RenderStats) {
492 // Show stats about rendering.
493 SetColour(col_TURQUOISE);
494 int y = GetYSize() - GetFontSize();
495 if (last_time != 0.0) {
496 // timer.Time() measure in milliseconds.
497 double fps = 1000.0 / (now - last_time);
498 DrawIndicatorText(1, y, wxString::Format(wxT("FPS:% 5.1f"), fps));
499 }
500 y -= GetFontSize();
501 DrawIndicatorText(1, y, wxString::Format(wxT("▲:%lu"), (unsigned long)n_tris));
502 }
503 last_time = now;
504
505 // Draw indicators.
506 //
507 // There's no advantage in generating an OpenGL list for the
508 // indicators since they change with almost every redraw (and
509 // sometimes several times between redraws). This way we avoid
510 // the need to track when to update the indicator OpenGL list,
511 // and also avoid indicator update bugs when we don't quite get this
512 // right...
513 DrawIndicators();
514
515 if (zoombox.active()) {
516 SetColour(SEL_COLOUR);
517 EnableDashedLines();
518 BeginPolyline();
519 glaCoord Y = GetYSize();
520 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
521 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y2);
522 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y2);
523 PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y1);
524 PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
525 EndPolyline();
526 DisableDashedLines();
527 } else if (MeasuringLineActive()) {
528 // Draw "here" and "there".
529 double hx, hy;
530 SetColour(HERE_COLOUR);
531 if (m_here) {
532 double dummy;
533 Transform(*m_here, &hx, &hy, &dummy);
534 if (m_here != &temp_here) DrawRing(hx, hy);
535 }
536 if (m_there) {
537 double tx, ty;
538 double dummy;
539 Transform(*m_there, &tx, &ty, &dummy);
540 if (m_here) {
541 BeginLines();
542 PlaceIndicatorVertex(hx, hy);
543 PlaceIndicatorVertex(tx, ty);
544 EndLines();
545 }
546 BeginBlobs();
547 DrawBlob(tx, ty);
548 EndBlobs();
549 }
550 }
551
552 FinishDrawing();
553 } else {
554 dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
555 dc.Clear();
556 }
557}
558
559void GfxCore::DrawBoundingBox()
560{
561 const Vector3 v = 0.5 * m_Parent->GetExtent();
562
563 SetColour(col_BLUE);
564 EnableDashedLines();
565 BeginPolyline();
566 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
567 PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
568 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
569 PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
570 PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
571 EndPolyline();
572 BeginPolyline();
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 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
577 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
578 EndPolyline();
579 BeginLines();
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 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
584 PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
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 EndLines();
589 DisableDashedLines();
590}
591
592void GfxCore::DrawShadowedBoundingBox()
593{
594 const Vector3 v = 0.5 * m_Parent->GetExtent();
595
596 DrawBoundingBox();
597
598 PolygonOffset(true);
599 SetColour(col_DARK_GREY);
600 BeginQuadrilaterals();
601 PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
602 PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
603 PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
604 PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
605 EndQuadrilaterals();
606 PolygonOffset(false);
607
608 DrawList(LIST_SHADOW);
609}
610
611void GfxCore::DrawGrid()
612{
613 // Draw the grid.
614 SetColour(col_RED);
615
616 // Calculate the extent of the survey, in metres across the screen plane.
617 Double m_across_screen = SurveyUnitsAcrossViewport();
618 // Calculate the length of the scale bar in metres.
619 //--move this elsewhere
620 Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
621 Double t = m_across_screen * 0.75 / size_snap;
622 if (t >= 5.0) {
623 size_snap *= 5.0;
624 }
625 else if (t >= 2.0) {
626 size_snap *= 2.0;
627 }
628
629 Double grid_size = size_snap * 0.1;
630 Double edge = grid_size * 2.0;
631 auto ext = m_Parent->GetExtent();
632 Double grid_z = -ext.GetZ() * 0.5 - grid_size;
633 Double left = -ext.GetX() * 0.5 - edge;
634 Double right = ext.GetX() * 0.5 + edge;
635 Double bottom = -ext.GetY() * 0.5 - edge;
636 Double top = ext.GetY() * 0.5 + edge;
637 int count_x = (int) ceil((right - left) / grid_size);
638 int count_y = (int) ceil((top - bottom) / grid_size);
639 Double actual_right = left + count_x*grid_size;
640 Double actual_top = bottom + count_y*grid_size;
641
642 BeginLines();
643
644 for (int xc = 0; xc <= count_x; xc++) {
645 Double x = left + xc*grid_size;
646
647 PlaceVertex(x, bottom, grid_z);
648 PlaceVertex(x, actual_top, grid_z);
649 }
650
651 for (int yc = 0; yc <= count_y; yc++) {
652 Double y = bottom + yc*grid_size;
653 PlaceVertex(left, y, grid_z);
654 PlaceVertex(actual_right, y, grid_z);
655 }
656
657 EndLines();
658}
659
660int GfxCore::GetClinoOffset() const
661{
662 int result = INDICATOR_OFFSET_X;
663 if (m_Compass) {
664 result += 6 + GetCompassWidth() + INDICATOR_GAP;
665 }
666 return result;
667}
668
669void GfxCore::DrawTick(int angle_cw)
670{
671 const Double theta = rad(angle_cw);
672 const wxCoord length1 = INDICATOR_RADIUS;
673 const wxCoord length0 = length1 + TICK_LENGTH;
674 wxCoord x0 = wxCoord(length0 * sin(theta));
675 wxCoord y0 = wxCoord(length0 * cos(theta));
676 wxCoord x1 = wxCoord(length1 * sin(theta));
677 wxCoord y1 = wxCoord(length1 * cos(theta));
678
679 PlaceIndicatorVertex(x0, y0);
680 PlaceIndicatorVertex(x1, y1);
681}
682
683void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
684 Vector3 p1(0, INDICATOR_RADIUS, 0);
685 Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
686 Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
687 Vector3 pc(0, 0, 0);
688
689 DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
690 DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
691}
692
693void GfxCore::DrawCompass() {
694 // Ticks.
695 BeginLines();
696 for (int angle = 315; angle > 0; angle -= 45) {
697 DrawTick(angle);
698 }
699 SetColour(col_GREEN);
700 DrawTick(0);
701 EndLines();
702
703 // Compass background.
704 DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
705
706 // Compass arrow.
707 DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
708}
709
710// Draw the non-rotating background to the clino.
711void GfxCore::DrawClinoBack() {
712 BeginLines();
713 for (int angle = 0; angle <= 180; angle += 90) {
714 DrawTick(angle);
715 }
716
717 SetColour(col_GREY);
718 PlaceIndicatorVertex(0, INDICATOR_RADIUS);
719 PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
720 PlaceIndicatorVertex(0, 0);
721 PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
722
723 EndLines();
724}
725
726void GfxCore::DrawClino() {
727 // Ticks.
728 SetColour(col_GREEN);
729 BeginLines();
730 DrawTick(0);
731 EndLines();
732
733 // Clino background.
734 DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
735
736 // Elevation arrow.
737 DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
738}
739
740void GfxCore::Draw2dIndicators()
741{
742 // Draw the compass and elevation indicators.
743
744 const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
745
746 const int comp_centre_x = GetCompassXPosition();
747
748 if (m_Compass && !m_Parent->IsExtendedElevation()) {
749 // If the user is dragging the compass with the pointer outside the
750 // compass, we snap to 45 degree multiples, and the ticks go white.
751 SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
752 DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
753 }
754
755 const int elev_centre_x = GetClinoXPosition();
756
757 if (m_Clino) {
758 // If the user is dragging the clino with the pointer outside the
759 // clino, we snap to 90 degree multiples, and the ticks go white.
760 SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
761 DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
762 DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
763 }
764
765 SetColour(TEXT_COLOUR);
766
767 static int triple_zero_width = 0;
768 static int height = 0;
769 if (!triple_zero_width) {
770 GetTextExtent(wxT("000"), &triple_zero_width, &height);
771 }
772 const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
773
774 if (m_Compass && !m_Parent->IsExtendedElevation()) {
775 wxString str;
776 int value;
777 int brg_unit;
778 if (m_Degrees) {
779 value = int(m_PanAngle);
780 /* TRANSLATORS: degree symbol - probably should be translated to
781 * itself. */
782 brg_unit = /*°*/344;
783 } else {
784 value = int(m_PanAngle * 200.0 / 180.0);
785 /* TRANSLATORS: symbol for grad (400 grad = 360 degrees = full
786 * circle). */
787 brg_unit = /*ᵍ*/345;
788 }
789 str.Printf(wxT("%03d"), value);
790 str += wmsg(brg_unit);
791 DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
792
793 // TRANSLATORS: Used in aven above the compass indicator at the lower
794 // right of the display, with a bearing below "Facing". This indicates the
795 // direction the viewer is "facing" in.
796 //
797 // Try to keep this translation short - ideally at most 10 characters -
798 // as otherwise the compass and clino will be moved further apart to
799 // make room. */
800 str = wmsg(/*Facing*/203);
801 int w;
802 GetTextExtent(str, &w, NULL);
803 DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
804 }
805
806 if (m_Clino) {
807 if (m_TiltAngle == -90.0) {
808 // TRANSLATORS: Label used for "clino" in Aven when the view is
809 // from directly above.
810 //
811 // Try to keep this translation short - ideally at most 10
812 // characters - as otherwise the compass and clino will be moved
813 // further apart to make room. */
814 wxString str = wmsg(/*Plan*/432);
815 static int width = 0;
816 if (!width) {
817 GetTextExtent(str, &width, NULL);
818 }
819 int x = elev_centre_x - width / 2;
820 DrawIndicatorText(x, y_off + height / 2, str);
821 } else if (m_TiltAngle == 90.0) {
822 // TRANSLATORS: Label used for "clino" in Aven when the view is
823 // from directly below.
824 //
825 // Try to keep this translation short - ideally at most 10
826 // characters - as otherwise the compass and clino will be moved
827 // further apart to make room. */
828 wxString str = wmsg(/*Kiwi Plan*/433);
829 static int width = 0;
830 if (!width) {
831 GetTextExtent(str, &width, NULL);
832 }
833 int x = elev_centre_x - width / 2;
834 DrawIndicatorText(x, y_off + height / 2, str);
835 } else {
836 int angle;
837 wxString str;
838 int width;
839 int unit;
840 if (m_Percent) {
841 static int zero_width = 0;
842 if (!zero_width) {
843 GetTextExtent(wxT("0"), &zero_width, NULL);
844 }
845 width = zero_width;
846 if (m_TiltAngle > 89.99) {
847 angle = 1000000;
848 } else if (m_TiltAngle < -89.99) {
849 angle = -1000000;
850 } else {
851 angle = int(100 * tan(rad(m_TiltAngle)));
852 }
853 if (angle > 99999 || angle < -99999) {
854 str = angle > 0 ? wxT("+") : wxT("-");
855 /* TRANSLATORS: infinity symbol - used for the percentage gradient on
856 * vertical angles. */
857 str += wmsg(/*∞*/431);
858 } else {
859 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("0");
860 }
861 /* TRANSLATORS: symbol for percentage gradient (100% = 45
862 * degrees = 50 grad). */
863 unit = /*%*/96;
864 } else if (m_Degrees) {
865 static int zero_zero_width = 0;
866 if (!zero_zero_width) {
867 GetTextExtent(wxT("00"), &zero_zero_width, NULL);
868 }
869 width = zero_zero_width;
870 angle = int(m_TiltAngle);
871 str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
872 unit = /*°*/344;
873 } else {
874 width = triple_zero_width;
875 angle = int(m_TiltAngle * 200.0 / 180.0);
876 str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
877 unit = /*ᵍ*/345;
878 }
879
880 int sign_offset = 0;
881 if (unit == /*%*/96) {
882 // Right align % since the width changes so much.
883 GetTextExtent(str, &sign_offset, NULL);
884 sign_offset -= width;
885 } else if (angle < 0) {
886 // Adjust horizontal position so the left of the first digit is
887 // always in the same place.
888 static int minus_width = 0;
889 if (!minus_width) {
890 GetTextExtent(wxT("-"), &minus_width, NULL);
891 }
892 sign_offset = minus_width;
893 } else if (angle > 0) {
894 // Adjust horizontal position so the left of the first digit is
895 // always in the same place.
896 static int plus_width = 0;
897 if (!plus_width) {
898 GetTextExtent(wxT("+"), &plus_width, NULL);
899 }
900 sign_offset = plus_width;
901 }
902
903 str += wmsg(unit);
904 DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
905
906 // TRANSLATORS: Label used for "clino" in Aven when the view is
907 // neither from directly above nor from directly below. It is
908 // also used in the dialog for editing a marked position in a
909 // presentation.
910 //
911 // Try to keep this translation short - ideally at most 10
912 // characters - as otherwise the compass and clino will be moved
913 // further apart to make room. */
914 str = wmsg(/*Elevation*/118);
915 static int elevation_width = 0;
916 if (!elevation_width) {
917 GetTextExtent(str, &elevation_width, NULL);
918 }
919 int x = elev_centre_x - elevation_width / 2;
920 DrawIndicatorText(x, y_off + height, str);
921 }
922 }
923}
924
925void GfxCore::NattyDrawNames()
926{
927 // Draw station names, without overlapping.
928
929 const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
930 const unsigned int quantised_x = GetXSize() / quantise;
931 const unsigned int quantised_y = GetYSize() / quantise;
932 const size_t buffer_size = quantised_x * quantised_y;
933
934 if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
935
936 memset((void*) m_LabelGrid, 0, buffer_size);
937
938 const SurveyFilter* filter = m_Parent->GetTreeFilter();
939 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
940 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
941 if (!((m_Surface && (*label)->IsSurface()) ||
942 (m_Legs && (*label)->IsUnderground()) ||
943 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
944 // if this station isn't to be displayed, skip to the next
945 // (last case is for stns with no legs attached)
946 continue;
947 }
948 if (filter && !filter->CheckVisible((*label)->GetText()))
949 continue;
950
951 double x, y, z;
952
953 Transform(**label, &x, &y, &z);
954 // Check if the label is behind us (in perspective view).
955 if (z <= 0.0 || z >= 1.0) continue;
956
957 // Apply a small shift so that translating the view doesn't make which
958 // labels are displayed change as the resulting twinkling effect is
959 // distracting.
960 double tx, ty, tz;
961 Transform(Vector3(), &tx, &ty, &tz);
962 tx -= floor(tx / quantise) * quantise;
963 ty -= floor(ty / quantise) * quantise;
964
965 tx = x - tx;
966 if (tx < 0) continue;
967
968 ty = y - ty;
969 if (ty < 0) continue;
970
971 unsigned int iy = unsigned(ty) / quantise;
972 if (iy >= quantised_y) continue;
973 unsigned int width = (*label)->get_width();
974 unsigned int ix = unsigned(tx) / quantise;
975 if (ix + width >= quantised_x) continue;
976
977 char * test = m_LabelGrid + ix + iy * quantised_x;
978 if (memchr(test, 1, width)) continue;
979
980 x += 3;
981 y -= GetFontSize() / 2;
982 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
983
984 if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
985 test -= quantised_x * iy;
986 iy += 4;
987 while (--iy && test < m_LabelGrid + buffer_size) {
988 memset(test, 1, width);
989 test += quantised_x;
990 }
991 }
992}
993
994void GfxCore::SimpleDrawNames()
995{
996 const SurveyFilter* filter = m_Parent->GetTreeFilter();
997 // Draw all station names, without worrying about overlaps
998 list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
999 for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
1000 if (!((m_Surface && (*label)->IsSurface()) ||
1001 (m_Legs && (*label)->IsUnderground()) ||
1002 (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
1003 // if this station isn't to be displayed, skip to the next
1004 // (last case is for stns with no legs attached)
1005 continue;
1006 }
1007 if (filter && !filter->CheckVisible((*label)->GetText()))
1008 continue;
1009
1010 double x, y, z;
1011 Transform(**label, &x, &y, &z);
1012
1013 // Check if the label is behind us (in perspective view).
1014 if (z <= 0) continue;
1015
1016 x += 3;
1017 y -= GetFontSize() / 2;
1018 DrawIndicatorText((int)x, (int)y, (*label)->GetText());
1019 }
1020}
1021
1022void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
1023{
1024 int total_block_height =
1025 KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
1026 if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
1027 if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
1028
1029 const int bottom = -total_block_height;
1030
1031 int size = 0;
1032 if (!other.empty()) GetTextExtent(other, &size, NULL);
1033 int band;
1034 for (band = 0; band < num_bands; ++band) {
1035 int x;
1036 GetTextExtent(key_legends[band], &x, NULL);
1037 if (x > size) size = x;
1038 }
1039
1040 int left = -KEY_BLOCK_WIDTH - size;
1041
1042 key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
1043 key_lowerleft[m_ColourBy].y = bottom;
1044
1045 int y = bottom;
1046 if (!units.empty()) y += KEY_BLOCK_HEIGHT;
1047
1048 if (!other.empty()) {
1049 DrawRectangle(NODATA_COLOUR, col_BLACK,
1050 left, y,
1051 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1052 y += KEY_BLOCK_HEIGHT * 2;
1053 }
1054
1055 int start = y;
1056 if (num_bands == 1) {
1057 DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
1058 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1059 y += KEY_BLOCK_HEIGHT;
1060 } else {
1061 for (band = 0; band < num_bands - 1; ++band) {
1062 DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
1063 KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1064 y += KEY_BLOCK_HEIGHT;
1065 }
1066 }
1067
1068 SetColour(col_BLACK);
1069 BeginPolyline();
1070 PlaceIndicatorVertex(left, y);
1071 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1072 PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
1073 PlaceIndicatorVertex(left, start);
1074 PlaceIndicatorVertex(left, y);
1075 EndPolyline();
1076
1077 SetColour(TEXT_COLOUR);
1078
1079 y = bottom;
1080 if (!units.empty()) {
1081 GetTextExtent(units, &size, NULL);
1082 DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
1083 y += KEY_BLOCK_HEIGHT;
1084 }
1085 y -= GetFontSize() / 2;
1086 left += KEY_BLOCK_WIDTH + 5;
1087
1088 if (!other.empty()) {
1089 y += KEY_BLOCK_HEIGHT / 2;
1090 DrawIndicatorText(left, y, other);
1091 y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
1092 }
1093
1094 if (num_bands == 1) {
1095 y += KEY_BLOCK_HEIGHT / 2;
1096 DrawIndicatorText(left, y, key_legends[0]);
1097 } else {
1098 for (band = 0; band < num_bands; ++band) {
1099 DrawIndicatorText(left, y, key_legends[band]);
1100 y += KEY_BLOCK_HEIGHT;
1101 }
1102 }
1103}
1104
1105void GfxCore::DrawDepthKey()
1106{
1107 Double z_ext = m_Parent->GetDepthExtent();
1108 int num_bands = 1;
1109 int sf = 0;
1110 if (z_ext > 0.0) {
1111 num_bands = GetNumColourBands();
1112 Double z_range = z_ext;
1113 if (!m_Metric) z_range /= METRES_PER_FOOT;
1114 sf = max(0, 1 - (int)floor(log10(z_range)));
1115 }
1116
1117 Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
1118 for (int band = 0; band < num_bands; ++band) {
1119 Double z = z_min;
1120 if (band)
1121 z += z_ext * band / (num_bands - 1);
1122
1123 if (!m_Metric)
1124 z /= METRES_PER_FOOT;
1125
1126 key_legends[band].Printf(wxT("%.*f"), sf, z);
1127 }
1128
1129 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1130}
1131
1132void GfxCore::DrawDateKey()
1133{
1134 int num_bands;
1135 if (!HasDateInformation()) {
1136 num_bands = 0;
1137 } else {
1138 int date_ext = m_Parent->GetDateExtent();
1139 if (date_ext == 0) {
1140 num_bands = 1;
1141 } else {
1142 num_bands = GetNumColourBands();
1143 }
1144 for (int band = 0; band < num_bands; ++band) {
1145 int y, m, d;
1146 int days = m_Parent->GetDateMin();
1147 if (band)
1148 days += date_ext * band / (num_bands - 1);
1149 ymd_from_days_since_1900(days, &y, &m, &d);
1150 key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
1151 }
1152 }
1153
1154 wxString other;
1155 if (!m_Parent->HasCompleteDateInfo()) {
1156 /* TRANSLATORS: Used in the "colour key" for "colour by date" if there
1157 * are surveys without date information. Try to keep this fairly short.
1158 */
1159 other = wmsg(/*Undated*/221);
1160 }
1161
1162 DrawColourKey(num_bands, other, wxString());
1163}
1164
1165void GfxCore::DrawErrorKey()
1166{
1167 int num_bands;
1168 if (HasErrorInformation()) {
1169 // Use fixed colours for each error factor so it's directly visually
1170 // comparable between surveys.
1171 num_bands = GetNumColourBands();
1172 for (int band = 0; band < num_bands; ++band) {
1173 double E = MAX_ERROR * band / (num_bands - 1);
1174 key_legends[band].Printf(wxT("%.2f"), E);
1175 }
1176 } else {
1177 num_bands = 0;
1178 }
1179
1180 // Always show the "Not in loop" legend for now (FIXME).
1181 /* TRANSLATORS: Used in the "colour key" for "colour by error" for surveys
1182 * which aren’t part of a loop and so have no error information. Try to keep
1183 * this fairly short. */
1184 DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
1185}
1186
1187void GfxCore::DrawGradientKey()
1188{
1189 int num_bands;
1190 // Use fixed colours for each gradient so it's directly visually comparable
1191 // between surveys.
1192 num_bands = GetNumColourBands();
1193 wxString units = wmsg(m_Degrees ? /*°*/344 : /*ᵍ*/345);
1194 for (int band = 0; band < num_bands; ++band) {
1195 double gradient = double(band) / (num_bands - 1);
1196 if (m_Degrees) {
1197 gradient *= 90.0;
1198 } else {
1199 gradient *= 100.0;
1200 }
1201 key_legends[band].Printf(wxT("%.f%s"), gradient, units);
1202 }
1203
1204 DrawColourKey(num_bands, wxString(), wxString());
1205}
1206
1207void GfxCore::DrawLengthKey()
1208{
1209 int num_bands;
1210 // Use fixed colours for each length so it's directly visually comparable
1211 // between surveys.
1212 num_bands = GetNumColourBands();
1213 for (int band = 0; band < num_bands; ++band) {
1214 double len = pow(10, LOG_LEN_MAX * band / (num_bands - 1));
1215 if (!m_Metric) {
1216 len /= METRES_PER_FOOT;
1217 }
1218 key_legends[band].Printf(wxT("%.1f"), len);
1219 }
1220
1221 DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1222}
1223
1224void GfxCore::DrawScaleBar()
1225{
1226 // Calculate how many metres of survey are currently displayed across the
1227 // screen.
1228 Double across_screen = SurveyUnitsAcrossViewport();
1229
1230 double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
1231 if (f > 0.75) {
1232 f = 0.75;
1233 } else if (f < 0.5) {
1234 // Stop it getting squeezed to nothing.
1235 // FIXME: In this case we should probably move the compass and clino up
1236 // to make room rather than letting stuff overlap.
1237 f = 0.5;
1238 }
1239
1240 // Convert to imperial measurements if required.
1241 Double multiplier = 1.0;
1242 if (!m_Metric) {
1243 across_screen /= METRES_PER_FOOT;
1244 multiplier = METRES_PER_FOOT;
1245 if (across_screen >= 5280.0 / f) {
1246 across_screen /= 5280.0;
1247 multiplier *= 5280.0;
1248 }
1249 }
1250
1251 // Calculate the length of the scale bar.
1252 Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1253 Double t = across_screen * f / size_snap;
1254 if (t >= 5.0) {
1255 size_snap *= 5.0;
1256 } else if (t >= 2.0) {
1257 size_snap *= 2.0;
1258 }
1259
1260 if (!m_Metric) size_snap *= multiplier;
1261
1262 // Actual size of the thing in pixels:
1263 int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1264 m_ScaleBarWidth = size;
1265
1266 // Draw it...
1267 const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1268 int interval = size / 10;
1269
1270 gla_colour col = col_WHITE;
1271 for (int ix = 0; ix < 10; ix++) {
1272 int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1273
1274 DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1275
1276 col = (col == col_WHITE) ? col_GREY : col_WHITE;
1277 }
1278
1279 // Add labels.
1280 wxString str;
1281 int units;
1282 if (m_Metric) {
1283 Double km = size_snap * 1e-3;
1284 if (km >= 1.0) {
1285 size_snap = km;
1286 /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1287 * used e.g. "5km".
1288 *
1289 * If there should be a space between the number and this, include
1290 * one in the translation. */
1291 units = /*km*/423;
1292 } else if (size_snap >= 1.0) {
1293 /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1294 * e.g. "10m".
1295 *
1296 * If there should be a space between the number and this, include
1297 * one in the translation. */
1298 units = /*m*/424;
1299 } else {
1300 size_snap *= 1e2;
1301 /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1302 * used e.g. "50cm".
1303 *
1304 * If there should be a space between the number and this, include
1305 * one in the translation. */
1306 units = /*cm*/425;
1307 }
1308 } else {
1309 size_snap /= METRES_PER_FOOT;
1310 Double miles = size_snap / 5280.0;
1311 if (miles >= 1.0) {
1312 size_snap = miles;
1313 if (size_snap >= 2.0) {
1314 /* TRANSLATORS: abbreviation for "miles" (unit of length,
1315 * plural), used e.g. "2 miles".
1316 *
1317 * If there should be a space between the number and this,
1318 * include one in the translation. */
1319 units = /* miles*/426;
1320 } else {
1321 /* TRANSLATORS: abbreviation for "mile" (unit of length,
1322 * singular), used e.g. "1 mile".
1323 *
1324 * If there should be a space between the number and this,
1325 * include one in the translation. */
1326 units = /* mile*/427;
1327 }
1328 } else if (size_snap >= 1.0) {
1329 /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1330 * as "10ft".
1331 *
1332 * If there should be a space between the number and this, include
1333 * one in the translation. */
1334 units = /*ft*/428;
1335 } else {
1336 size_snap *= 12.0;
1337 /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1338 * e.g. as "6in".
1339 *
1340 * If there should be a space between the number and this, include
1341 * one in the translation. */
1342 units = /*in*/429;
1343 }
1344 }
1345 if (size_snap >= 1.0) {
1346 str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1347 } else {
1348 int sf = -(int)floor(log10(size_snap));
1349 str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1350 }
1351
1352 int text_width, text_height;
1353 GetTextExtent(str, &text_width, &text_height);
1354 const int text_y = end_y - text_height + 1;
1355 SetColour(TEXT_COLOUR);
1356 DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1357 DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1358}
1359
1360bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1361{
1362 if (Animating()) return false;
1363
1364 if (point.x < 0 || point.x >= GetXSize() ||
1365 point.y < 0 || point.y >= GetYSize()) {
1366 return false;
1367 }
1368
1369 SetDataTransform();
1370
1371 if (!m_HitTestGridValid) CreateHitTestGrid();
1372
1373 int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1374 int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
1375
1376 LabelInfo *best = NULL;
1377 int dist_sqrd = sqrd_measure_threshold;
1378 int square = grid_x + grid_y * HITTEST_SIZE;
1379 list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1380
1381 while (iter != m_PointGrid[square].end()) {
1382 LabelInfo *pt = *iter++;
1383
1384 double cx, cy, cz;
1385
1386 Transform(*pt, &cx, &cy, &cz);
1387
1388 cy = GetYSize() - cy;
1389
1390 int dx = point.x - int(cx);
1391 int ds = dx * dx;
1392 if (ds >= dist_sqrd) continue;
1393 int dy = point.y - int(cy);
1394
1395 ds += dy * dy;
1396 if (ds >= dist_sqrd) continue;
1397
1398 dist_sqrd = ds;
1399 best = pt;
1400
1401 if (ds == 0) break;
1402 }
1403
1404 if (best) {
1405 m_Parent->ShowInfo(best, m_there);
1406 if (centre) {
1407 // FIXME: allow Ctrl-Click to not set there or something?
1408 CentreOn(*best);
1409 WarpPointer(GetXSize() / 2, GetYSize() / 2);
1410 SetThere(best);
1411 m_Parent->SelectTreeItem(best);
1412 }
1413 } else {
1414 // Left-clicking not on a survey cancels the measuring line.
1415 if (centre) {
1416 ClearTreeSelection();
1417 } else {
1418 m_Parent->ShowInfo(best, m_there);
1419 double x, y, z;
1420 ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1421 temp_here.assign(Vector3(x, y, z));
1422 SetHere(&temp_here);
1423 }
1424 }
1425
1426 return best;
1427}
1428
1429void GfxCore::OnSize(wxSizeEvent& event)
1430{
1431 // Handle a change in window size.
1432 wxSize size = event.GetSize();
1433
1434 if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1435 // Before things are fully initialised, we sometimes get a bogus
1436 // resize message...
1437 // FIXME have changes in MainFrm cured this? It still happens with
1438 // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1439 // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1440 // is resized such that the GfxCore window isn't visible.
1441 //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1442 return;
1443 }
1444
1445 event.Skip();
1446
1447 if (m_DoneFirstShow) {
1448 TryToFreeArrays();
1449
1450 m_HitTestGridValid = false;
1451
1452 ForceRefresh();
1453 }
1454}
1455
1456void GfxCore::DefaultParameters()
1457{
1458 // Set default viewing parameters.
1459
1460 m_Surface = false;
1461 if (!m_Parent->HasUndergroundLegs()) {
1462 if (m_Parent->HasSurfaceLegs()) {
1463 // If there are surface legs, but no underground legs, turn
1464 // surface surveys on.
1465 m_Surface = true;
1466 } else {
1467 // If there are no legs (e.g. after loading a .pos file), turn
1468 // crosses on.
1469 m_Crosses = true;
1470 }
1471 }
1472
1473 m_PanAngle = 0.0;
1474 if (m_Parent->IsExtendedElevation()) {
1475 m_TiltAngle = 0.0;
1476 } else {
1477 m_TiltAngle = -90.0;
1478 }
1479
1480 SetRotation(m_PanAngle, m_TiltAngle);
1481 SetTranslation(Vector3());
1482
1483 m_RotationStep = 30.0;
1484 m_Rotating = false;
1485 m_SwitchingTo = 0;
1486 m_Entrances = false;
1487 m_FixedPts = false;
1488 m_ExportedPts = false;
1489 m_Grid = false;
1490 m_BoundingBox = false;
1491 m_Tubes = false;
1492 if (GetPerspective()) TogglePerspective();
1493
1494 // Set the initial scale.
1495 SetScale(initial_scale);
1496}
1497
1498void GfxCore::Defaults()
1499{
1500 // Restore default scale, rotation and translation parameters.
1501 DefaultParameters();
1502
1503 // Invalidate all the cached lists.
1504 GLACanvas::FirstShow();
1505
1506 ForceRefresh();
1507}
1508
1509void GfxCore::Animate()
1510{
1511 // Don't show pointer coordinates while animating.
1512 // FIXME : only do this when we *START* animating! Use a static copy
1513 // of the value of "Animating()" last time we were here to track this?
1514 // MainFrm now checks if we're trying to clear already cleared labels
1515 // and just returns, but it might be simpler to check here!
1516 ClearCoords();
1517 m_Parent->ShowInfo();
1518
1519 long t;
1520 if (movie) {
1521 ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1522 if (!movie->AddFrame()) {
1523 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1524 delete movie;
1525 movie = NULL;
1526 presentation_mode = 0;
1527 return;
1528 }
1529 t = 1000 / 25; // 25 frames per second
1530 } else {
1531 static long t_prev = 0;
1532 t = timer.Time();
1533 // Avoid redrawing twice in the same frame.
1534 long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1535 if (delta_t < 1000 / MAX_FRAMERATE)
1536 return;
1537 t_prev = t;
1538 if (presentation_mode == PLAYING && pres_speed != 0.0)
1539 t = delta_t;
1540 }
1541
1542 if (presentation_mode == PLAYING && pres_speed != 0.0) {
1543 // FIXME: It would probably be better to work relative to the time we
1544 // passed the last mark, but that's complicated by the speed
1545 // potentially changing (or even the direction of playback reversing)
1546 // at any point during playback.
1547 Double tick = t * 0.001 * fabs(pres_speed);
1548 while (tick >= next_mark_time) {
1549 tick -= next_mark_time;
1550 this_mark_total = 0;
1551 PresentationMark prev_mark = next_mark;
1552 if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1553 else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1554 if (pres_reverse)
1555 next_mark = m_Parent->GetPresMark(MARK_PREV);
1556 else
1557 next_mark = m_Parent->GetPresMark(MARK_NEXT);
1558 if (!next_mark.is_valid()) {
1559 SetView(prev_mark);
1560 presentation_mode = 0;
1561 if (movie && !movie->Close()) {
1562 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1563 }
1564 delete movie;
1565 movie = NULL;
1566 break;
1567 }
1568
1569 double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1570 if (tmp > 0) {
1571 next_mark_time = tmp;
1572 } else {
1573 double d = (next_mark - prev_mark).magnitude();
1574 // FIXME: should ignore component of d which is unseen in
1575 // non-perspective mode?
1576 next_mark_time = sqrd(d / 30.0);
1577 double a = next_mark.angle - prev_mark.angle;
1578 if (a > 180.0) {
1579 next_mark.angle -= 360.0;
1580 a = 360.0 - a;
1581 } else if (a < -180.0) {
1582 next_mark.angle += 360.0;
1583 a += 360.0;
1584 } else {
1585 a = fabs(a);
1586 }
1587 next_mark_time += sqrd(a / 60.0);
1588 double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1589 next_mark_time += sqrd(ta / 60.0);
1590 double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1591 next_mark_time += sqrd(s / 2.0);
1592 next_mark_time = sqrt(next_mark_time);
1593 // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1594 //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1595 // next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1596 if (tmp < 0) next_mark_time /= -tmp;
1597 }
1598 }
1599
1600 if (presentation_mode) {
1601 // Advance position towards next_mark
1602 double p = tick / next_mark_time;
1603 double q = 1 - p;
1604 PresentationMark here = GetView();
1605 if (next_mark.angle < 0) {
1606 if (here.angle >= next_mark.angle + 360.0)
1607 here.angle -= 360.0;
1608 } else if (next_mark.angle >= 360.0) {
1609 if (here.angle <= next_mark.angle - 360.0)
1610 here.angle += 360.0;
1611 }
1612 here.assign(q * here + p * next_mark);
1613 here.angle = q * here.angle + p * next_mark.angle;
1614 if (here.angle < 0) here.angle += 360.0;
1615 else if (here.angle >= 360.0) here.angle -= 360.0;
1616 here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1617 here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1618 SetView(here);
1619 this_mark_total += tick;
1620 next_mark_time -= tick;
1621 }
1622
1623 ForceRefresh();
1624 return;
1625 }
1626
1627 // When rotating...
1628 if (m_Rotating) {
1629 Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1630 TurnCave(step);
1631 }
1632
1633 if (m_SwitchingTo == PLAN) {
1634 // When switching to plan view...
1635 Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1636 TiltCave(step);
1637 if (m_TiltAngle == -90.0) {
1638 m_SwitchingTo = 0;
1639 }
1640 } else if (m_SwitchingTo == ELEVATION) {
1641 // When switching to elevation view...
1642 Double step;
1643 if (m_TiltAngle > 0.0) {
1644 step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1645 } else {
1646 step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1647 }
1648 if (fabs(step) >= fabs(m_TiltAngle)) {
1649 m_SwitchingTo = 0;
1650 step = -m_TiltAngle;
1651 }
1652 TiltCave(step);
1653 } else if (m_SwitchingTo) {
1654 // Rotate the shortest way around to the destination angle. If we're
1655 // 180 off, we favour turning anticlockwise, as auto-rotation does by
1656 // default.
1657 Double target = (m_SwitchingTo - NORTH) * 90;
1658 Double diff = target - m_PanAngle;
1659 diff = fmod(diff, 360);
1660 if (diff <= -180)
1661 diff += 360;
1662 else if (diff > 180)
1663 diff -= 360;
1664 if (m_RotationStep < 0 && diff == 180.0)
1665 diff = -180.0;
1666 Double step = base_pan - m_PanAngle;
1667 Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1668 if (diff > 0) {
1669 step += delta;
1670 } else {
1671 step -= delta;
1672 }
1673 step = fmod(step, 360);
1674 if (step <= -180)
1675 step += 360;
1676 else if (step > 180)
1677 step -= 360;
1678 if (fabs(step) >= fabs(diff)) {
1679 m_SwitchingTo = 0;
1680 step = diff;
1681 }
1682 TurnCave(step);
1683 }
1684
1685 ForceRefresh();
1686}
1687
1688// How much to allow around the box - this is because of the ring shape
1689// at one end of the line.
1690static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1691#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1692void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
1693{
1694#ifdef __WXMSW__
1695 (void)a;
1696 (void)b;
1697 (void)c;
1698 // FIXME: We get odd redraw artifacts if we just update the line, and
1699 // redrawing the whole scene doesn't actually seem to be measurably
1700 // slower. That may not be true with software rendering though...
1701 ForceRefresh();
1702#else
1703 // Best of all might be to copy the window contents before we draw the
1704 // line, then replace each time we redraw.
1705
1706 // Calculate the minimum rectangle which includes the old and new
1707 // measuring lines to minimise the redraw time
1708 int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1709 double X, Y, Z;
1710 if (a) {
1711 if (!Transform(*a, &X, &Y, &Z)) {
1712 printf("oops\n");
1713 } else {
1714 int x = int(X);
1715 int y = GetYSize() - 1 - int(Y);
1716 l = x;
1717 r = x;
1718 u = y;
1719 d = y;
1720 }
1721 }
1722 if (b) {
1723 if (!Transform(*b, &X, &Y, &Z)) {
1724 printf("oops\n");
1725 } else {
1726 int x = int(X);
1727 int y = GetYSize() - 1 - int(Y);
1728 l = min(l, x);
1729 r = max(r, x);
1730 u = max(u, y);
1731 d = min(d, y);
1732 }
1733 }
1734 if (c) {
1735 if (!Transform(*c, &X, &Y, &Z)) {
1736 printf("oops\n");
1737 } else {
1738 int x = int(X);
1739 int y = GetYSize() - 1 - int(Y);
1740 l = min(l, x);
1741 r = max(r, x);
1742 u = max(u, y);
1743 d = min(d, y);
1744 }
1745 }
1746 l -= MARGIN;
1747 r += MARGIN;
1748 u += MARGIN;
1749 d -= MARGIN;
1750 RefreshRect(wxRect(l, d, r - l, u - d), false);
1751#endif
1752}
1753
1754void GfxCore::SetHereFromTree(const LabelInfo * p)
1755{
1756 SetHere(p);
1757 m_Parent->ShowInfo(m_here, m_there);
1758}
1759
1760void GfxCore::SetHere(const LabelInfo *p)
1761{
1762 if (p == m_here) return;
1763 bool line_active = MeasuringLineActive();
1764 const LabelInfo * old = m_here;
1765 m_here = p;
1766 if (line_active || MeasuringLineActive())
1767 RefreshLine(old, m_there, m_here);
1768}
1769
1770void GfxCore::SetThere(const LabelInfo * p)
1771{
1772 if (p == m_there) return;
1773 const LabelInfo * old = m_there;
1774 m_there = p;
1775 RefreshLine(m_here, old, m_there);
1776}
1777
1778void GfxCore::CreateHitTestGrid()
1779{
1780 if (!m_PointGrid) {
1781 // Initialise hit-test grid.
1782 m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1783 } else {
1784 // Clear hit-test grid.
1785 for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1786 m_PointGrid[i].clear();
1787 }
1788 }
1789
1790 const SurveyFilter* filter = m_Parent->GetTreeFilter();
1791 // Fill the grid.
1792 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1793 list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1794 while (pos != end) {
1795 LabelInfo* label = *pos++;
1796
1797 if (!((m_Surface && label->IsSurface()) ||
1798 (m_Legs && label->IsUnderground()) ||
1799 (!label->IsSurface() && !label->IsUnderground()))) {
1800 // if this station isn't to be displayed, skip to the next
1801 // (last case is for stns with no legs attached)
1802 continue;
1803 }
1804 if (filter && !filter->CheckVisible(label->GetText()))
1805 continue;
1806
1807 // Calculate screen coordinates.
1808 double cx, cy, cz;
1809 Transform(*label, &cx, &cy, &cz);
1810 if (cx < 0 || cx >= GetXSize()) continue;
1811 if (cy < 0 || cy >= GetYSize()) continue;
1812
1813 cy = GetYSize() - cy;
1814
1815 // On-screen, so add to hit-test grid...
1816 int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1817 int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
1818
1819 m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1820 }
1821
1822 m_HitTestGridValid = true;
1823}
1824
1825//
1826// Methods for controlling the orientation of the survey
1827//
1828
1829void GfxCore::TurnCave(Double angle)
1830{
1831 // Turn the cave around its z-axis by a given angle.
1832
1833 m_PanAngle += angle;
1834 // Wrap to range [0, 360):
1835 m_PanAngle = fmod(m_PanAngle, 360.0);
1836 if (m_PanAngle < 0.0) {
1837 m_PanAngle += 360.0;
1838 }
1839
1840 m_HitTestGridValid = false;
1841 if (m_here && m_here == &temp_here) SetHere();
1842
1843 SetRotation(m_PanAngle, m_TiltAngle);
1844}
1845
1846void GfxCore::TurnCaveTo(Double angle)
1847{
1848 if (m_Rotating) {
1849 // If we're rotating, jump to the specified angle.
1850 TurnCave(angle - m_PanAngle);
1851 SetPanBase();
1852 return;
1853 }
1854
1855 int new_switching_to = ((int)angle) / 90 + NORTH;
1856 if (new_switching_to == m_SwitchingTo) {
1857 // A second order to switch takes us there right away
1858 TurnCave(angle - m_PanAngle);
1859 m_SwitchingTo = 0;
1860 ForceRefresh();
1861 } else {
1862 SetPanBase();
1863 m_SwitchingTo = new_switching_to;
1864 }
1865}
1866
1867void GfxCore::TiltCave(Double tilt_angle)
1868{
1869 // Tilt the cave by a given angle.
1870 if (m_TiltAngle + tilt_angle > 90.0) {
1871 m_TiltAngle = 90.0;
1872 } else if (m_TiltAngle + tilt_angle < -90.0) {
1873 m_TiltAngle = -90.0;
1874 } else {
1875 m_TiltAngle += tilt_angle;
1876 }
1877
1878 m_HitTestGridValid = false;
1879 if (m_here && m_here == &temp_here) SetHere();
1880
1881 SetRotation(m_PanAngle, m_TiltAngle);
1882}
1883
1884void GfxCore::TranslateCave(int dx, int dy)
1885{
1886 AddTranslationScreenCoordinates(dx, dy);
1887 m_HitTestGridValid = false;
1888
1889 if (m_here && m_here == &temp_here) SetHere();
1890
1891 ForceRefresh();
1892}
1893
1894void GfxCore::DragFinished()
1895{
1896 m_MouseOutsideCompass = m_MouseOutsideElev = false;
1897 ForceRefresh();
1898}
1899
1900void GfxCore::ClearCoords()
1901{
1902 m_Parent->ClearCoords();
1903}
1904
1905void GfxCore::SetCoords(wxPoint point)
1906{
1907 // We can't work out 2D coordinates from a perspective view, and it
1908 // doesn't really make sense to show coordinates while we're animating.
1909 if (GetPerspective() || Animating()) return;
1910
1911 // Update the coordinate or altitude display, given the (x, y) position in
1912 // window coordinates. The relevant display is updated depending on
1913 // whether we're in plan or elevation view.
1914
1915 double cx, cy, cz;
1916
1917 SetDataTransform();
1918 ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
1919
1920 if (ShowingPlan()) {
1921 m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1922 cy + m_Parent->GetOffset().GetY(),
1923 m_there);
1924 } else if (ShowingElevation()) {
1925 m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
1926 m_there);
1927 } else {
1928 m_Parent->ClearCoords();
1929 }
1930}
1931
1932int GfxCore::GetCompassWidth() const
1933{
1934 static int result = 0;
1935 if (result == 0) {
1936 result = INDICATOR_BOX_SIZE;
1937 int width;
1938 const wxString & msg = wmsg(/*Facing*/203);
1939 GetTextExtent(msg, &width, NULL);
1940 if (width > result) result = width;
1941 }
1942 return result;
1943}
1944
1945int GfxCore::GetClinoWidth() const
1946{
1947 static int result = 0;
1948 if (result == 0) {
1949 result = INDICATOR_BOX_SIZE;
1950 int width;
1951 const wxString & msg1 = wmsg(/*Plan*/432);
1952 GetTextExtent(msg1, &width, NULL);
1953 if (width > result) result = width;
1954 const wxString & msg2 = wmsg(/*Kiwi Plan*/433);
1955 GetTextExtent(msg2, &width, NULL);
1956 if (width > result) result = width;
1957 const wxString & msg3 = wmsg(/*Elevation*/118);
1958 GetTextExtent(msg3, &width, NULL);
1959 if (width > result) result = width;
1960 }
1961 return result;
1962}
1963
1964int GfxCore::GetCompassXPosition() const
1965{
1966 // Return the x-coordinate of the centre of the compass in window
1967 // coordinates.
1968 return GetXSize() - INDICATOR_OFFSET_X - GetCompassWidth() / 2;
1969}
1970
1971int GfxCore::GetClinoXPosition() const
1972{
1973 // Return the x-coordinate of the centre of the compass in window
1974 // coordinates.
1975 return GetXSize() - GetClinoOffset() - GetClinoWidth() / 2;
1976}
1977
1978int GfxCore::GetIndicatorYPosition() const
1979{
1980 // Return the y-coordinate of the centre of the indicators in window
1981 // coordinates.
1982 return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1983}
1984
1985int GfxCore::GetIndicatorRadius() const
1986{
1987 // Return the radius of each indicator.
1988 return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1989}
1990
1991bool GfxCore::PointWithinCompass(wxPoint point) const
1992{
1993 // Determine whether a point (in window coordinates) lies within the
1994 // compass.
1995 if (!ShowingCompass()) return false;
1996
1997 glaCoord dx = point.x - GetCompassXPosition();
1998 glaCoord dy = point.y - GetIndicatorYPosition();
1999 glaCoord radius = GetIndicatorRadius();
2000
2001 return (dx * dx + dy * dy <= radius * radius);
2002}
2003
2004bool GfxCore::PointWithinClino(wxPoint point) const
2005{
2006 // Determine whether a point (in window coordinates) lies within the clino.
2007 if (!ShowingClino()) return false;
2008
2009 glaCoord dx = point.x - GetClinoXPosition();
2010 glaCoord dy = point.y - GetIndicatorYPosition();
2011 glaCoord radius = GetIndicatorRadius();
2012
2013 return (dx * dx + dy * dy <= radius * radius);
2014}
2015
2016bool GfxCore::PointWithinScaleBar(wxPoint point) const
2017{
2018 // Determine whether a point (in window coordinates) lies within the scale
2019 // bar.
2020 if (!ShowingScaleBar()) return false;
2021
2022 return (point.x >= SCALE_BAR_OFFSET_X &&
2023 point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
2024 point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
2025 point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
2026}
2027
2028bool GfxCore::PointWithinColourKey(wxPoint point) const
2029{
2030 // Determine whether a point (in window coordinates) lies within the key.
2031 point.x -= GetXSize() - KEY_OFFSET_X;
2032 point.y = KEY_OFFSET_Y - point.y;
2033 return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
2034 point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
2035}
2036
2037void GfxCore::SetCompassFromPoint(wxPoint point)
2038{
2039 // Given a point in window coordinates, set the heading of the survey. If
2040 // the point is outside the compass, it snaps to 45 degree intervals;
2041 // otherwise it operates as normal.
2042
2043 wxCoord dx = point.x - GetCompassXPosition();
2044 wxCoord dy = point.y - GetIndicatorYPosition();
2045 wxCoord radius = GetIndicatorRadius();
2046
2047 double angle = deg(atan2(double(dx), double(dy))) - 180.0;
2048 if (dx * dx + dy * dy <= radius * radius) {
2049 TurnCave(angle - m_PanAngle);
2050 m_MouseOutsideCompass = false;
2051 } else {
2052 TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
2053 m_MouseOutsideCompass = true;
2054 }
2055
2056 ForceRefresh();
2057}
2058
2059void GfxCore::SetClinoFromPoint(wxPoint point)
2060{
2061 // Given a point in window coordinates, set the elevation of the survey.
2062 // If the point is outside the clino, it snaps to 90 degree intervals;
2063 // otherwise it operates as normal.
2064
2065 glaCoord dx = point.x - GetClinoXPosition();
2066 glaCoord dy = point.y - GetIndicatorYPosition();
2067 glaCoord radius = GetIndicatorRadius();
2068
2069 if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
2070 TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
2071 m_MouseOutsideElev = false;
2072 } else if (dy >= INDICATOR_MARGIN) {
2073 TiltCave(-90.0 - m_TiltAngle);
2074 m_MouseOutsideElev = true;
2075 } else if (dy <= -INDICATOR_MARGIN) {
2076 TiltCave(90.0 - m_TiltAngle);
2077 m_MouseOutsideElev = true;
2078 } else {
2079 TiltCave(-m_TiltAngle);
2080 m_MouseOutsideElev = true;
2081 }
2082
2083 ForceRefresh();
2084}
2085
2086void GfxCore::SetScaleBarFromOffset(wxCoord dx)
2087{
2088 // Set the scale of the survey, given an offset as to how much the mouse has
2089 // been dragged over the scalebar since the last scale change.
2090
2091 SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
2092 ForceRefresh();
2093}
2094
2095void GfxCore::RedrawIndicators()
2096{
2097 // Redraw the compass and clino indicators.
2098
2099 int total_width = GetCompassWidth() + INDICATOR_GAP + GetClinoWidth();
2100 RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - total_width,
2101 GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
2102 total_width,
2103 INDICATOR_BOX_SIZE), false);
2104}
2105
2106void GfxCore::StartRotation()
2107{
2108 // Start the survey rotating.
2109
2110 if (m_SwitchingTo >= NORTH)
2111 m_SwitchingTo = 0;
2112 m_Rotating = true;
2113 SetPanBase();
2114}
2115
2116void GfxCore::ToggleRotation()
2117{
2118 // Toggle the survey rotation on/off.
2119
2120 if (m_Rotating) {
2121 StopRotation();
2122 } else {
2123 StartRotation();
2124 }
2125}
2126
2127void GfxCore::StopRotation()
2128{
2129 // Stop the survey rotating.
2130
2131 m_Rotating = false;
2132 ForceRefresh();
2133}
2134
2135bool GfxCore::IsExtendedElevation() const
2136{
2137 return m_Parent->IsExtendedElevation();
2138}
2139
2140void GfxCore::ReverseRotation()
2141{
2142 // Reverse the direction of rotation.
2143
2144 m_RotationStep = -m_RotationStep;
2145 if (m_Rotating)
2146 SetPanBase();
2147}
2148
2149void GfxCore::RotateSlower(bool accel)
2150{
2151 // Decrease the speed of rotation, optionally by an increased amount.
2152 if (fabs(m_RotationStep) == 1.0)
2153 return;
2154
2155 m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2156
2157 if (fabs(m_RotationStep) < 1.0) {
2158 m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
2159 }
2160 if (m_Rotating)
2161 SetPanBase();
2162}
2163
2164void GfxCore::RotateFaster(bool accel)
2165{
2166 // Increase the speed of rotation, optionally by an increased amount.
2167 if (fabs(m_RotationStep) == 180.0)
2168 return;
2169
2170 m_RotationStep *= accel ? 1.44 : 1.2;
2171 if (fabs(m_RotationStep) > 180.0) {
2172 m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
2173 }
2174 if (m_Rotating)
2175 SetPanBase();
2176}
2177
2178void GfxCore::SwitchToElevation()
2179{
2180 // Perform an animated switch to elevation view.
2181
2182 if (m_SwitchingTo != ELEVATION) {
2183 SetTiltBase();
2184 m_SwitchingTo = ELEVATION;
2185 } else {
2186 // A second order to switch takes us there right away
2187 TiltCave(-m_TiltAngle);
2188 m_SwitchingTo = 0;
2189 ForceRefresh();
2190 }
2191}
2192
2193void GfxCore::SwitchToPlan()
2194{
2195 // Perform an animated switch to plan view.
2196
2197 if (m_SwitchingTo != PLAN) {
2198 SetTiltBase();
2199 m_SwitchingTo = PLAN;
2200 } else {
2201 // A second order to switch takes us there right away
2202 TiltCave(-90.0 - m_TiltAngle);
2203 m_SwitchingTo = 0;
2204 ForceRefresh();
2205 }
2206}
2207
2208void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2209{
2210
2211 SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
2212 Double scale = HUGE_VAL;
2213 const Vector3 ext = m_Parent->GetExtent();
2214 if (xmax > xmin) {
2215 Double s = ext.GetX() / (xmax - xmin);
2216 if (s < scale) scale = s;
2217 }
2218 if (ymax > ymin) {
2219 Double s = ext.GetY() / (ymax - ymin);
2220 if (s < scale) scale = s;
2221 }
2222 if (!ShowingPlan() && zmax > zmin) {
2223 Double s = ext.GetZ() / (zmax - zmin);
2224 if (s < scale) scale = s;
2225 }
2226 if (scale != HUGE_VAL) SetScale(scale);
2227 ForceRefresh();
2228}
2229
2230bool GfxCore::CanRaiseViewpoint() const
2231{
2232 // Determine if the survey can be viewed from a higher angle of elevation.
2233
2234 return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
2235}
2236
2237bool GfxCore::CanLowerViewpoint() const
2238{
2239 // Determine if the survey can be viewed from a lower angle of elevation.
2240
2241 return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
2242}
2243
2244bool GfxCore::HasDepth() const
2245{
2246 return m_Parent->GetDepthExtent() == 0.0;
2247}
2248
2249bool GfxCore::HasErrorInformation() const
2250{
2251 return m_Parent->HasErrorInformation();
2252}
2253
2254bool GfxCore::HasDateInformation() const
2255{
2256 return m_Parent->GetDateMin() >= 0;
2257}
2258
2259bool GfxCore::ShowingPlan() const
2260{
2261 // Determine if the survey is in plan view.
2262
2263 return (m_TiltAngle == -90.0);
2264}
2265
2266bool GfxCore::ShowingElevation() const
2267{
2268 // Determine if the survey is in elevation view.
2269
2270 return (m_TiltAngle == 0.0);
2271}
2272
2273bool GfxCore::ShowingMeasuringLine() const
2274{
2275 // Determine if the measuring line is being shown. Only check if "there"
2276 // is valid, since that means the measuring line anchor is out.
2277
2278 return m_there;
2279}
2280
2281void GfxCore::ToggleFlag(bool* flag, int update)
2282{
2283 *flag = !*flag;
2284 if (update == UPDATE_BLOBS) {
2285 UpdateBlobs();
2286 } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2287 UpdateBlobs();
2288 InvalidateList(LIST_CROSSES);
2289 m_HitTestGridValid = false;
2290 }
2291 ForceRefresh();
2292}
2293
2294int GfxCore::GetNumEntrances() const
2295{
2296 return m_Parent->GetNumEntrances();
2297}
2298
2299int GfxCore::GetNumFixedPts() const
2300{
2301 return m_Parent->GetNumFixedPts();
2302}
2303
2304int GfxCore::GetNumExportedPts() const
2305{
2306 return m_Parent->GetNumExportedPts();
2307}
2308
2309void GfxCore::ToggleTerrain()
2310{
2311 if (!m_Terrain && !dem) {
2312 // OnOpenTerrain() calls us if a file is selected.
2313 wxCommandEvent dummy;
2314 m_Parent->OnOpenTerrain(dummy);
2315 return;
2316 }
2317 ToggleFlag(&m_Terrain);
2318}
2319
2320void GfxCore::ToggleFatFinger()
2321{
2322 if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2323 sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2324 wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2325 } else {
2326 sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2327 wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2328 }
2329}
2330
2331void GfxCore::ClearTreeSelection()
2332{
2333 m_Parent->ClearTreeSelection();
2334}
2335
2336void GfxCore::CentreOn(const Point &p)
2337{
2338 SetTranslation(-p);
2339 m_HitTestGridValid = false;
2340
2341 ForceRefresh();
2342}
2343
2344void GfxCore::ForceRefresh()
2345{
2346 Refresh(false);
2347}
2348
2349void GfxCore::GenerateList(unsigned int l)
2350{
2351 assert(m_HaveData);
2352
2353 switch (l) {
2354 case LIST_COMPASS:
2355 DrawCompass();
2356 break;
2357 case LIST_CLINO:
2358 DrawClino();
2359 break;
2360 case LIST_CLINO_BACK:
2361 DrawClinoBack();
2362 break;
2363 case LIST_SCALE_BAR:
2364 DrawScaleBar();
2365 break;
2366 case LIST_DEPTH_KEY:
2367 DrawDepthKey();
2368 break;
2369 case LIST_DATE_KEY:
2370 DrawDateKey();
2371 break;
2372 case LIST_ERROR_KEY:
2373 DrawErrorKey();
2374 break;
2375 case LIST_GRADIENT_KEY:
2376 DrawGradientKey();
2377 break;
2378 case LIST_LENGTH_KEY:
2379 DrawLengthKey();
2380 break;
2381 case LIST_UNDERGROUND_LEGS:
2382 GenerateDisplayList(false);
2383 break;
2384 case LIST_TUBES:
2385 GenerateDisplayListTubes();
2386 break;
2387 case LIST_SURFACE_LEGS:
2388 GenerateDisplayList(true);
2389 break;
2390 case LIST_BLOBS:
2391 GenerateBlobsDisplayList();
2392 break;
2393 case LIST_CROSSES: {
2394 BeginCrosses();
2395 SetColour(col_LIGHT_GREY);
2396 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2397 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2398 while (pos != m_Parent->GetLabelsEnd()) {
2399 const LabelInfo* label = *pos++;
2400
2401 if ((m_Surface && label->IsSurface()) ||
2402 (m_Legs && label->IsUnderground()) ||
2403 (!label->IsSurface() && !label->IsUnderground())) {
2404 // Check if this station should be displayed
2405 // (last case above is for stns with no legs attached)
2406 if (filter && !filter->CheckVisible(label->GetText()))
2407 continue;
2408 DrawCross(label->GetX(), label->GetY(), label->GetZ());
2409 }
2410 }
2411 EndCrosses();
2412 break;
2413 }
2414 case LIST_GRID:
2415 DrawGrid();
2416 break;
2417 case LIST_SHADOW:
2418 GenerateDisplayListShadow();
2419 break;
2420 case LIST_TERRAIN:
2421 DrawTerrain();
2422 break;
2423 default:
2424 assert(false);
2425 break;
2426 }
2427}
2428
2429void GfxCore::ToggleSmoothShading()
2430{
2431 GLACanvas::ToggleSmoothShading();
2432 InvalidateList(LIST_TUBES);
2433 ForceRefresh();
2434}
2435
2436void GfxCore::GenerateDisplayList(bool surface)
2437{
2438 unsigned surf_or_not = surface ? img_FLAG_SURFACE : 0;
2439 // Generate the display list for the surface or underground legs.
2440 for (int f = 0; f != 8; ++f) {
2441 if ((f & img_FLAG_SURFACE) != surf_or_not) continue;
2442 const unsigned SHOW_DASHED_AND_FADED = unsigned(-1);
2443 unsigned style = SHOW_NORMAL;
2444 if ((f & img_FLAG_SPLAY) && m_Splays != SHOW_NORMAL) {
2445 style = m_Splays;
2446 } else if (f & img_FLAG_DUPLICATE) {
2447 style = m_Dupes;
2448 }
2449 if (f & img_FLAG_SURFACE) {
2450 if (style == SHOW_FADED) {
2451 style = SHOW_DASHED_AND_FADED;
2452 } else {
2453 style = SHOW_DASHED;
2454 }
2455 }
2456
2457 switch (style) {
2458 case SHOW_HIDE:
2459 continue;
2460 case SHOW_FADED:
2461 SetAlpha(0.4);
2462 break;
2463 case SHOW_DASHED:
2464 EnableDashedLines();
2465 break;
2466 case SHOW_DASHED_AND_FADED:
2467 SetAlpha(0.4);
2468 EnableDashedLines();
2469 break;
2470 }
2471
2472 void (GfxCore::* add_poly)(const traverse&);
2473 if (surface) {
2474 if (m_ColourBy == COLOUR_BY_ERROR) {
2475 add_poly = &GfxCore::AddPolylineError;
2476 } else {
2477 add_poly = &GfxCore::AddPolyline;
2478 }
2479 } else {
2480 add_poly = AddPoly;
2481 }
2482
2483 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2484 list<traverse>::const_iterator trav = m_Parent->traverses_begin(f, filter);
2485 list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2486 while (trav != tend) {
2487 (this->*add_poly)(*trav);
2488 trav = m_Parent->traverses_next(f, filter, trav);
2489 }
2490
2491 switch (style) {
2492 case SHOW_FADED:
2493 SetAlpha(1.0);
2494 break;
2495 case SHOW_DASHED:
2496 DisableDashedLines();
2497 break;
2498 case SHOW_DASHED_AND_FADED:
2499 DisableDashedLines();
2500 SetAlpha(1.0);
2501 break;
2502 }
2503 }
2504}
2505
2506void GfxCore::GenerateDisplayListTubes()
2507{
2508 // Generate the display list for the tubes.
2509 list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2510 list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2511 while (trav != tend) {
2512 SkinPassage(*trav);
2513 ++trav;
2514 }
2515}
2516
2517void GfxCore::GenerateDisplayListShadow()
2518{
2519 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2520 SetColour(col_BLACK);
2521 for (int f = 0; f != 8; ++f) {
2522 // Only include underground legs in the shadow.
2523 if ((f & img_FLAG_SURFACE) != 0) continue;
2524 list<traverse>::const_iterator trav = m_Parent->traverses_begin(f, filter);
2525 list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2526 while (trav != tend) {
2527 AddPolylineShadow(*trav);
2528 trav = m_Parent->traverses_next(f, filter, trav);
2529 }
2530 }
2531}
2532
2533void
2534GfxCore::parse_hgt_filename(const wxString & lc_name)
2535{
2536 char * leaf = leaf_from_fnm(lc_name.utf8_str());
2537 const char * p = leaf;
2538 char * q;
2539 char dirn = *p++;
2540 o_y = strtoul(p, &q, 10);
2541 p = q;
2542 if (dirn == 's')
2543 o_y = -o_y;
2544 ++o_y;
2545 dirn = *p++;
2546 o_x = strtoul(p, &q, 10);
2547 if (dirn == 'w')
2548 o_x = -o_x;
2549 bigendian = true;
2550 nodata_value = -32768;
2551 osfree(leaf);
2552}
2553
2554size_t
2555GfxCore::parse_hdr(wxInputStream & is, unsigned long & skipbytes)
2556{
2557 // ESRI docs say NBITS defaults to 8.
2558 unsigned long nbits = 8;
2559 // ESRI docs say NBANDS defaults to 1.
2560 unsigned long nbands = 1;
2561 unsigned long bandrowbytes = 0;
2562 unsigned long totalrowbytes = 0;
2563 // ESRI docs say ULXMAP defaults to 0.
2564 o_x = 0.0;
2565 // ESRI docs say ULYMAP defaults to NROWS - 1.
2566 o_y = HUGE_VAL;
2567 // ESRI docs say XDIM and YDIM default to 1.
2568 step_x = step_y = 1.0;
2569 while (!is.Eof()) {
2570 wxString line;
2571 int ch;
2572 while ((ch = is.GetC()) != wxEOF) {
2573 if (ch == '\n' || ch == '\r') break;
2574 line += wxChar(ch);
2575 }
2576#define CHECK(X, COND) \
2577} else if (line.StartsWith(wxT(X " "))) { \
2578size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2579if (v == line.npos || !(COND)) { \
2580err += wxT("Unexpected value for " X); \
2581}
2582 wxString err;
2583 if (false) {
2584 // I = little-endian; M = big-endian
2585 CHECK("BYTEORDER", (bigendian = (line[v] == 'M')) || line[v] == 'I')
2586 // ESRI docs say LAYOUT defaults to BIL if not specified.
2587 CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2588 CHECK("NROWS", line.substr(v).ToCULong(&dem_height))
2589 CHECK("NCOLS", line.substr(v).ToCULong(&dem_width))
2590 // ESRI docs say NBANDS defaults to 1 if not specified.
2591 CHECK("NBANDS", line.substr(v).ToCULong(&nbands) && nbands == 1)
2592 CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2593 CHECK("BANDROWBYTES", line.substr(v).ToCULong(&bandrowbytes))
2594 CHECK("TOTALROWBYTES", line.substr(v).ToCULong(&totalrowbytes))
2595 // PIXELTYPE is a GDAL extension, so may not be present.
2596 CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2597 CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2598 CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2599 CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2600 CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2601 CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2602 CHECK("SKIPBYTES", line.substr(v).ToCULong(&skipbytes))
2603 }
2604 if (!err.empty()) {
2605 wxMessageBox(err);
2606 }
2607 }
2608 if (o_y == HUGE_VAL) {
2609 o_y = dem_height - 1;
2610 }
2611 if (bandrowbytes != 0) {
2612 if (nbits * dem_width != bandrowbytes * 8) {
2613 wxMessageBox("BANDROWBYTES setting indicates unused bits after each band - not currently supported");
2614 }
2615 }
2616 if (totalrowbytes != 0) {
2617 // This is the ESRI default for BIL, for BIP it would be
2618 // nbands * bandrowbytes.
2619 if (nbands * nbits * dem_width != totalrowbytes * 8) {
2620 wxMessageBox("TOTALROWBYTES setting indicates unused bits after "
2621 "each row - not currently supported");
2622 }
2623 }
2624 return ((nbits * dem_width + 7) / 8) * dem_height;
2625}
2626
2627bool
2628GfxCore::read_bil(wxInputStream & is, size_t size, unsigned long skipbytes)
2629{
2630 bool know_size = true;
2631 if (!size) {
2632 // If the stream doesn't know its size, GetSize() returns 0.
2633 size = is.GetSize();
2634 if (!size) {
2635 size = DEFAULT_HGT_SIZE;
2636 know_size = false;
2637 }
2638 }
2639 dem = new unsigned short[size / 2];
2640 if (skipbytes) {
2641 if (is.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2642 while (skipbytes) {
2643 unsigned long to_read = skipbytes;
2644 if (size < to_read) to_read = size;
2645 is.Read(reinterpret_cast<char *>(dem), to_read);
2646 size_t c = is.LastRead();
2647 if (c == 0) {
2648 wxMessageBox(wxT("Failed to skip terrain data header"));
2649 break;
2650 }
2651 skipbytes -= c;
2652 }
2653 }
2654 }
2655
2656#if wxCHECK_VERSION(2,9,5)
2657 if (!is.ReadAll(dem, size)) {
2658 if (know_size) {
2659 // FIXME: On __WXMSW__ currently we fail to
2660 // read any data from files in zips.
2661 delete [] dem;
2662 dem = NULL;
2663 wxMessageBox(wxT("Failed to read terrain data"));
2664 return false;
2665 }
2666 size = is.LastRead();
2667 }
2668#else
2669 char * p = reinterpret_cast<char *>(dem);
2670 while (size) {
2671 is.Read(p, size);
2672 size_t c = is.LastRead();
2673 if (c == 0) {
2674 if (!know_size) {
2675 size = DEFAULT_HGT_SIZE - size;
2676 if (size)
2677 break;
2678 }
2679 delete [] dem;
2680 dem = NULL;
2681 wxMessageBox(wxT("Failed to read terrain data"));
2682 return false;
2683 }
2684 p += c;
2685 size -= c;
2686 }
2687#endif
2688
2689 if (dem_width == 0 && dem_height == 0) {
2690 dem_width = dem_height = sqrt(size / 2);
2691 if (dem_width * dem_height * 2 != size) {
2692 delete [] dem;
2693 dem = NULL;
2694 wxMessageBox(wxT("HGT format data doesn't form a square"));
2695 return false;
2696 }
2697 step_x = step_y = 1.0 / dem_width;
2698 }
2699
2700 return true;
2701}
2702
2703bool GfxCore::LoadDEM(const wxString & file)
2704{
2705 if (m_Parent->GetCSProj().empty()) {
2706 wxMessageBox(wxT("No coordinate system specified in survey data"));
2707 return false;
2708 }
2709
2710 delete [] dem;
2711 dem = NULL;
2712
2713 size_t size = 0;
2714 // Default is to not skip any bytes.
2715 unsigned long skipbytes = 0;
2716 // For .hgt files, default to using filesize to determine.
2717 dem_width = dem_height = 0;
2718 // ESRI say "The default byte order is the same as that of the host machine
2719 // executing the software", but that's stupid so we default to
2720 // little-endian.
2721 bigendian = false;
2722
2723 wxFileInputStream fs(file);
2724 if (!fs.IsOk()) {
2725 wxMessageBox(wxT("Failed to open DEM file"));
2726 return false;
2727 }
2728
2729 const wxString & lc_file = file.Lower();
2730 if (lc_file.EndsWith(wxT(".hgt"))) {
2731 parse_hgt_filename(lc_file);
2732 read_bil(fs, size, skipbytes);
2733 } else if (lc_file.EndsWith(wxT(".bil"))) {
2734 wxString hdr_file = file;
2735 hdr_file.replace(file.size() - 4, 4, wxT(".hdr"));
2736 wxFileInputStream hdr_is(hdr_file);
2737 if (!hdr_is.IsOk()) {
2738 wxMessageBox(wxT("Failed to open HDR file '") + hdr_file + wxT("'"));
2739 return false;
2740 }
2741 size = parse_hdr(hdr_is, skipbytes);
2742 read_bil(fs, size, skipbytes);
2743 } else if (lc_file.EndsWith(wxT(".zip"))) {
2744 wxZipEntry * ze_data = NULL;
2745 wxZipInputStream zs(fs);
2746 wxZipEntry * ze;
2747 while ((ze = zs.GetNextEntry()) != NULL) {
2748 if (!ze->IsDir()) {
2749 const wxString & lc_name = ze->GetName().Lower();
2750 if (!ze_data && lc_name.EndsWith(wxT(".hgt"))) {
2751 // SRTM .hgt files are raw binary data, with the filename
2752 // encoding the coordinates.
2753 parse_hgt_filename(lc_name);
2754 read_bil(zs, size, skipbytes);
2755 delete ze;
2756 break;
2757 }
2758
2759 if (!ze_data && lc_name.EndsWith(wxT(".bil"))) {
2760 if (size) {
2761 read_bil(zs, size, skipbytes);
2762 break;
2763 }
2764 ze_data = ze;
2765 continue;
2766 }
2767
2768 if (lc_name.EndsWith(wxT(".hdr"))) {
2769 size = parse_hdr(zs, skipbytes);
2770 if (ze_data) {
2771 if (!zs.OpenEntry(*ze_data)) {
2772 wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2773 break;
2774 }
2775 read_bil(zs, size, skipbytes);
2776 }
2777 } else if (lc_name.EndsWith(wxT(".prj"))) {
2778 //FIXME: check this matches the datum string we use
2779 //Projection GEOGRAPHIC
2780 //Datum WGS84
2781 //Zunits METERS
2782 //Units DD
2783 //Spheroid WGS84
2784 //Xshift 0.0000000000
2785 //Yshift 0.0000000000
2786 //Parameters
2787 }
2788 }
2789 delete ze;
2790 }
2791 delete ze_data;
2792 }
2793
2794 if (!dem) {
2795 return false;
2796 }
2797
2798 InvalidateList(LIST_TERRAIN);
2799 ForceRefresh();
2800 return true;
2801}
2802
2803void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2804{
2805 Vector3 n = (b - a) * (c - a);
2806 n.normalise();
2807 Double factor = dot(n, light) * .95 + .05;
2808 SetColour(col_WHITE, factor);
2809 PlaceVertex(a);
2810 PlaceVertex(b);
2811 PlaceVertex(c);
2812 ++n_tris;
2813}
2814
2815// Like wxBusyCursor, but you can cancel it early.
2816class AvenBusyCursor {
2817 bool active;
2818
2819 public:
2820 AvenBusyCursor() : active(true) {
2821 wxBeginBusyCursor();
2822 }
2823
2824 void stop() {
2825 if (active) {
2826 active = false;
2827 wxEndBusyCursor();
2828 }
2829 }
2830
2831 ~AvenBusyCursor() {
2832 stop();
2833 }
2834};
2835
2836void GfxCore::DrawTerrain()
2837{
2838 if (!dem) return;
2839
2840 AvenBusyCursor hourglass;
2841
2842 // Draw terrain to twice the extent, or at least 1km.
2843 double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2844#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2845 static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2846 if (!pj_in) {
2847 ToggleTerrain();
2848 delete [] dem;
2849 dem = NULL;
2850 hourglass.stop();
2851 error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2852 return;
2853 }
2854 static projPJ pj_out = pj_init_plus(m_Parent->GetCSProj().c_str());
2855 if (!pj_out) {
2856 ToggleTerrain();
2857 delete [] dem;
2858 dem = NULL;
2859 hourglass.stop();
2860 error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->GetCSProj().c_str());
2861 return;
2862 }
2863 n_tris = 0;
2864 SetAlpha(0.3);
2865 BeginTriangles();
2866 const Vector3 & off = m_Parent->GetOffset();
2867 vector<Vector3> prevcol(dem_height + 1);
2868 for (size_t x = 0; x < dem_width; ++x) {
2869 double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2870 Vector3 prev;
2871 for (size_t y = 0; y < dem_height; ++y) {
2872 unsigned short elev = dem[x + y * dem_width];
2873#ifdef WORDS_BIGENDIAN
2874 const bool MACHINE_BIGENDIAN = true;
2875#else
2876 const bool MACHINE_BIGENDIAN = false;
2877#endif
2878 if (bigendian != MACHINE_BIGENDIAN) {
2879#if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2880 elev = __builtin_bswap16(elev);
2881#else
2882 elev = (elev >> 8) | (elev << 8);
2883#endif
2884 }
2885 double Z = (short)elev;
2886 Vector3 pt;
2887 if (Z == nodata_value) {
2888 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2889 } else {
2890 double X = X_;
2891 double Y = (o_y - y * step_y) * DEG_TO_RAD;
2892 pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2893 pt = Vector3(X, Y, Z) - off;
2894 double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2895 if (dist_2 > r_sqrd) {
2896 pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2897 }
2898 }
2899 if (x > 0 && y > 0) {
2900 const Vector3 & a = prevcol[y - 1];
2901 const Vector3 & b = prevcol[y];
2902 // If all points are valid, split the quadrilateral into
2903 // triangles along the shorter 3D diagonal, which typically
2904 // looks better:
2905 //
2906 // ----->
2907 // prev---a x prev---a
2908 // | |P /| |\ S|
2909 // y | | / | or | \ |
2910 // V | / | | \ |
2911 // |/ Q| |R \|
2912 // b----pt b----pt
2913 //
2914 // FORWARD BACKWARD
2915 enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
2916 int valid =
2917 ((prev.GetZ() != DBL_MAX)) |
2918 ((a.GetZ() != DBL_MAX) << 1) |
2919 ((b.GetZ() != DBL_MAX) << 2) |
2920 ((pt.GetZ() != DBL_MAX) << 3);
2921 static const int tris_map[16] = {
2922 NONE, // nothing valid
2923 NONE, // prev
2924 NONE, // a
2925 NONE, // a, prev
2926 NONE, // b
2927 NONE, // b, prev
2928 NONE, // b, a
2929 P, // b, a, prev
2930 NONE, // pt
2931 NONE, // pt, prev
2932 NONE, // pt, a
2933 S, // pt, a, prev
2934 NONE, // pt, b
2935 R, // pt, b, prev
2936 Q, // pt, b, a
2937 ALL, // pt, b, a, prev
2938 };
2939 int tris = tris_map[valid];
2940 if (tris == ALL) {
2941 // All points valid.
2942 if ((a - b).magnitude() < (prev - pt).magnitude()) {
2943 tris = P | Q;
2944 } else {
2945 tris = R | S;
2946 }
2947 }
2948 if (tris & P)
2949 DrawTerrainTriangle(a, prev, b);
2950 if (tris & Q)
2951 DrawTerrainTriangle(a, b, pt);
2952 if (tris & R)
2953 DrawTerrainTriangle(pt, prev, b);
2954 if (tris & S)
2955 DrawTerrainTriangle(a, prev, pt);
2956 }
2957 prev = prevcol[y];
2958 prevcol[y].assign(pt);
2959 }
2960 }
2961 EndTriangles();
2962 SetAlpha(1.0);
2963 if (n_tris == 0) {
2964 ToggleTerrain();
2965 delete [] dem;
2966 dem = NULL;
2967 hourglass.stop();
2968 /* TRANSLATORS: Aven shows a circle of terrain covering the area
2969 * of the survey plus a bit, but the terrain data file didn't
2970 * contain any data inside that circle.
2971 */
2972 error(/*No terrain data near area of survey*/161);
2973 }
2974}
2975
2976// Plot blobs.
2977void GfxCore::GenerateBlobsDisplayList()
2978{
2979 if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2980 m_Parent->GetNumHighlightedPts()))
2981 return;
2982
2983 // Plot blobs.
2984 const SurveyFilter* filter = m_Parent->GetTreeFilter();
2985 gla_colour prev_col = col_BLACK; // not a colour used for blobs
2986 list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2987 BeginBlobs();
2988 while (pos != m_Parent->GetLabelsEnd()) {
2989 const LabelInfo* label = *pos++;
2990
2991 // When more than one flag is set on a point:
2992 // search results take priority over entrance highlighting
2993 // which takes priority over fixed point
2994 // highlighting, which in turn takes priority over exported
2995 // point highlighting.
2996
2997 if (!((m_Surface && label->IsSurface()) ||
2998 (m_Legs && label->IsUnderground()) ||
2999 (!label->IsSurface() && !label->IsUnderground()))) {
3000 // if this station isn't to be displayed, skip to the next
3001 // (last case is for stns with no legs attached)
3002 continue;
3003 }
3004 if (filter && !filter->CheckVisible(label->GetText()))
3005 continue;
3006
3007 gla_colour col;
3008
3009 if (label->IsHighLighted()) {
3010 col = col_YELLOW;
3011 } else if (m_Entrances && label->IsEntrance()) {
3012 col = col_GREEN;
3013 } else if (m_FixedPts && label->IsFixedPt()) {
3014 col = col_RED;
3015 } else if (m_ExportedPts && label->IsExportedPt()) {
3016 col = col_TURQUOISE;
3017 } else {
3018 continue;
3019 }
3020
3021 // Stations are sorted by blob type, so colour changes are infrequent.
3022 if (col != prev_col) {
3023 SetColour(col);
3024 prev_col = col;
3025 }
3026 DrawBlob(label->GetX(), label->GetY(), label->GetZ());
3027 }
3028 EndBlobs();
3029}
3030
3031void GfxCore::DrawIndicators()
3032{
3033 // Draw colour key.
3034 if (m_ColourKey) {
3035 drawing_list key_list = LIST_LIMIT_;
3036 switch (m_ColourBy) {
3037 case COLOUR_BY_DEPTH:
3038 key_list = LIST_DEPTH_KEY; break;
3039 case COLOUR_BY_DATE:
3040 key_list = LIST_DATE_KEY; break;
3041 case COLOUR_BY_ERROR:
3042 key_list = LIST_ERROR_KEY; break;
3043 case COLOUR_BY_GRADIENT:
3044 key_list = LIST_GRADIENT_KEY; break;
3045 case COLOUR_BY_LENGTH:
3046 key_list = LIST_LENGTH_KEY; break;
3047 }
3048 if (key_list != LIST_LIMIT_) {
3049 DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
3050 GetYSize() - KEY_OFFSET_Y, 0);
3051 }
3052 }
3053
3054 // Draw compass or elevation/heading indicators.
3055 if (m_Compass || m_Clino) {
3056 if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
3057 }
3058
3059 // Draw scalebar.
3060 if (m_Scalebar && !GetPerspective()) {
3061 DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
3062 }
3063}
3064
3065void GfxCore::PlaceVertexWithColour(const Vector3 & v,
3066 glaTexCoord tex_x, glaTexCoord tex_y,
3067 Double factor)
3068{
3069 SetColour(col_WHITE, factor);
3070 PlaceVertex(v, tex_x, tex_y);
3071}
3072
3073void GfxCore::SetDepthColour(Double z, Double factor) {
3074 // Set the drawing colour based on the altitude.
3075 Double z_ext = m_Parent->GetDepthExtent();
3076
3077 z -= m_Parent->GetDepthMin();
3078 // points arising from tubes may be slightly outside the limits...
3079 if (z < 0) z = 0;
3080 if (z > z_ext) z = z_ext;
3081
3082 if (z == 0) {
3083 SetColour(GetPen(0), factor);
3084 return;
3085 }
3086
3087 assert(z_ext > 0.0);
3088 Double how_far = z / z_ext;
3089 assert(how_far >= 0.0);
3090 assert(how_far <= 1.0);
3091
3092 int band = int(floor(how_far * (GetNumColourBands() - 1)));
3093 GLAPen pen1 = GetPen(band);
3094 if (band < GetNumColourBands() - 1) {
3095 const GLAPen& pen2 = GetPen(band + 1);
3096
3097 Double interval = z_ext / (GetNumColourBands() - 1);
3098 Double into_band = z / interval - band;
3099
3100// printf("%g z_offset=%g interval=%g band=%d\n", into_band,
3101// z_offset, interval, band);
3102 // FIXME: why do we need to clamp here? Is it because the walls can
3103 // extend further up/down than the centre-line?
3104 if (into_band < 0.0) into_band = 0.0;
3105 if (into_band > 1.0) into_band = 1.0;
3106 assert(into_band >= 0.0);
3107 assert(into_band <= 1.0);
3108
3109 pen1.Interpolate(pen2, into_band);
3110 }
3111 SetColour(pen1, factor);
3112}
3113
3114void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
3115{
3116 SetDepthColour(v.GetZ(), factor);
3117 PlaceVertex(v);
3118}
3119
3120void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
3121 glaTexCoord tex_x, glaTexCoord tex_y,
3122 Double factor)
3123{
3124 SetDepthColour(v.GetZ(), factor);
3125 PlaceVertex(v, tex_x, tex_y);
3126}
3127
3128void GfxCore::SplitLineAcrossBands(int band, int band2,
3129 const Vector3 &p, const Vector3 &q,
3130 Double factor)
3131{
3132 const int step = (band < band2) ? 1 : -1;
3133 for (int i = band; i != band2; i += step) {
3134 const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3135
3136 // Find the intersection point of the line p -> q
3137 // with the plane parallel to the xy-plane with z-axis intersection z.
3138 assert(q.GetZ() - p.GetZ() != 0.0);
3139
3140 const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3141// assert(0.0 <= t && t <= 1.0); FIXME: rounding problems!
3142
3143 const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3144 const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3145
3146 PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
3147 }
3148}
3149
3150void GfxCore::SplitPolyAcrossBands(vector<vector<Split> >& splits,
3151 int band, int band2,
3152 const Vector3 &p, const Vector3 &q,
3153 glaTexCoord ptx, glaTexCoord pty,
3154 glaTexCoord w, glaTexCoord h)
3155{
3156 const int step = (band < band2) ? 1 : -1;
3157 for (int i = band; i != band2; i += step) {
3158 const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3159
3160 // Find the intersection point of the line p -> q
3161 // with the plane parallel to the xy-plane with z-axis intersection z.
3162 assert(q.GetZ() - p.GetZ() != 0.0);
3163
3164 const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3165// assert(0.0 <= t && t <= 1.0); FIXME: rounding problems!
3166
3167 const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3168 const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3169 glaTexCoord tx = ptx, ty = pty;
3170 if (w) tx += t * w;
3171 if (h) ty += t * h;
3172
3173 splits[i].push_back(Split(Vector3(x, y, z), tx, ty));
3174 splits[i + step].push_back(Split(Vector3(x, y, z), tx, ty));
3175 }
3176}
3177
3178int GfxCore::GetDepthColour(Double z) const
3179{
3180 // Return the (0-based) depth colour band index for a z-coordinate.
3181 Double z_ext = m_Parent->GetDepthExtent();
3182 z -= m_Parent->GetDepthMin();
3183 // We seem to get rounding differences causing z to sometimes be slightly
3184 // less than GetDepthMin() here, and it can certainly be true for passage
3185 // tubes, so just clamp the value to 0.
3186 if (z <= 0) return 0;
3187 // We seem to get rounding differences causing z to sometimes exceed z_ext
3188 // by a small amount here (see: https://trac.survex.com/ticket/26) and it
3189 // can certainly be true for passage tubes, so just clamp the value.
3190 if (z >= z_ext) return GetNumColourBands() - 1;
3191 return int(z / z_ext * (GetNumColourBands() - 1));
3192}
3193
3194Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
3195{
3196 // Return the z-coordinate of the depth colour boundary between
3197 // two adjacent depth colour bands (specified by 0-based indices).
3198
3199 assert((a == b - 1) || (a == b + 1));
3200 if (GetNumColourBands() == 1) return 0;
3201
3202 int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
3203 Double z_ext = m_Parent->GetDepthExtent();
3204 return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
3205}
3206
3207void GfxCore::AddPolyline(const traverse & centreline)
3208{
3209 BeginPolyline();
3210 SetColour(col_WHITE);
3211 vector<PointInfo>::const_iterator i = centreline.begin();
3212 PlaceVertex(*i);
3213 ++i;
3214 while (i != centreline.end()) {
3215 PlaceVertex(*i);
3216 ++i;
3217 }
3218 EndPolyline();
3219}
3220
3221void GfxCore::AddPolylineShadow(const traverse & centreline)
3222{
3223 BeginPolyline();
3224 const double z = -0.5 * m_Parent->GetExtent().GetZ();
3225 vector<PointInfo>::const_iterator i = centreline.begin();
3226 PlaceVertex(i->GetX(), i->GetY(), z);
3227 ++i;
3228 while (i != centreline.end()) {
3229 PlaceVertex(i->GetX(), i->GetY(), z);
3230 ++i;
3231 }
3232 EndPolyline();
3233}
3234
3235void GfxCore::AddPolylineDepth(const traverse & centreline)
3236{
3237 BeginPolyline();
3238 vector<PointInfo>::const_iterator i, prev_i;
3239 i = centreline.begin();
3240 int band0 = GetDepthColour(i->GetZ());
3241 PlaceVertexWithDepthColour(*i);
3242 prev_i = i;
3243 ++i;
3244 while (i != centreline.end()) {
3245 int band = GetDepthColour(i->GetZ());
3246 if (band != band0) {
3247 SplitLineAcrossBands(band0, band, *prev_i, *i);
3248 band0 = band;
3249 }
3250 PlaceVertexWithDepthColour(*i);
3251 prev_i = i;
3252 ++i;
3253 }
3254 EndPolyline();
3255}
3256
3257void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3258 const Vector3 &c, const Vector3 &d)
3259{
3260 Vector3 normal = (a - c) * (d - b);
3261 normal.normalise();
3262 Double factor = dot(normal, light) * .3 + .7;
3263 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3264 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3265 // FIXME: should plot triangles instead to avoid rendering glitches.
3266 BeginQuadrilaterals();
3267 PlaceVertexWithColour(a, 0, 0, factor);
3268 PlaceVertexWithColour(b, w, 0, factor);
3269 PlaceVertexWithColour(c, w, h, factor);
3270 PlaceVertexWithColour(d, 0, h, factor);
3271 EndQuadrilaterals();
3272}
3273
3274void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3275 const Vector3 &c, const Vector3 &d)
3276{
3277 Vector3 normal = (a - c) * (d - b);
3278 normal.normalise();
3279 Double factor = dot(normal, light) * .3 + .7;
3280 int a_band, b_band, c_band, d_band;
3281 a_band = GetDepthColour(a.GetZ());
3282 a_band = min(max(a_band, 0), GetNumColourBands());
3283 b_band = GetDepthColour(b.GetZ());
3284 b_band = min(max(b_band, 0), GetNumColourBands());
3285 c_band = GetDepthColour(c.GetZ());
3286 c_band = min(max(c_band, 0), GetNumColourBands());
3287 d_band = GetDepthColour(d.GetZ());
3288 d_band = min(max(d_band, 0), GetNumColourBands());
3289 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3290 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3291 int min_band = min(min(a_band, b_band), min(c_band, d_band));
3292 int max_band = max(max(a_band, b_band), max(c_band, d_band));
3293 if (min_band == max_band) {
3294 // Simple case - the polygon is entirely within one band.
3295 BeginPolygon();
3296//// PlaceNormal(normal);
3297 PlaceVertexWithDepthColour(a, 0, 0, factor);
3298 PlaceVertexWithDepthColour(b, w, 0, factor);
3299 PlaceVertexWithDepthColour(c, w, h, factor);
3300 PlaceVertexWithDepthColour(d, 0, h, factor);
3301 EndPolygon();
3302 } else {
3303 // We need to make a separate polygon for each depth band...
3304 vector<vector<Split> > splits;
3305 splits.resize(max_band + 1);
3306 splits[a_band].push_back(Split(a, 0, 0));
3307 if (a_band != b_band) {
3308 SplitPolyAcrossBands(splits, a_band, b_band, a, b, 0, 0, w, 0);
3309 }
3310 splits[b_band].push_back(Split(b, w, 0));
3311 if (b_band != c_band) {
3312 SplitPolyAcrossBands(splits, b_band, c_band, b, c, w, 0, 0, h);
3313 }
3314 splits[c_band].push_back(Split(c, w, h));
3315 if (c_band != d_band) {
3316 SplitPolyAcrossBands(splits, c_band, d_band, c, d, w, h, -w, 0);
3317 }
3318 splits[d_band].push_back(Split(d, 0, h));
3319 if (d_band != a_band) {
3320 SplitPolyAcrossBands(splits, d_band, a_band, d, a, 0, h, 0, -h);
3321 }
3322 for (int band = min_band; band <= max_band; ++band) {
3323 BeginPolygon();
3324 for (auto&& item : splits[band]) {
3325 PlaceVertexWithDepthColour(item.vec, item.tx, item.ty, factor);
3326 }
3327 EndPolygon();
3328 }
3329 }
3330}
3331
3332void GfxCore::SetColourFromDate(int date, Double factor)
3333{
3334 // Set the drawing colour based on a date.
3335
3336 if (date == -1) {
3337 // Undated.
3338 SetColour(NODATA_COLOUR, factor);
3339 return;
3340 }
3341
3342 int date_offset = date - m_Parent->GetDateMin();
3343 if (date_offset == 0) {
3344 // Earliest date - handle as a special case for the single date case.
3345 SetColour(GetPen(0), factor);
3346 return;
3347 }
3348
3349 int date_ext = m_Parent->GetDateExtent();
3350 Double how_far = (Double)date_offset / date_ext;
3351 assert(how_far >= 0.0);
3352 assert(how_far <= 1.0);
3353 SetColourFrom01(how_far, factor);
3354}
3355
3356void GfxCore::AddPolylineDate(const traverse & centreline)
3357{
3358 BeginPolyline();
3359 vector<PointInfo>::const_iterator i, prev_i;
3360 i = centreline.begin();
3361 int date = i->GetDate();
3362 SetColourFromDate(date, 1.0);
3363 PlaceVertex(*i);
3364 prev_i = i;
3365 while (++i != centreline.end()) {
3366 int newdate = i->GetDate();
3367 if (newdate != date) {
3368 EndPolyline();
3369 BeginPolyline();
3370 date = newdate;
3371 SetColourFromDate(date, 1.0);
3372 PlaceVertex(*prev_i);
3373 }
3374 PlaceVertex(*i);
3375 prev_i = i;
3376 }
3377 EndPolyline();
3378}
3379
3380static int static_date_hack; // FIXME
3381
3382void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3383 const Vector3 &c, const Vector3 &d)
3384{
3385 Vector3 normal = (a - c) * (d - b);
3386 normal.normalise();
3387 Double factor = dot(normal, light) * .3 + .7;
3388 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3389 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3390 // FIXME: should plot triangles instead to avoid rendering glitches.
3391 BeginQuadrilaterals();
3392//// PlaceNormal(normal);
3393 SetColourFromDate(static_date_hack, factor);
3394 PlaceVertex(a, 0, 0);
3395 PlaceVertex(b, w, 0);
3396 PlaceVertex(c, w, h);
3397 PlaceVertex(d, 0, h);
3398 EndQuadrilaterals();
3399}
3400
3401static double static_E_hack; // FIXME
3402
3403void GfxCore::SetColourFromError(double E, Double factor)
3404{
3405 // Set the drawing colour based on an error value.
3406
3407 if (E < 0) {
3408 SetColour(NODATA_COLOUR, factor);
3409 return;
3410 }
3411
3412 Double how_far = E / MAX_ERROR;
3413 assert(how_far >= 0.0);
3414 if (how_far > 1.0) how_far = 1.0;
3415 SetColourFrom01(how_far, factor);
3416}
3417
3418void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3419 const Vector3 &c, const Vector3 &d)
3420{
3421 Vector3 normal = (a - c) * (d - b);
3422 normal.normalise();
3423 Double factor = dot(normal, light) * .3 + .7;
3424 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3425 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3426 // FIXME: should plot triangles instead to avoid rendering glitches.
3427 BeginQuadrilaterals();
3428//// PlaceNormal(normal);
3429 SetColourFromError(static_E_hack, factor);
3430 PlaceVertex(a, 0, 0);
3431 PlaceVertex(b, w, 0);
3432 PlaceVertex(c, w, h);
3433 PlaceVertex(d, 0, h);
3434 EndQuadrilaterals();
3435}
3436
3437void GfxCore::AddPolylineError(const traverse & centreline)
3438{
3439 BeginPolyline();
3440 SetColourFromError(centreline.E, 1.0);
3441 vector<PointInfo>::const_iterator i;
3442 for(i = centreline.begin(); i != centreline.end(); ++i) {
3443 PlaceVertex(*i);
3444 }
3445 EndPolyline();
3446}
3447
3448// gradient is in *radians*.
3449void GfxCore::SetColourFromGradient(double gradient, Double factor)
3450{
3451 // Set the drawing colour based on the gradient of the leg.
3452
3453 const Double GRADIENT_MAX = M_PI_2;
3454 gradient = fabs(gradient);
3455 Double how_far = gradient / GRADIENT_MAX;
3456 SetColourFrom01(how_far, factor);
3457}
3458
3459void GfxCore::AddPolylineGradient(const traverse & centreline)
3460{
3461 vector<PointInfo>::const_iterator i, prev_i;
3462 i = centreline.begin();
3463 prev_i = i;
3464 while (++i != centreline.end()) {
3465 BeginPolyline();
3466 SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3467 PlaceVertex(*prev_i);
3468 PlaceVertex(*i);
3469 prev_i = i;
3470 EndPolyline();
3471 }
3472}
3473
3474static double static_gradient_hack; // FIXME
3475
3476void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3477 const Vector3 &c, const Vector3 &d)
3478{
3479 Vector3 normal = (a - c) * (d - b);
3480 normal.normalise();
3481 Double factor = dot(normal, light) * .3 + .7;
3482 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3483 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3484 // FIXME: should plot triangles instead to avoid rendering glitches.
3485 BeginQuadrilaterals();
3486//// PlaceNormal(normal);
3487 SetColourFromGradient(static_gradient_hack, factor);
3488 PlaceVertex(a, 0, 0);
3489 PlaceVertex(b, w, 0);
3490 PlaceVertex(c, w, h);
3491 PlaceVertex(d, 0, h);
3492 EndQuadrilaterals();
3493}
3494
3495void GfxCore::SetColourFromLength(double length, Double factor)
3496{
3497 // Set the drawing colour based on log(length_of_leg).
3498
3499 Double log_len = log10(length);
3500 Double how_far = log_len / LOG_LEN_MAX;
3501 how_far = max(how_far, 0.0);
3502 how_far = min(how_far, 1.0);
3503 SetColourFrom01(how_far, factor);
3504}
3505
3506void GfxCore::SetColourFrom01(double how_far, Double factor)
3507{
3508 double b;
3509 double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3510 int band(b);
3511 GLAPen pen1 = GetPen(band);
3512 // With 24bit colour, interpolating by less than this can have no effect.
3513 if (into_band >= 1.0 / 512.0) {
3514 const GLAPen& pen2 = GetPen(band + 1);
3515 pen1.Interpolate(pen2, into_band);
3516 }
3517 SetColour(pen1, factor);
3518}
3519
3520void GfxCore::AddPolylineLength(const traverse & centreline)
3521{
3522 vector<PointInfo>::const_iterator i, prev_i;
3523 i = centreline.begin();
3524 prev_i = i;
3525 while (++i != centreline.end()) {
3526 BeginPolyline();
3527 SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3528 PlaceVertex(*prev_i);
3529 PlaceVertex(*i);
3530 prev_i = i;
3531 EndPolyline();
3532 }
3533}
3534
3535static double static_length_hack; // FIXME
3536
3537void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3538 const Vector3 &c, const Vector3 &d)
3539{
3540 Vector3 normal = (a - c) * (d - b);
3541 normal.normalise();
3542 Double factor = dot(normal, light) * .3 + .7;
3543 glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3544 glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3545 // FIXME: should plot triangles instead to avoid rendering glitches.
3546 BeginQuadrilaterals();
3547//// PlaceNormal(normal);
3548 SetColourFromLength(static_length_hack, factor);
3549 PlaceVertex(a, 0, 0);
3550 PlaceVertex(b, w, 0);
3551 PlaceVertex(c, w, h);
3552 PlaceVertex(d, 0, h);
3553 EndQuadrilaterals();
3554}
3555
3556void
3557GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3558{
3559 const SurveyFilter* filter = m_Parent->GetTreeFilter();
3560 assert(centreline.size() > 1);
3561 Vector3 U[4];
3562 XSect* prev_pt_v = NULL;
3563 Vector3 last_right(1.0, 0.0, 0.0);
3564
3565// FIXME: it's not simple to set the colour of a tube based on error...
3566// static_E_hack = something...
3567 vector<XSect>::iterator i = centreline.begin();
3568 vector<XSect>::size_type segment = 0;
3569 while (i != centreline.end()) {
3570 // get the coordinates of this vertex
3571 XSect & pt_v = *i++;
3572
3573 bool cover_end = false;
3574
3575 Vector3 right, up;
3576
3577 const Vector3 up_v(0.0, 0.0, 1.0);
3578
3579 if (segment == 0) {
3580 assert(i != centreline.end());
3581 // first segment
3582
3583 // get the coordinates of the next vertex
3584 const XSect & next_pt_v = *i;
3585
3586 // calculate vector from this pt to the next one
3587 Vector3 leg_v = next_pt_v - pt_v;
3588
3589 // obtain a vector in the LRUD plane
3590 right = leg_v * up_v;
3591 if (right.magnitude() == 0) {
3592 right = last_right;
3593 // Obtain a second vector in the LRUD plane,
3594 // perpendicular to the first.
3595 //up = right * leg_v;
3596 up = up_v;
3597 } else {
3598 last_right = right;
3599 up = up_v;
3600 }
3601
3602 cover_end = true;
3603 static_date_hack = next_pt_v.GetDate();
3604 } else if (segment + 1 == centreline.size()) {
3605 // last segment
3606
3607 // Calculate vector from the previous pt to this one.
3608 Vector3 leg_v = pt_v - *prev_pt_v;
3609
3610 // Obtain a horizontal vector in the LRUD plane.
3611 right = leg_v * up_v;
3612 if (right.magnitude() == 0) {
3613 right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3614 // Obtain a second vector in the LRUD plane,
3615 // perpendicular to the first.
3616 //up = right * leg_v;
3617 up = up_v;
3618 } else {
3619 last_right = right;
3620 up = up_v;
3621 }
3622
3623 cover_end = true;
3624 static_date_hack = pt_v.GetDate();
3625 } else {
3626 assert(i != centreline.end());
3627 // Intermediate segment.
3628
3629 // Get the coordinates of the next vertex.
3630 const XSect & next_pt_v = *i;
3631
3632 // Calculate vectors from this vertex to the
3633 // next vertex, and from the previous vertex to
3634 // this one.
3635 Vector3 leg1_v = pt_v - *prev_pt_v;
3636 Vector3 leg2_v = next_pt_v - pt_v;
3637
3638 // Obtain horizontal vectors perpendicular to
3639 // both legs, then normalise and average to get
3640 // a horizontal bisector.
3641 Vector3 r1 = leg1_v * up_v;
3642 Vector3 r2 = leg2_v * up_v;
3643 r1.normalise();
3644 r2.normalise();
3645 right = r1 + r2;
3646 if (right.magnitude() == 0) {
3647 // This is the "mid-pitch" case...
3648 right = last_right;
3649 }
3650 if (r1.magnitude() == 0) {
3651 up = up_v;
3652
3653 // Rotate pitch section to minimise the
3654 // "tortional stress" - FIXME: use
3655 // triangles instead of rectangles?
3656 int shift = 0;
3657 Double maxdotp = 0;
3658
3659 // Scale to unit vectors in the LRUD plane.
3660 right.normalise();
3661 up.normalise();
3662 Vector3 vec = up - right;
3663 for (int orient = 0; orient <= 3; ++orient) {
3664 Vector3 tmp = U[orient] - prev_pt_v->GetPoint();
3665 tmp.normalise();
3666 Double dotp = dot(vec, tmp);
3667 if (dotp > maxdotp) {
3668 maxdotp = dotp;
3669 shift = orient;
3670 }
3671 }
3672 if (shift) {
3673 if (shift != 2) {
3674 Vector3 temp(U[0]);
3675 U[0] = U[shift];
3676 U[shift] = U[2];
3677 U[2] = U[shift ^ 2];
3678 U[shift ^ 2] = temp;
3679 } else {
3680 swap(U[0], U[2]);
3681 swap(U[1], U[3]);
3682 }
3683 }
3684#if 0
3685 // Check that the above code actually permuted
3686 // the vertices correctly.
3687 shift = 0;
3688 maxdotp = 0;
3689 for (int j = 0; j <= 3; ++j) {
3690 Vector3 tmp = U[j] - *prev_pt_v;
3691 tmp.normalise();
3692 Double dotp = dot(vec, tmp);
3693 if (dotp > maxdotp) {
3694 maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3695 shift = j;
3696 }
3697 }
3698 if (shift) {
3699 printf("New shift = %d!\n", shift);
3700 shift = 0;
3701 maxdotp = 0;
3702 for (int j = 0; j <= 3; ++j) {
3703 Vector3 tmp = U[j] - *prev_pt_v;
3704 tmp.normalise();
3705 Double dotp = dot(vec, tmp);
3706 printf(" %d : %.8f\n", j, dotp);
3707 }
3708 }
3709#endif
3710 } else {
3711 up = up_v;
3712 }
3713 last_right = right;
3714 static_date_hack = pt_v.GetDate();
3715 }
3716
3717 // Scale to unit vectors in the LRUD plane.
3718 right.normalise();
3719 up.normalise();
3720
3721 Double l = fabs(pt_v.GetL());
3722 Double r = fabs(pt_v.GetR());
3723 Double u = fabs(pt_v.GetU());
3724 Double d = fabs(pt_v.GetD());
3725
3726 // Produce coordinates of the corners of the LRUD "plane".
3727 Vector3 v[4];
3728 v[0] = pt_v.GetPoint() - right * l + up * u;
3729 v[1] = pt_v.GetPoint() + right * r + up * u;
3730 v[2] = pt_v.GetPoint() + right * r - up * d;
3731 v[3] = pt_v.GetPoint() - right * l - up * d;
3732
3733 if (draw) {
3734 if (segment > 0) {
3735 if (!filter || (filter->CheckVisible(pt_v.GetLabel()) &&
3736 filter->CheckVisible(prev_pt_v->GetLabel()))) {
3737 const Vector3 & delta = pt_v - *prev_pt_v;
3738 static_length_hack = delta.magnitude();
3739 static_gradient_hack = delta.gradient();
3740 (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3741 (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3742 (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3743 (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3744 }
3745 }
3746
3747 if (cover_end) {
3748 if (!filter || filter->CheckVisible(pt_v.GetLabel())) {
3749 if (segment == 0) {
3750 (this->*AddQuad)(v[0], v[1], v[2], v[3]);
3751 } else {
3752 (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3753 }
3754 }
3755 }
3756 }
3757
3758 prev_pt_v = &pt_v;
3759 U[0] = v[0];
3760 U[1] = v[1];
3761 U[2] = v[2];
3762 U[3] = v[3];
3763
3764 pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3765
3766 ++segment;
3767 }
3768}
3769
3770void GfxCore::FullScreenMode()
3771{
3772 m_Parent->ViewFullScreen();
3773}
3774
3775bool GfxCore::IsFullScreen() const
3776{
3777 return m_Parent->IsFullScreen();
3778}
3779
3780bool GfxCore::FullScreenModeShowingMenus() const
3781{
3782 return m_Parent->FullScreenModeShowingMenus();
3783}
3784
3785void GfxCore::FullScreenModeShowMenus(bool show)
3786{
3787 m_Parent->FullScreenModeShowMenus(show);
3788}
3789
3790void
3791GfxCore::MoveViewer(double forward, double up, double right)
3792{
3793 double cT = cos(rad(m_TiltAngle));
3794 double sT = sin(rad(m_TiltAngle));
3795 double cP = cos(rad(m_PanAngle));
3796 double sP = sin(rad(m_PanAngle));
3797 Vector3 v_forward(cT * sP, cT * cP, sT);
3798 Vector3 v_up(sT * sP, sT * cP, -cT);
3799 Vector3 v_right(-cP, sP, 0);
3800 assert(fabs(dot(v_forward, v_up)) < 1e-6);
3801 assert(fabs(dot(v_forward, v_right)) < 1e-6);
3802 assert(fabs(dot(v_right, v_up)) < 1e-6);
3803 Vector3 move = v_forward * forward + v_up * up + v_right * right;
3804 AddTranslation(-move);
3805 // Show current position.
3806 m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3807 ForceRefresh();
3808}
3809
3810PresentationMark GfxCore::GetView() const
3811{
3812 return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3813 m_PanAngle, -m_TiltAngle, m_Scale);
3814}
3815
3816void GfxCore::SetView(const PresentationMark & p)
3817{
3818 m_SwitchingTo = 0;
3819 SetTranslation(p - m_Parent->GetOffset());
3820 m_PanAngle = p.angle;
3821 m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3822 SetRotation(m_PanAngle, m_TiltAngle);
3823 SetScale(p.scale);
3824 ForceRefresh();
3825}
3826
3827void GfxCore::PlayPres(double speed, bool change_speed) {
3828 if (!change_speed || presentation_mode == 0) {
3829 if (speed == 0.0) {
3830 presentation_mode = 0;
3831 return;
3832 }
3833 presentation_mode = PLAYING;
3834 next_mark = m_Parent->GetPresMark(MARK_FIRST);
3835 SetView(next_mark);
3836 next_mark_time = 0; // There already!
3837 this_mark_total = 0;
3838 pres_reverse = (speed < 0);
3839 }
3840
3841 if (change_speed) pres_speed = speed;
3842
3843 if (speed != 0.0) {
3844 bool new_pres_reverse = (speed < 0);
3845 if (new_pres_reverse != pres_reverse) {
3846 pres_reverse = new_pres_reverse;
3847 if (pres_reverse) {
3848 next_mark = m_Parent->GetPresMark(MARK_PREV);
3849 } else {
3850 next_mark = m_Parent->GetPresMark(MARK_NEXT);
3851 }
3852 swap(this_mark_total, next_mark_time);
3853 }
3854 }
3855}
3856
3857void GfxCore::SetColourBy(int colour_by) {
3858 m_ColourBy = colour_by;
3859 switch (colour_by) {
3860 case COLOUR_BY_DEPTH:
3861 AddQuad = &GfxCore::AddQuadrilateralDepth;
3862 AddPoly = &GfxCore::AddPolylineDepth;
3863 break;
3864 case COLOUR_BY_DATE:
3865 AddQuad = &GfxCore::AddQuadrilateralDate;
3866 AddPoly = &GfxCore::AddPolylineDate;
3867 break;
3868 case COLOUR_BY_ERROR:
3869 AddQuad = &GfxCore::AddQuadrilateralError;
3870 AddPoly = &GfxCore::AddPolylineError;
3871 break;
3872 case COLOUR_BY_GRADIENT:
3873 AddQuad = &GfxCore::AddQuadrilateralGradient;
3874 AddPoly = &GfxCore::AddPolylineGradient;
3875 break;
3876 case COLOUR_BY_LENGTH:
3877 AddQuad = &GfxCore::AddQuadrilateralLength;
3878 AddPoly = &GfxCore::AddPolylineLength;
3879 break;
3880 default: // case COLOUR_BY_NONE:
3881 AddQuad = &GfxCore::AddQuadrilateral;
3882 AddPoly = &GfxCore::AddPolyline;
3883 break;
3884 }
3885
3886 InvalidateList(LIST_UNDERGROUND_LEGS);
3887 InvalidateList(LIST_SURFACE_LEGS);
3888 InvalidateList(LIST_TUBES);
3889
3890 ForceRefresh();
3891}
3892
3893bool GfxCore::ExportMovie(const wxString & fnm)
3894{
3895 FILE* fh = wxFopen(fnm.fn_str(), wxT("wb"));
3896 if (fh == NULL) {
3897 wxGetApp().ReportError(wxString::Format(wmsg(/*Failed to open output file “%s”*/47), fnm.c_str()));
3898 return false;
3899 }
3900
3901 wxString ext;
3902 wxFileName::SplitPath(fnm, NULL, NULL, NULL, &ext, wxPATH_NATIVE);
3903
3904 int width;
3905 int height;
3906 GetSize(&width, &height);
3907 // Round up to next multiple of 2 (required by ffmpeg).
3908 width += (width & 1);
3909 height += (height & 1);
3910
3911 movie = new MovieMaker();
3912
3913 // movie takes ownership of fh.
3914 if (!movie->Open(fh, ext.utf8_str(), width, height)) {
3915 wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3916 delete movie;
3917 movie = NULL;
3918 return false;
3919 }
3920
3921 PlayPres(1);
3922 return true;
3923}
3924
3925void
3926GfxCore::OnPrint(const wxString &filename, const wxString &title,
3927 const wxString &datestamp,
3928 bool close_after_print)
3929{
3930 svxPrintDlg * p;
3931 p = new svxPrintDlg(m_Parent, filename, title, datestamp,
3932 m_PanAngle, m_TiltAngle,
3933 m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
3934 m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
3935 true, close_after_print);
3936 p->Show(true);
3937}
3938
3939void
3940GfxCore::OnExport(const wxString &filename, const wxString &title,
3941 const wxString &datestamp)
3942{
3943 // Fill in "right_bearing" for each cross-section.
3944 list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3945 list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3946 while (trav != tend) {
3947 SkinPassage(*trav, false);
3948 ++trav;
3949 }
3950
3951 svxPrintDlg * p;
3952 p = new svxPrintDlg(m_Parent, filename, title, datestamp,
3953 m_PanAngle, m_TiltAngle,
3954 m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
3955 m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
3956 false);
3957 p->Show(true);
3958}
3959
3960static wxCursor
3961make_cursor(const unsigned char * bits, const unsigned char * mask,
3962 int hotx, int hoty)
3963{
3964#if defined __WXGTK__ && !defined __WXGTK3__
3965 // Use this code for GTK < 3 only - it doesn't work properly with GTK3
3966 // (reported and should be fixed in wxWidgets 3.0.4 and 3.1.1, see:
3967 // https://trac.wxwidgets.org/ticket/17916)
3968 return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3969 (const char *)mask, wxBLACK, wxWHITE);
3970#else
3971# ifdef __WXMAC__
3972 // The default Mac cursor is black with a white edge, so
3973 // invert our custom cursors to match.
3974 char b[128];
3975 for (int i = 0; i < 128; ++i)
3976 b[i] = bits[i] ^ 0xff;
3977# else
3978 const char * b = reinterpret_cast<const char *>(bits);
3979# endif
3980 wxBitmap cursor_bitmap(b, 32, 32);
3981 wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3982 cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3983 wxImage cursor_image = cursor_bitmap.ConvertToImage();
3984 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3985 cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3986 return wxCursor(cursor_image);
3987#endif
3988}
3989
3990const
3991#include "hand.xbm"
3992const
3993#include "handmask.xbm"
3994
3995const
3996#include "brotate.xbm"
3997const
3998#include "brotatemask.xbm"
3999
4000const
4001#include "vrotate.xbm"
4002const
4003#include "vrotatemask.xbm"
4004
4005const
4006#include "rotate.xbm"
4007const
4008#include "rotatemask.xbm"
4009
4010const
4011#include "rotatezoom.xbm"
4012const
4013#include "rotatezoommask.xbm"
4014
4015void
4016GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
4017{
4018 // Check if we're already showing that cursor.
4019 if (current_cursor == new_cursor) return;
4020
4021 current_cursor = new_cursor;
4022 switch (current_cursor) {
4023 case GfxCore::CURSOR_DEFAULT:
4024 GLACanvas::SetCursor(wxNullCursor);
4025 break;
4026 case GfxCore::CURSOR_POINTING_HAND:
4027 GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
4028 break;
4029 case GfxCore::CURSOR_DRAGGING_HAND:
4030 GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
4031 break;
4032 case GfxCore::CURSOR_HORIZONTAL_RESIZE:
4033 GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
4034 break;
4035 case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
4036 GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
4037 break;
4038 case GfxCore::CURSOR_ROTATE_VERTICALLY:
4039 GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
4040 break;
4041 case GfxCore::CURSOR_ROTATE_EITHER_WAY:
4042 GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
4043 break;
4044 case GfxCore::CURSOR_ZOOM:
4045 GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
4046 break;
4047 case GfxCore::CURSOR_ZOOM_ROTATE:
4048 GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
4049 break;
4050 }
4051}
4052
4053bool GfxCore::MeasuringLineActive() const
4054{
4055 if (Animating()) return false;
4056 return HereIsReal() || m_there;
4057}
4058
4059bool GfxCore::HandleRClick(wxPoint point)
4060{
4061 if (PointWithinCompass(point)) {
4062 // Pop up menu.
4063 wxMenu menu;
4064 /* TRANSLATORS: View *looking* North */
4065 menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
4066 /* TRANSLATORS: View *looking* East */
4067 menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
4068 /* TRANSLATORS: View *looking* South */
4069 menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
4070 /* TRANSLATORS: View *looking* West */
4071 menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
4072 menu.AppendSeparator();
4073 /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
4074 menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
4075 /* TRANSLATORS: tickable menu item in View menu.
4076 *
4077 * Degrees are the angular measurement where there are 360 in a full
4078 * circle. */
4079 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4080 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4081 PopupMenu(&menu);
4082 return true;
4083 }
4084
4085 if (PointWithinClino(point)) {
4086 // Pop up menu.
4087 wxMenu menu;
4088 menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
4089 menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
4090 menu.AppendSeparator();
4091 /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
4092 menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
4093 /* TRANSLATORS: tickable menu item in View menu.
4094 *
4095 * Degrees are the angular measurement where there are 360 in a full
4096 * circle. */
4097 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4098 /* TRANSLATORS: tickable menu item in View menu.
4099 *
4100 * Show the tilt of the survey as a percentage gradient (100% = 45
4101 * degrees = 50 grad). */
4102 menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
4103 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4104 PopupMenu(&menu);
4105 return true;
4106 }
4107
4108 if (PointWithinScaleBar(point)) {
4109 // Pop up menu.
4110 wxMenu menu;
4111 /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
4112 menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
4113 /* TRANSLATORS: tickable menu item in View menu.
4114 *
4115 * "Metric" here means metres, km, etc (rather than feet, miles, etc)
4116 */
4117 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4118 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4119 PopupMenu(&menu);
4120 return true;
4121 }
4122
4123 if (PointWithinColourKey(point)) {
4124 // Pop up menu.
4125 wxMenu menu;
4126 menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
4127 menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
4128 menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
4129 menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
4130 menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
4131 menu.AppendSeparator();
4132 /* TRANSLATORS: Menu item which turns off the colour key.
4133 * The "Colour Key" is the thing in aven showing which colour
4134 * corresponds to which depth, date, survey closure error, etc. */
4135 menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
4136 if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
4137 menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4138 else if (m_ColourBy == COLOUR_BY_GRADIENT)
4139 menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4140 menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4141 PopupMenu(&menu);
4142 return true;
4143 }
4144
4145 return false;
4146}
4147
4148void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
4149{
4150 if (centred) {
4151 p1.x = p2.x + (p1.x - p2.x) * 2;
4152 p1.y = p2.y + (p1.y - p2.y) * 2;
4153 }
4154 if (aspect) {
4155#if 0 // FIXME: This needs more work.
4156 int sx = GetXSize();
4157 int sy = GetYSize();
4158 int dx = p1.x - p2.x;
4159 int dy = p1.y - p2.y;
4160 int dy_new = dx * sy / sx;
4161 if (abs(dy_new) >= abs(dy)) {
4162 p1.y += (dy_new - dy) / 2;
4163 p2.y -= (dy_new - dy) / 2;
4164 } else {
4165 int dx_new = dy * sx / sy;
4166 p1.x += (dx_new - dx) / 2;
4167 p2.x -= (dx_new - dx) / 2;
4168 }
4169#endif
4170 }
4171 zoombox.set(p1, p2);
4172 ForceRefresh();
4173}
4174
4175void GfxCore::ZoomBoxGo()
4176{
4177 if (!zoombox.active()) return;
4178
4179 int width = GetXSize();
4180 int height = GetYSize();
4181
4182 TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
4183 -0.5 * (zoombox.y1 + zoombox.y2 - height));
4184 int box_w = abs(zoombox.x1 - zoombox.x2);
4185 int box_h = abs(zoombox.y1 - zoombox.y2);
4186
4187 double factor = min(double(width) / box_w, double(height) / box_h);
4188
4189 zoombox.unset();
4190
4191 SetScale(GetScale() * factor);
4192}
Note: See TracBrowser for help on using the repository browser.