source: git/src/gfxcore.cc @ 5fc8d1f

Last change on this file since 5fc8d1f was 5fc8d1f, checked in by Olly Betts <olly@…>, 11 years ago

Splay legs display patch from Mateusz

  • Property mode set to 100644
File size: 80.2 KB
RevLine 
[5809313]1//
[156dc16]2//  gfxcore.cc
[5809313]3//
[33b2094]4//  Core drawing code for Aven.
[5809313]5//
[b72f4b5]6//  Copyright (C) 2000-2003,2005,2006 Mark R. Shinwell
[6e0c5879]7//  Copyright (C) 2001-2003,2004,2005,2006,2007,2010,2011,2012 Olly Betts
[887c26e]8//  Copyright (C) 2005 Martin Green
[5809313]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
[5940815]22//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
[5809313]23//
24
[cbfa50d]25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
[892a40c]29#include <assert.h>
[7aa15c0]30#include <float.h>
31
[7a89dc2]32#include "aven.h"
[1ee204e]33#include "date.h"
[5809313]34#include "gfxcore.h"
[137bf99]35#include "mainfrm.h"
[93c3f97]36#include "message.h"
[7a89dc2]37#include "useful.h"
[ce403f1]38#include "printwx.h"
[5876fcb]39#include "guicontrol.h"
[6a4cdcb6]40#include "moviemaker.h"
[8000d8f]41
42#include <wx/confbase.h>
43#include <wx/image.h>
[5809313]44
[db4b33c]45#define MAX(a, b) ((a) > (b) ? (a) : (b))
[003d953]46#define MAX3(a, b, c) ((a) > (b) ? MAX(a, c) : MAX(b, c))
[5809313]47
[3d00693]48// Values for m_SwitchingTo
49#define PLAN 1
50#define ELEVATION 2
[3ddd351]51#define NORTH 3
52#define EAST 4
53#define SOUTH 5
54#define WEST 6
[3d00693]55
[c61aa79]56// Any error value higher than this is clamped to this.
57#define MAX_ERROR 12.0
58
[86cdcf2]59// How many bins per letter height to use when working out non-overlapping
60// labels.
61const unsigned int QUANTISE_FACTOR = 2;
62
[0e69efe]63#include "avenpal.h"
64
[6606406]65static const int COMPASS_OFFSET_X = 60;
66static const int COMPASS_OFFSET_Y = 80;
67static const int INDICATOR_BOX_SIZE = 60;
[c300a04]68static const int INDICATOR_GAP = 2;
[6606406]69static const int INDICATOR_MARGIN = 5;
70static const int INDICATOR_OFFSET_X = 15;
[c300a04]71static const int INDICATOR_OFFSET_Y = 15;
[fe665c4]72static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
[dde4fe7]73static const int CLINO_OFFSET_X = 6 + INDICATOR_OFFSET_X +
[429465a]74                                  INDICATOR_BOX_SIZE + INDICATOR_GAP;
[62da267]75static const int KEY_OFFSET_X = 10;
76static const int KEY_OFFSET_Y = 10;
77static const int KEY_EXTRA_LEFT_MARGIN = 2;
78static const int KEY_BLOCK_WIDTH = 20;
79static const int KEY_BLOCK_HEIGHT = 16;
[b56df45]80static const int TICK_LENGTH = 4;
[42adb19]81static const int SCALE_BAR_OFFSET_X = 15;
82static const int SCALE_BAR_OFFSET_Y = 12;
83static const int SCALE_BAR_HEIGHT = 12;
[aa048c3]84
85static const gla_colour TEXT_COLOUR = col_GREEN;
86static const gla_colour HERE_COLOUR = col_WHITE;
87static const gla_colour NAME_COLOUR = col_GREEN;
[33b2094]88
[39e460c9]89#define HITTEST_SIZE 20
90
[dde4fe7]91// vector for lighting angle
92static const Vector3 light(.577, .577, .577);
93
[9071cf5]94BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
[5809313]95    EVT_PAINT(GfxCore::OnPaint)
96    EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
97    EVT_LEFT_UP(GfxCore::OnLButtonUp)
98    EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
99    EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
100    EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
101    EVT_RIGHT_UP(GfxCore::OnRButtonUp)
[34d8d1a]102    EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
[5809313]103    EVT_MOTION(GfxCore::OnMouseMove)
[887c26e]104    EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
[5809313]105    EVT_SIZE(GfxCore::OnSize)
[a8e9fde]106    EVT_IDLE(GfxCore::OnIdle)
[4b1fc48]107    EVT_CHAR(GfxCore::OnKeyPress)
[5809313]108END_EVENT_TABLE()
109
[5876fcb]110GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
[88707e0b]111    GLACanvas(parent_win, 100),
112    m_Scale(0.0),
113    m_ScaleBarWidth(0),
114    m_Control(control),
115    m_LabelGrid(NULL),
116    m_Parent(parent),
117    m_DoneFirstShow(false),
118    m_TiltAngle(0.0),
119    m_PanAngle(0.0),
120    m_Rotating(false),
121    m_RotationStep(0.0),
122    m_SwitchingTo(0),
123    m_Crosses(false),
124    m_Legs(true),
[5fc8d1f]125    m_Splays(SPLAYS_SHOW_FADED),
[88707e0b]126    m_Names(false),
127    m_Scalebar(true),
[97ea48d]128    m_ColourKey(true),
[88707e0b]129    m_OverlappingNames(false),
130    m_Compass(true),
131    m_Clino(true),
132    m_Tubes(false),
133    m_ColourBy(COLOUR_BY_DEPTH),
134    m_HaveData(false),
135    m_MouseOutsideCompass(false),
136    m_MouseOutsideElev(false),
137    m_Surface(false),
138    m_Entrances(false),
139    m_FixedPts(false),
140    m_ExportedPts(false),
141    m_Grid(false),
142    m_BoundingBox(false),
143    m_Degrees(false),
144    m_Metric(false),
145    m_HitTestGridValid(false),
146    m_here_is_temporary(false),
147    presentation_mode(0),
148    pres_reverse(false),
149    pres_speed(0.0),
[75d4a2b]150    movie(NULL),
[88707e0b]151    current_cursor(GfxCore::CURSOR_DEFAULT)
[5809313]152{
[da6c802]153    AddQuad = &GfxCore::AddQuadrilateralDepth;
154    AddPoly = &GfxCore::AddPolylineDepth;
[5627cbb]155    wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
156    wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
[d67450e]157    m_here.Invalidate();
158    m_there.Invalidate();
[5809313]159
[39e460c9]160    // Initialise grid for hit testing.
[fa42426]161    m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
[0e69efe]162
[5fc8d1f]163    m_HalfPens = new GLAPen[NUM_COLOUR_BANDS + 1];
164    m_FullPens = new GLAPen[NUM_COLOUR_BANDS + 1];
[97ea48d]165    for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
[5fc8d1f]166        m_HalfPens[pen].SetColour(REDS[pen] / 255.0 / 4.0,
167                              GREENS[pen] / 255.0 / 4.0,
168                              BLUES[pen] / 255.0 / 4.0);
169        m_FullPens[pen].SetColour(REDS[pen] / 255.0,
[0e69efe]170                              GREENS[pen] / 255.0,
171                              BLUES[pen] / 255.0);
172    }
[5fc8d1f]173    m_Pens = m_FullPens;
[5809313]174}
175
176GfxCore::~GfxCore()
177{
178    TryToFreeArrays();
[156dc16]179
[5fc8d1f]180    delete[] m_HalfPens;
181    delete[] m_FullPens;
[39e460c9]182    delete[] m_PointGrid;
[5809313]183}
184
185void GfxCore::TryToFreeArrays()
186{
187    // Free up any memory allocated for arrays.
[81f1266]188    delete[] m_LabelGrid;
189    m_LabelGrid = NULL;
[5809313]190}
191
192//
193//  Initialisation methods
194//
195
[0c6bf5e8]196void GfxCore::Initialise(bool same_file)
[5809313]197{
198    // Initialise the view from the parent holding the survey data.
199
200    TryToFreeArrays();
201
[33b2094]202    m_DoneFirstShow = false;
203
[dfe4454c]204    m_HitTestGridValid = false;
[d35144d]205    m_here_is_temporary = true;
[d67450e]206    m_here.Invalidate();
207    m_there.Invalidate();
[dfe4454c]208
[d35144d]209    m_MouseOutsideCompass = m_MouseOutsideElev = false;
210
[0c6bf5e8]211    if (!same_file) {
212        // Apply default parameters unless reloading the same file.
213        DefaultParameters();
214
215        // Set the initial scale.
216        SetScale(1.0);
217    }
[9eb58d0]218
219    m_HaveData = true;
[936a197]220
[92cf7a8]221    // Clear any cached OpenGL lists which depend on the data.
222    InvalidateList(LIST_SCALE_BAR);
223    InvalidateList(LIST_DEPTH_KEY);
224    InvalidateList(LIST_DATE_KEY);
225    InvalidateList(LIST_ERROR_KEY);
226    InvalidateList(LIST_UNDERGROUND_LEGS);
227    InvalidateList(LIST_TUBES);
228    InvalidateList(LIST_SURFACE_LEGS);
229    InvalidateList(LIST_BLOBS);
230    InvalidateList(LIST_CROSSES);
231    InvalidateList(LIST_GRID);
232    InvalidateList(LIST_SHADOW);
233
[936a197]234    ForceRefresh();
[9eb58d0]235}
236
237void GfxCore::FirstShow()
238{
239    GLACanvas::FirstShow();
240
[8bd480e]241    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
[86cdcf2]242    list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
243    while (pos != m_Parent->GetLabelsNCEnd()) {
244        LabelInfo* label = *pos++;
245        // Calculate and set the label width for use when plotting
246        // none-overlapping labels.
247        int ext_x;
248        GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
[5a24583]249        label->set_width(unsigned(ext_x) / quantise + 1);
[86cdcf2]250    }
251
[c5fc8eb]252    // Set diameter of the viewing volume.
253    SetVolumeDiameter(sqrt(sqrd(m_Parent->GetXExtent()) +
254                           sqrd(m_Parent->GetYExtent()) +
255                           sqrd(m_Parent->GetZExtent())));
[9eb58d0]256
[5809313]257    m_DoneFirstShow = true;
258}
259
260//
261//  Recalculating methods
262//
263
[cd6ea75]264void GfxCore::SetScale(Double scale)
[5047c53]265{
[8b0d57f]266    if (scale < 0.05) {
267        scale = 0.05;
[70acad9]268    } else if (scale > GetVolumeDiameter()) {
269        scale = GetVolumeDiameter();
[5047c53]270    }
271
[5b7164d]272    m_Scale = scale;
[00a68e0]273    m_HitTestGridValid = false;
[c00c6713]274    if (m_here_is_temporary) SetHere();
[33b2094]275
276    GLACanvas::SetScale(scale);
[d9b3270]277}
278
[f433fda]279bool GfxCore::HasUndergroundLegs() const
280{
281    return m_Parent->HasUndergroundLegs();
282}
283
[e4f82db]284bool GfxCore::HasSplays() const
285{
286    return m_Parent->HasSplays();
287}
288
[f433fda]289bool GfxCore::HasSurfaceLegs() const
290{
291    return m_Parent->HasSurfaceLegs();
292}
293
[50e8979]294bool GfxCore::HasTubes() const
295{
296    return m_Parent->HasTubes();
297}
298
[d9b3270]299void GfxCore::UpdateBlobs()
300{
[d2fcc9b]301    InvalidateList(LIST_BLOBS);
[33b2094]302}
303
[cd6ea75]304//
[5876fcb]305//  Event handlers
[cd6ea75]306//
[5047c53]307
[41f7a27]308void GfxCore::OnLeaveWindow(wxMouseEvent&) {
[887c26e]309    SetHere();
310    ClearCoords();
311}
312
[5876fcb]313void GfxCore::OnIdle(wxIdleEvent& event)
314{
315    // Handle an idle event.
[b72f4b5]316    if (Animate()) {
317        ForceRefresh();
318        event.RequestMore();
319    }
[5809313]320}
321
[b4fe9fb]322void GfxCore::OnPaint(wxPaintEvent&)
[5809313]323{
324    // Redraw the window.
[b462168]325
326    // Get a graphics context.
[1b12b82]327    wxPaintDC dc(this);
[5809313]328
[815eab2]329    if (m_HaveData) {
[01d91fd]330        // Make sure we're initialised.
331        bool first_time = !m_DoneFirstShow;
332        if (first_time) {
333            FirstShow();
334        }
335
[58dfdd21]336        StartDrawing();
337
338        // Clear the background.
339        Clear();
340
[429465a]341        // Set up model transformation matrix.
342        SetDataTransform();
343
[9eb58d0]344        timer.Start(); // reset timer
[203d2a7]345
[429465a]346        if (m_Legs || m_Tubes) {
347            if (m_Tubes) {
[d67450e]348                EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
[d2fcc9b]349                DrawList(LIST_TUBES);
[429465a]350                DisableSmoothPolygons();
351            }
[e4d40792]352
[50e8979]353            // Draw the underground legs.  Do this last so that anti-aliasing
[e4d40792]354            // works over polygons.
355            SetColour(col_GREEN);
[d2fcc9b]356            DrawList(LIST_UNDERGROUND_LEGS);
[429465a]357        }
[33b2094]358
[429465a]359        if (m_Surface) {
360            // Draw the surface legs.
[d2fcc9b]361            DrawList(LIST_SURFACE_LEGS);
[429465a]362        }
[bbc22ca]363
[f4c5932]364        if (m_BoundingBox) {
365            DrawShadowedBoundingBox();
366        }
[429465a]367        if (m_Grid) {
368            // Draw the grid.
[37d7084]369            DrawList(LIST_GRID);
[429465a]370        }
[b13aee4]371
[d2cc100]372        DrawList(LIST_BLOBS);
373
[86fe6e4]374        if (m_Crosses) {
375            DrawList(LIST_CROSSES);
376        }
377
[429465a]378        SetIndicatorTransform();
379
[6adffadf]380        // Draw station names.
381        if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
382            SetColour(NAME_COLOUR);
383
384            if (m_OverlappingNames) {
385                SimpleDrawNames();
386            } else {
387                NattyDrawNames();
388            }
389        }
390
[c091027]391        // Draw indicators.
392        //
393        // There's no advantage in generating an OpenGL list for the
394        // indicators since they change with almost every redraw (and
395        // sometimes several times between redraws).  This way we avoid
396        // the need to track when to update the indicator OpenGL list,
397        // and also avoid indicator update bugs when we don't quite get this
398        // right...
399        DrawIndicators();
400
[6b061db]401        if (MeasuringLineActive()) {
[429465a]402            // Draw "here" and "there".
[f6d8375]403            double hx, hy;
[aa048c3]404            SetColour(HERE_COLOUR);
[d67450e]405            if (m_here.IsValid()) {
[f6d8375]406                double dummy;
[d67450e]407                Transform(m_here, &hx, &hy, &dummy);
[570d62c3]408                if (!m_here_is_temporary) DrawRing(hx, hy);
[429465a]409            }
[d67450e]410            if (m_there.IsValid()) {
[f6d8375]411                double tx, ty;
412                double dummy;
[d67450e]413                Transform(m_there, &tx, &ty, &dummy);
414                if (m_here.IsValid()) {
[429465a]415                    BeginLines();
416                    PlaceIndicatorVertex(hx, hy);
417                    PlaceIndicatorVertex(tx, ty);
[42d23c5]418                    EndLines();
[429465a]419                }
[e633bb1]420                BeginBlobs();
[81aea4e]421                DrawBlob(tx, ty);
[e633bb1]422                EndBlobs();
[429465a]423            }
424        }
[f433fda]425
[58dfdd21]426        FinishDrawing();
427
428        drawtime = timer.Time();
[5997ffd]429    } else {
430        dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
431        dc.Clear();
[58dfdd21]432    }
[5809313]433}
434
[f4c5932]435void GfxCore::DrawBoundingBox()
436{
[d67450e]437    const Vector3 v = 0.5 * m_Parent->GetExtent();
[f4c5932]438
439    SetColour(col_BLUE);
440    EnableDashedLines();
441    BeginPolyline();
[d67450e]442    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
443    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
444    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
445    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
446    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
[f4c5932]447    EndPolyline();
448    BeginPolyline();
[d67450e]449    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
450    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
451    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
452    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
453    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]454    EndPolyline();
455    BeginLines();
[d67450e]456    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
457    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
458    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
459    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
460    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
461    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
462    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
463    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]464    EndLines();
465    DisableDashedLines();
466}
467
468void GfxCore::DrawShadowedBoundingBox()
469{
[d67450e]470    const Vector3 v = 0.5 * m_Parent->GetExtent();
[f4c5932]471
[f7dae86]472    DrawBoundingBox();
473
[f9ca87c]474    PolygonOffset(true);
[f4c5932]475    SetColour(col_DARK_GREY);
476    BeginQuadrilaterals();
[d67450e]477    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
478    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
479    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
480    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
[f4c5932]481    EndQuadrilaterals();
[f9ca87c]482    PolygonOffset(false);
[f4c5932]483
[d2fcc9b]484    DrawList(LIST_SHADOW);
[f4c5932]485}
486
[c1cf79d]487void GfxCore::DrawGrid()
488{
489    // Draw the grid.
[156dc16]490    SetColour(col_RED);
[c1cf79d]491
492    // Calculate the extent of the survey, in metres across the screen plane.
[b81eee2]493    Double m_across_screen = SurveyUnitsAcrossViewport();
[c1cf79d]494    // Calculate the length of the scale bar in metres.
495    //--move this elsewhere
[c6d95d8]496    Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
497    Double t = m_across_screen * 0.75 / size_snap;
[c1cf79d]498    if (t >= 5.0) {
[429465a]499        size_snap *= 5.0;
[c1cf79d]500    }
501    else if (t >= 2.0) {
[429465a]502        size_snap *= 2.0;
[c1cf79d]503    }
504
[d67450e]505    Double grid_size = size_snap * 0.1;
[c6d95d8]506    Double edge = grid_size * 2.0;
[d67450e]507    Double grid_z = -m_Parent->GetZExtent() * 0.5 - grid_size;
508    Double left = -m_Parent->GetXExtent() * 0.5 - edge;
509    Double right = m_Parent->GetXExtent() * 0.5 + edge;
510    Double bottom = -m_Parent->GetYExtent() * 0.5 - edge;
511    Double top = m_Parent->GetYExtent() * 0.5 + edge;
[c1cf79d]512    int count_x = (int) ceil((right - left) / grid_size);
513    int count_y = (int) ceil((top - bottom) / grid_size);
[c6d95d8]514    Double actual_right = left + count_x*grid_size;
515    Double actual_top = bottom + count_y*grid_size;
[c1cf79d]516
[b81eee2]517    BeginLines();
518
[c1cf79d]519    for (int xc = 0; xc <= count_x; xc++) {
[429465a]520        Double x = left + xc*grid_size;
[f433fda]521
[b81eee2]522        PlaceVertex(x, bottom, grid_z);
523        PlaceVertex(x, actual_top, grid_z);
[c1cf79d]524    }
525
526    for (int yc = 0; yc <= count_y; yc++) {
[429465a]527        Double y = bottom + yc*grid_size;
[b81eee2]528        PlaceVertex(left, y, grid_z);
529        PlaceVertex(actual_right, y, grid_z);
[c1cf79d]530    }
[b81eee2]531
532    EndLines();
[c1cf79d]533}
534
[1eeb55a]535int GfxCore::GetClinoOffset() const
[c300a04]536{
537    return m_Compass ? CLINO_OFFSET_X : INDICATOR_OFFSET_X;
538}
539
[fe665c4]540void GfxCore::DrawTick(int angle_cw)
[6606406]541{
[fe665c4]542    const Double theta = rad(angle_cw);
543    const wxCoord length1 = INDICATOR_RADIUS;
544    const wxCoord length0 = length1 + TICK_LENGTH;
545    wxCoord x0 = wxCoord(length0 * sin(theta));
546    wxCoord y0 = wxCoord(length0 * cos(theta));
547    wxCoord x1 = wxCoord(length1 * sin(theta));
548    wxCoord y1 = wxCoord(length1 * cos(theta));
[6606406]549
[fe665c4]550    PlaceIndicatorVertex(x0, y0);
551    PlaceIndicatorVertex(x1, y1);
[6606406]552}
553
[d67450e]554void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
555    Vector3 p1(0, INDICATOR_RADIUS, 0);
556    Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
557    Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
558    Vector3 pc(0, 0, 0);
559
560    DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
561    DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
562}
563
[fe665c4]564void GfxCore::DrawCompass() {
565    // Ticks.
566    BeginLines();
567    for (int angle = 315; angle > 0; angle -= 45) {
568        DrawTick(angle);
569    }
570    SetColour(col_GREEN);
571    DrawTick(0);
572    EndLines();
573
574    // Compass background.
575    DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
[6606406]576
[fe665c4]577    // Compass arrow.
[d67450e]578    DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
[6606406]579}
580
[fe665c4]581// Draw the non-rotating background to the clino.
582void GfxCore::DrawClinoBack() {
583    BeginLines();
584    for (int angle = 0; angle <= 180; angle += 90) {
585        DrawTick(angle);
586    }
587
588    SetColour(col_GREY);
589    PlaceIndicatorVertex(0, INDICATOR_RADIUS);
590    PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
591    PlaceIndicatorVertex(0, 0);
592    PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
[b56df45]593
[fe665c4]594    EndLines();
595}
596
597void GfxCore::DrawClino() {
598    // Ticks.
599    SetColour(col_GREEN);
[33b2094]600    BeginLines();
[fe665c4]601    DrawTick(0);
[33b2094]602    EndLines();
[fe665c4]603
604    // Clino background.
605    DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
606
607    // Elevation arrow.
[d67450e]608    DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
[b56df45]609}
610
[6606406]611void GfxCore::Draw2dIndicators()
612{
[76dd228]613    // Draw the compass and elevation indicators.
614
615    const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
616
[fe665c4]617    const int comp_centre_x = GetCompassXPosition();
[6606406]618
[eef68f9]619    if (m_Compass && !m_Parent->IsExtendedElevation()) {
[fe665c4]620        // If the user is dragging the compass with the pointer outside the
621        // compass, we snap to 45 degree multiples, and the ticks go white.
[76dd228]622        SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
[fe665c4]623        DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
[c300a04]624    }
[76dd228]625
[fe665c4]626    const int elev_centre_x = GetClinoXPosition();
[76dd228]627
[eef68f9]628    if (m_Clino) {
[fe665c4]629        // If the user is dragging the clino with the pointer outside the
630        // clino, we snap to 90 degree multiples, and the ticks go white.
631        SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
632        DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
[7a57dc7]633        DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
[c300a04]634    }
[6606406]635
[aa048c3]636    SetColour(TEXT_COLOUR);
[6606406]637
[21958ec]638    static int triple_zero_width = 0;
639    static int height = 0;
640    if (!triple_zero_width) {
[5627cbb]641        GetTextExtent(wxT("000"), &triple_zero_width, &height);
[21958ec]642    }
643    const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
[421b7d2]644
[eef68f9]645    if (m_Compass && !m_Parent->IsExtendedElevation()) {
[21958ec]646        wxString str;
647        int value;
[429465a]648        if (m_Degrees) {
[21958ec]649            value = int(m_PanAngle);
[429465a]650        } else {
[21958ec]651            value = int(m_PanAngle * 200.0 / 180.0);
[f433fda]652        }
[5627cbb]653        str.Printf(wxT("%03d"), value);
[21958ec]654        DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
655
[5627cbb]656        str = wmsg(/*Facing*/203);
[21958ec]657        int w;
[d92d282]658        GetTextExtent(str, &w, NULL);
[21958ec]659        DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
[c300a04]660    }
661
[eef68f9]662    if (m_Clino) {
[429465a]663        int angle;
[21958ec]664        wxString str;
665        int width;
[429465a]666        if (m_Degrees) {
[21958ec]667            static int zero_zero_width = 0;
668            if (!zero_zero_width) {
[5627cbb]669                GetTextExtent(wxT("00"), &zero_zero_width, NULL);
[21958ec]670            }
671            width = zero_zero_width;
[7a57dc7]672            angle = int(m_TiltAngle);
[5627cbb]673            str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
[429465a]674        } else {
[21958ec]675            width = triple_zero_width;
[7a57dc7]676            angle = int(m_TiltAngle * 200.0 / 180.0);
[5627cbb]677            str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
[f433fda]678        }
[21958ec]679
680        // Adjust horizontal position so the left of the first digit is
681        // always in the same place.
682        int sign_offset = 0;
683        if (angle < 0) {
684            static int minus_width = 0;
685            if (!minus_width) {
[5627cbb]686                GetTextExtent(wxT("-"), &minus_width, NULL);
[21958ec]687            }
688            sign_offset = minus_width + 1;
689        } else if (angle > 0) {
690            static int plus_width = 0;
691            if (!plus_width) {
[5627cbb]692                GetTextExtent(wxT("+"), &plus_width, NULL);
[21958ec]693            }
694            sign_offset = plus_width + 1;
695        }
696        DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
697
[5627cbb]698        str = wmsg(/*Elevation*/118);
[21958ec]699        int w;
[d92d282]700        GetTextExtent(str, &w, NULL);
[21958ec]701        DrawIndicatorText(elev_centre_x - w / 2, y_off + height, str);
[c300a04]702    }
[5809313]703}
704
705void GfxCore::NattyDrawNames()
706{
[84cab34]707    // Draw station names, without overlapping.
[f433fda]708
[d92d282]709    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
[90430f2]710    const unsigned int quantised_x = GetXSize() / quantise;
711    const unsigned int quantised_y = GetYSize() / quantise;
[84cab34]712    const size_t buffer_size = quantised_x * quantised_y;
[f433fda]713
[69463a0]714    if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
[5809313]715
[33b2094]716    memset((void*) m_LabelGrid, 0, buffer_size);
[156dc16]717
[33b2094]718    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
[36c3285]719    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
[ece003f]720        if (!((m_Surface && (*label)->IsSurface()) ||
721              (m_Legs && (*label)->IsUnderground()) ||
722              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
723            // if this station isn't to be displayed, skip to the next
724            // (last case is for stns with no legs attached)
725            continue;
726        }
727
[f6d8375]728        double x, y, z;
[f433fda]729
[d67450e]730        Transform(**label, &x, &y, &z);
[36c3285]731        // Check if the label is behind us (in perspective view).
[d92d282]732        if (z <= 0.0 || z >= 1.0) continue;
[421b7d2]733
[1eeb55a]734        // Apply a small shift so that translating the view doesn't make which
735        // labels are displayed change as the resulting twinkling effect is
736        // distracting.
[f6d8375]737        double tx, ty, tz;
[d67450e]738        Transform(Vector3(), &tx, &ty, &tz);
[429465a]739        tx -= floor(tx / quantise) * quantise;
740        ty -= floor(ty / quantise) * quantise;
[5809313]741
[f12e8cc]742        tx = x - tx;
743        if (tx < 0) continue;
744
745        ty = y - ty;
746        if (ty < 0) continue;
[421b7d2]747
[f12e8cc]748        unsigned int iy = unsigned(ty) / quantise;
[d92d282]749        if (iy >= quantised_y) continue;
[5a24583]750        unsigned int width = (*label)->get_width();
[f12e8cc]751        unsigned int ix = unsigned(tx) / quantise;
752        if (ix + width >= quantised_x) continue;
[33b2094]753
[f12e8cc]754        char * test = m_LabelGrid + ix + iy * quantised_x;
[d92d282]755        if (memchr(test, 1, width)) continue;
[33b2094]756
[8bd480e]757        x += 3;
758        y -= GetFontSize() / 2;
[d92d282]759        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
760
761        if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
762        test -= quantised_x * iy;
[f12e8cc]763        iy += 4;
764        while (--iy && test < m_LabelGrid + buffer_size) {
[d92d282]765            memset(test, 1, width);
766            test += quantised_x;
[429465a]767        }
[84cab34]768    }
[5809313]769}
770
771void GfxCore::SimpleDrawNames()
772{
[a8aedf4]773    // Draw all station names, without worrying about overlaps
[d5de678]774    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
[01d91fd]775    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
[ece003f]776        if (!((m_Surface && (*label)->IsSurface()) ||
777              (m_Legs && (*label)->IsUnderground()) ||
778              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
779            // if this station isn't to be displayed, skip to the next
780            // (last case is for stns with no legs attached)
781            continue;
782        }
783
[f6d8375]784        double x, y, z;
[d67450e]785        Transform(**label, &x, &y, &z);
[d92d282]786
787        // Check if the label is behind us (in perspective view).
788        if (z <= 0) continue;
789
[8bd480e]790        x += 3;
791        y -= GetFontSize() / 2;
[d92d282]792        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
[84cab34]793    }
[5809313]794}
795
[825bdff]796void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
[5809313]797{
[7cdb1c3]798    int total_block_height =
[62da267]799        KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
800    if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
[825bdff]801    if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
[5809313]802
[3585243]803    const int bottom = -total_block_height;
[a74b014]804
[d4650b3]805    int size = 0;
[7cdb1c3]806    if (!other.empty()) GetTextExtent(other, &size, NULL);
[d4650b3]807    int band;
[2043961]808    for (band = 0; band < num_bands; ++band) {
[a74b014]809        int x;
[7cdb1c3]810        GetTextExtent(key_legends[band], &x, NULL);
[d4650b3]811        if (x > size) size = x;
812    }
813
[3585243]814    int left = -KEY_BLOCK_WIDTH - size;
[d4650b3]815
[fcc3741]816    key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
817    key_lowerleft[m_ColourBy].y = bottom;
[d4650b3]818
[d43fa84]819    int y = bottom;
[825bdff]820    if (!units.empty()) y += KEY_BLOCK_HEIGHT;
[a74b014]821
[7cdb1c3]822    if (!other.empty()) {
[a74b014]823        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
[62da267]824                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
[2779338f]825        SetColour(col_BLACK);
826        BeginPolyline();
827        PlaceIndicatorVertex(left, y);
828        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
829        PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y + KEY_BLOCK_HEIGHT);
830        PlaceIndicatorVertex(left, y + KEY_BLOCK_HEIGHT);
831        PlaceIndicatorVertex(left, y);
832        EndPolyline();
[62da267]833        y += KEY_BLOCK_HEIGHT * 2;
[a74b014]834    }
835
[2779338f]836    int start = y;
[2043961]837    if (num_bands == 1) {
838        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
[62da267]839                            KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
[2779338f]840        y += KEY_BLOCK_HEIGHT;
[2043961]841    } else {
842        for (band = 0; band < num_bands - 1; ++band) {
843            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
[62da267]844                                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
845            y += KEY_BLOCK_HEIGHT;
[2043961]846        }
[d4650b3]847    }
848
[2779338f]849    SetColour(col_BLACK);
850    BeginPolyline();
851    PlaceIndicatorVertex(left, y);
852    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
853    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
854    PlaceIndicatorVertex(left, start);
855    PlaceIndicatorVertex(left, y);
856    EndPolyline();
857
[825bdff]858    SetColour(TEXT_COLOUR);
859
860    y = bottom;
861    if (!units.empty()) {
862        GetTextExtent(units, &size, NULL);
863        DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
864        y += KEY_BLOCK_HEIGHT;
865    }
866    y -= GetFontSize() / 2;
[62da267]867    left += KEY_BLOCK_WIDTH + 5;
[d4650b3]868
[7cdb1c3]869    if (!other.empty()) {
[62da267]870        y += KEY_BLOCK_HEIGHT / 2;
[7cdb1c3]871        DrawIndicatorText(left, y, other);
[62da267]872        y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
[a74b014]873    }
874
[2043961]875    if (num_bands == 1) {
[62da267]876        y += KEY_BLOCK_HEIGHT / 2;
[7cdb1c3]877        DrawIndicatorText(left, y, key_legends[0]);
[2043961]878    } else {
[62c5fc6]879        for (band = 0; band < num_bands; ++band) {
[7cdb1c3]880            DrawIndicatorText(left, y, key_legends[band]);
[62da267]881            y += KEY_BLOCK_HEIGHT;
[2043961]882        }
[d4650b3]883    }
884}
885
[e2ea75a]886void GfxCore::DrawDepthKey()
[c61aa79]887{
[62c5fc6]888    Double z_ext = m_Parent->GetDepthExtent();
[825bdff]889    int num_bands = 1;
890    int sf = 0;
891    if (z_ext > 0.0) {
[62c5fc6]892        num_bands = GetNumColourBands();
[825bdff]893        Double z_range = z_ext;
894        if (!m_Metric) z_range /= METRES_PER_FOOT;
895        sf = max(0, 1 - (int)floor(log10(z_range)));
[62c5fc6]896    }
897
[825bdff]898    Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
899    for (int band = 0; band < num_bands; ++band) {
900        Double z = z_min;
[62c5fc6]901        if (band)
902            z += z_ext * band / (num_bands - 1);
[825bdff]903
904        if (!m_Metric)
905            z /= METRES_PER_FOOT;
906
907        key_legends[band].Printf(wxT("%.*f"), sf, z);
[c61aa79]908    }
909
[825bdff]910    DrawColourKey(num_bands, wxString(), m_Metric ? wxT("m") : wxT("ft"));
[7cdb1c3]911}
[a74b014]912
[e2ea75a]913void GfxCore::DrawDateKey()
[7cdb1c3]914{
915    int num_bands;
[62c5fc6]916    if (!HasDateInformation()) {
917        num_bands = 0;
[7cdb1c3]918    } else {
[62c5fc6]919        int date_ext = m_Parent->GetDateExtent();
920        if (date_ext == 0) {
921            num_bands = 1;
922        } else {
923            num_bands = GetNumColourBands();
924        }
925        for (int band = 0; band < num_bands; ++band) {
926            int y, m, d;
927            int days = m_Parent->GetDateMin();
928            if (band)
929                days += date_ext * band / (num_bands - 1);
930            ymd_from_days_since_1900(days, &y, &m, &d);
931            key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
932        }
[7cdb1c3]933    }
[62c5fc6]934
[7cdb1c3]935    wxString other;
936    if (!m_Parent->HasCompleteDateInfo()) {
937        other = wmsg(/*Undated*/221);
[c61aa79]938    }
939
[825bdff]940    DrawColourKey(num_bands, other, wxString());
[7cdb1c3]941}
[a74b014]942
[e2ea75a]943void GfxCore::DrawErrorKey()
[7cdb1c3]944{
[62c5fc6]945    int num_bands;
946    if (HasErrorInformation()) {
947        // Use fixed colours for each error factor so it's directly visually
948        // comparable between surveys.
949        num_bands = GetNumColourBands();
950        for (int band = 0; band < num_bands; ++band) {
951            double E = MAX_ERROR * band / (num_bands - 1);
952            key_legends[band].Printf(wxT("%.2f"), E);
953        }
954    } else {
955        num_bands = 0;
[c61aa79]956    }
957
[7cdb1c3]958    // Always show the "Not in loop" legend for now (FIXME).
[825bdff]959    DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
[ac537e9]960}
961
[9c37beb]962void GfxCore::DrawScaleBar()
[5809313]963{
[84cab34]964    // Draw the scalebar.
[eef68f9]965    if (GetPerspective()) return;
[5809313]966
[37bc1f5]967    // Calculate how many metres of survey are currently displayed across the
968    // screen.
[087bc72]969    Double across_screen = SurveyUnitsAcrossViewport();
[156dc16]970
[90430f2]971    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
[5f50488]972    if (f > 0.75) {
973        f = 0.75;
974    } else if (f < 0.5) {
975        // Stop it getting squeezed to nothing.
976        // FIXME: In this case we should probably move the compass and clino up
977        // to make room rather than letting stuff overlap.
978        f = 0.5;
979    }
980
[087bc72]981    // Convert to imperial measurements if required.
[7a89dc2]982    Double multiplier = 1.0;
983    if (!m_Metric) {
[429465a]984        across_screen /= METRES_PER_FOOT;
985        multiplier = METRES_PER_FOOT;
[5f50488]986        if (across_screen >= 5280.0 / f) {
[429465a]987            across_screen /= 5280.0;
988            multiplier *= 5280.0;
989        }
[7a89dc2]990    }
[5757725]991
[7a89dc2]992    // Calculate the length of the scale bar.
[5f50488]993    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
994    Double t = across_screen * f / size_snap;
[98860c5]995    if (t >= 5.0) {
[429465a]996        size_snap *= 5.0;
[7a89dc2]997    } else if (t >= 2.0) {
[429465a]998        size_snap *= 2.0;
[98860c5]999    }
1000
[7a89dc2]1001    if (!m_Metric) size_snap *= multiplier;
1002
[84cab34]1003    // Actual size of the thing in pixels:
[90430f2]1004    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
[e2c1671]1005    m_ScaleBarWidth = size;
[421b7d2]1006
[5809313]1007    // Draw it...
[e2c1671]1008    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
[5809313]1009    int interval = size / 10;
1010
[aa048c3]1011    gla_colour col = col_WHITE;
[5809313]1012    for (int ix = 0; ix < 10; ix++) {
[e2c1671]1013        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
[421b7d2]1014
[e2c1671]1015        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
[421b7d2]1016
[aa048c3]1017        col = (col == col_WHITE) ? col_GREY : col_WHITE;
[5809313]1018    }
1019
[84cab34]1020    // Add labels.
[825bdff]1021    wxString str;
1022    if (m_Metric) {
1023        if (size_snap >= 1e3) {
1024            str.Printf(wxT("%.fkm"), size_snap * 1e-3);
1025        } else if (size_snap >= 1.0) {
1026            str.Printf(wxT("%.fm"), size_snap);
1027        } else {
1028            int sf = -(int)floor(log10(size_snap));
1029            str.Printf(wxT("%.*fm"), sf, size_snap);
1030        }
1031    } else {
1032        size_snap /= METRES_PER_FOOT;
1033        Double miles = size_snap / 5280.0;
1034        if (miles >= 2.0) {
1035            str.Printf(wxT("%.f miles"), miles);
1036        } else if (miles >= 1.0) {
1037            str.Printf(wxT("%.f mile"), miles);
1038        } else if (size_snap >= 1.0) {
1039            str.Printf(wxT("%.fft"), size_snap);
1040        } else {
1041            Double inches = size_snap * 12;
1042            if (inches >= 1.0) {
1043                str.Printf(wxT("%.fin"), inches);
1044            } else {
1045                int sf = -(int)floor(log10(inches));
1046                str.Printf(wxT("%.*fin"), sf, inches);
1047            }
1048        }
1049    }
[84cab34]1050
[1eeb55a]1051    int text_width, text_height;
[56da40e]1052    GetTextExtent(str, &text_width, &text_height);
[8bd480e]1053    const int text_y = end_y - text_height + 1;
1054    SetColour(TEXT_COLOUR);
[5627cbb]1055    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
[8bd480e]1056    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
[5809313]1057}
[56da40e]1058
[2072157]1059bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
[2effbf1]1060{
[0874c07e]1061    if (Animating()) return false;
1062
[90430f2]1063    if (point.x < 0 || point.x >= GetXSize() ||
1064        point.y < 0 || point.y >= GetYSize()) {
[429465a]1065        return false;
[137e31b]1066    }
[421b7d2]1067
[156f645]1068    SetDataTransform();
[00a68e0]1069
[69463a0]1070    if (!m_HitTestGridValid) CreateHitTestGrid();
[fa42426]1071
[90430f2]1072    int grid_x = (point.x * (HITTEST_SIZE - 1)) / GetXSize();
1073    int grid_y = (point.y * (HITTEST_SIZE - 1)) / GetYSize();
[137e31b]1074
[fa42426]1075    LabelInfo *best = NULL;
1076    int dist_sqrd = 25;
[2effbf1]1077    int square = grid_x + grid_y * HITTEST_SIZE;
[fa42426]1078    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
[00a68e0]1079
[fa42426]1080    while (iter != m_PointGrid[square].end()) {
[429465a]1081        LabelInfo *pt = *iter++;
[fa42426]1082
[f6d8375]1083        double cx, cy, cz;
[00a68e0]1084
[d67450e]1085        Transform(*pt, &cx, &cy, &cz);
[00a68e0]1086
[90430f2]1087        cy = GetYSize() - cy;
[00a68e0]1088
[429465a]1089        int dx = point.x - int(cx);
1090        int ds = dx * dx;
1091        if (ds >= dist_sqrd) continue;
1092        int dy = point.y - int(cy);
[fa42426]1093
[429465a]1094        ds += dy * dy;
1095        if (ds >= dist_sqrd) continue;
[f433fda]1096
[429465a]1097        dist_sqrd = ds;
1098        best = pt;
[f433fda]1099
[429465a]1100        if (ds == 0) break;
[2effbf1]1101    }
[f433fda]1102
[fa42426]1103    if (best) {
[6b061db]1104        m_Parent->ShowInfo(best);
[429465a]1105        if (centre) {
[e67ed1b]1106            // FIXME: allow Ctrl-Click to not set there or something?
[82c3731]1107            CentreOn(*best);
[90430f2]1108            WarpPointer(GetXSize() / 2, GetYSize() / 2);
[82c3731]1109            SetThere(*best);
[429465a]1110            m_Parent->SelectTreeItem(best);
1111        }
[e67ed1b]1112    } else {
1113        // Left-clicking not on a survey cancels the measuring line.
[0633bcc]1114        if (centre) {
1115            ClearTreeSelection();
1116        } else {
[6b061db]1117            m_Parent->ShowInfo(best);
[f6d8375]1118            double x, y, z;
[90430f2]1119            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
[0633bcc]1120            SetHere(Point(Vector3(x, y, z)));
[c00c6713]1121            m_here_is_temporary = true;
[0633bcc]1122        }
[2effbf1]1123    }
[203d2a7]1124
1125    return best;
[2effbf1]1126}
1127
[5876fcb]1128void GfxCore::OnSize(wxSizeEvent& event)
[5809313]1129{
[5876fcb]1130    // Handle a change in window size.
1131    wxSize size = event.GetSize();
[5809313]1132
[78beaf1]1133    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
[0580c6a]1134        // Before things are fully initialised, we sometimes get a bogus
1135        // resize message...
[6ef8bd73]1136        // FIXME have changes in MainFrm cured this?  It still happens with
[880b954]1137        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1138        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
[78beaf1]1139        // is resized such that the GfxCore window isn't visible.
1140        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
[0580c6a]1141        return;
1142    }
[b72f4b5]1143
[9071cf5]1144    event.Skip();
[39e460c9]1145
[5876fcb]1146    if (m_DoneFirstShow) {
[81f1266]1147        TryToFreeArrays();
[6ebc0ce]1148
[69463a0]1149        m_HitTestGridValid = false;
[33b2094]1150
[d67450e]1151        ForceRefresh();
[5809313]1152    }
1153}
1154
[de7a879]1155void GfxCore::DefaultParameters()
[5809313]1156{
[33b2094]1157    // Set default viewing parameters.
[b462168]1158
[f433fda]1159    m_Surface = false;
1160    if (!m_Parent->HasUndergroundLegs()) {
1161        if (m_Parent->HasSurfaceLegs()) {
1162            // If there are surface legs, but no underground legs, turn
1163            // surface surveys on.
1164            m_Surface = true;
1165        } else {
1166            // If there are no legs (e.g. after loading a .pos file), turn
1167            // crosses on.
1168            m_Crosses = true;
1169        }
[b462168]1170    }
1171
[714daae]1172    m_PanAngle = 0.0;
[eef68f9]1173    if (m_Parent->IsExtendedElevation()) {
1174        m_TiltAngle = 0.0;
1175    } else {
[7a57dc7]1176        m_TiltAngle = -90.0;
[b462168]1177    }
[714daae]1178
[08253d9]1179    SetRotation(m_PanAngle, m_TiltAngle);
[d67450e]1180    SetTranslation(Vector3());
[33b2094]1181
[e577f89]1182    m_RotationStep = 30.0;
[5809313]1183    m_Rotating = false;
[3d00693]1184    m_SwitchingTo = 0;
[fe444b8]1185    m_Entrances = false;
1186    m_FixedPts = false;
1187    m_ExportedPts = false;
[c1cf79d]1188    m_Grid = false;
[f4c5932]1189    m_BoundingBox = false;
[33b2094]1190    m_Tubes = false;
[1eeb55a]1191    if (GetPerspective()) TogglePerspective();
[de7a879]1192}
[5809313]1193
[de7a879]1194void GfxCore::Defaults()
1195{
1196    // Restore default scale, rotation and translation parameters.
1197    DefaultParameters();
[8b0d57f]1198    SetScale(1.0);
[ba358fc]1199
1200    // Invalidate all the cached lists.
1201    GLACanvas::FirstShow();
1202
[fa42426]1203    ForceRefresh();
[5809313]1204}
[84cab34]1205
[5876fcb]1206// return: true if animation occured (and ForceRefresh() needs to be called)
[1690fa9]1207bool GfxCore::Animate()
[5809313]1208{
[2a3d328]1209    if (!Animating()) return false;
1210
1211    // Don't show pointer coordinates while animating.
[4b031c0]1212    // FIXME : only do this when we *START* animating!  Use a static copy
1213    // of the value of "Animating()" last time we were here to track this?
1214    // MainFrm now checks if we're trying to clear already cleared labels
1215    // and just returns, but it might be simpler to check here!
[2a3d328]1216    ClearCoords();
[7c29c976]1217    m_Parent->ShowInfo(NULL);
[5809313]1218
[5876fcb]1219    static double last_t = 0;
[6a4cdcb6]1220    double t;
[75d4a2b]1221    if (movie) {
[aea4f8b]1222        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
[75d4a2b]1223        movie->AddFrame();
[6a4cdcb6]1224        t = 1.0 / 25.0; // 25 frames per second
1225    } else {
1226        t = timer.Time() * 1.0e-3;
1227        if (t == 0) t = 0.001;
1228        else if (t > 1.0) t = 1.0;
1229        if (last_t > 0) t = (t + last_t) / 2;
1230        last_t = t;
1231    }
[5809313]1232
[128fac4]1233    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1234        t *= fabs(pres_speed);
[1690fa9]1235        while (t >= next_mark_time) {
1236            t -= next_mark_time;
[128fac4]1237            this_mark_total = 0;
[58dfdd21]1238            PresentationMark prev_mark = next_mark;
[e577f89]1239            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1240            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
[128fac4]1241            if (pres_reverse)
1242                next_mark = m_Parent->GetPresMark(MARK_PREV);
1243            else
1244                next_mark = m_Parent->GetPresMark(MARK_NEXT);
[1690fa9]1245            if (!next_mark.is_valid()) {
[128fac4]1246                SetView(prev_mark);
[1690fa9]1247                presentation_mode = 0;
[81f1266]1248                delete movie;
1249                movie = NULL;
[1690fa9]1250                break;
1251            }
[58dfdd21]1252
[128fac4]1253            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1254            if (tmp > 0) {
1255                next_mark_time = tmp;
[58dfdd21]1256            } else {
[d67450e]1257                double d = (next_mark - prev_mark).magnitude();
[49ce5b0]1258                // FIXME: should ignore component of d which is unseen in
1259                // non-perspective mode?
[8674eea]1260                next_mark_time = sqrd(d / 30.0);
[49ce5b0]1261                double a = next_mark.angle - prev_mark.angle;
1262                if (a > 180.0) {
1263                    next_mark.angle -= 360.0;
1264                    a = 360.0 - a;
1265                } else if (a < -180.0) {
1266                    next_mark.angle += 360.0;
1267                    a += 360.0;
1268                } else {
1269                    a = fabs(a);
1270                }
1271                next_mark_time += sqrd(a / 60.0);
1272                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1273                next_mark_time += sqrd(ta / 60.0);
1274                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
[8674eea]1275                next_mark_time += sqrd(s / 2.0);
[49ce5b0]1276                next_mark_time = sqrt(next_mark_time);
[8674eea]1277                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
[49ce5b0]1278                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
[8674eea]1279                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1280                if (tmp < 0) next_mark_time /= -tmp;
[58dfdd21]1281            }
[1690fa9]1282        }
1283
1284        if (presentation_mode) {
1285            // Advance position towards next_mark
1286            double p = t / next_mark_time;
1287            double q = 1 - p;
1288            PresentationMark here = GetView();
[d877aa2]1289            if (next_mark.angle < 0) {
[e577f89]1290                if (here.angle >= next_mark.angle + 360.0)
1291                    here.angle -= 360.0;
1292            } else if (next_mark.angle >= 360.0) {
1293                if (here.angle <= next_mark.angle - 360.0)
1294                    here.angle += 360.0;
[d877aa2]1295            }
[8674eea]1296            here.assign(q * here + p * next_mark);
[1690fa9]1297            here.angle = q * here.angle + p * next_mark.angle;
[e577f89]1298            if (here.angle < 0) here.angle += 360.0;
1299            else if (here.angle >= 360.0) here.angle -= 360.0;
[1690fa9]1300            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
[58dfdd21]1301            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
[1690fa9]1302            SetView(here);
[128fac4]1303            this_mark_total += t;
[1690fa9]1304            next_mark_time -= t;
1305        }
1306    }
1307
[5876fcb]1308    // When rotating...
1309    if (m_Rotating) {
[1690fa9]1310        TurnCave(m_RotationStep * t);
[5876fcb]1311    }
[5809313]1312
[5876fcb]1313    if (m_SwitchingTo == PLAN) {
[429465a]1314        // When switching to plan view...
[7a57dc7]1315        TiltCave(-90.0 * t);
1316        if (m_TiltAngle == -90.0) {
[429465a]1317            m_SwitchingTo = 0;
1318        }
[1690fa9]1319    } else if (m_SwitchingTo == ELEVATION) {
[429465a]1320        // When switching to elevation view...
[e577f89]1321        if (fabs(m_TiltAngle) < 90.0 * t) {
[429465a]1322            m_SwitchingTo = 0;
1323            TiltCave(-m_TiltAngle);
[7a57dc7]1324        } else if (m_TiltAngle > 0.0) {
[e577f89]1325            TiltCave(-90.0 * t);
[7a57dc7]1326        } else {
1327            TiltCave(90.0 * t);
[429465a]1328        }
[3ddd351]1329    } else if (m_SwitchingTo) {
1330        int angle = (m_SwitchingTo - NORTH) * 90;
1331        double diff = angle - m_PanAngle;
1332        if (diff < -180) diff += 360;
1333        if (diff > 180) diff -= 360;
1334        double move = 90.0 * t;
1335        if (move >= fabs(diff)) {
1336            TurnCave(diff);
1337            m_SwitchingTo = 0;
1338        } else if (diff < 0) {
1339            TurnCave(-move);
1340        } else {
1341            TurnCave(move);
1342        }
[5876fcb]1343    }
[5809313]1344
[7757a4ed]1345    return true;
[5809313]1346}
[84cab34]1347
[0580c6a]1348// How much to allow around the box - this is because of the ring shape
1349// at one end of the line.
1350static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1351#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1352void GfxCore::RefreshLine(const Point &a, const Point &b, const Point &c)
[7a89dc2]1353{
[06d367d]1354    // Best of all might be to copy the window contents before we draw the
1355    // line, then replace each time we redraw.
[796d7bf]1356
[5876fcb]1357    // Calculate the minimum rectangle which includes the old and new
1358    // measuring lines to minimise the redraw time
1359    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
[f6d8375]1360    double X, Y, Z;
[d67450e]1361    if (a.IsValid()) {
1362        if (!Transform(a, &X, &Y, &Z)) {
[796d7bf]1363            printf("oops\n");
1364        } else {
1365            int x = int(X);
[90430f2]1366            int y = GetYSize() - 1 - int(Y);
[796d7bf]1367            l = x - MARGIN;
1368            r = x + MARGIN;
1369            u = y + MARGIN;
1370            d = y - MARGIN;
1371        }
[5876fcb]1372    }
[d67450e]1373    if (b.IsValid()) {
1374        if (!Transform(b, &X, &Y, &Z)) {
[796d7bf]1375            printf("oops\n");
1376        } else {
1377            int x = int(X);
[90430f2]1378            int y = GetYSize() - 1 - int(Y);
[796d7bf]1379            l = min(l, x - MARGIN);
1380            r = max(r, x + MARGIN);
1381            u = max(u, y + MARGIN);
1382            d = min(d, y - MARGIN);
1383        }
[5876fcb]1384    }
[d67450e]1385    if (c.IsValid()) {
1386        if (!Transform(c, &X, &Y, &Z)) {
[796d7bf]1387            printf("oops\n");
1388        } else {
1389            int x = int(X);
[90430f2]1390            int y = GetYSize() - 1 - int(Y);
[796d7bf]1391            l = min(l, x - MARGIN);
1392            r = max(r, x + MARGIN);
1393            u = max(u, y + MARGIN);
1394            d = min(d, y - MARGIN);
1395        }
[5876fcb]1396    }
1397    const wxRect R(l, d, r - l, u - d);
1398    Refresh(false, &R);
[7a89dc2]1399}
1400
[5876fcb]1401void GfxCore::SetHere()
[7a89dc2]1402{
[d67450e]1403    if (!m_here.IsValid()) return;
[6b061db]1404    bool line_active = MeasuringLineActive();
[5876fcb]1405    Point old = m_here;
[d67450e]1406    m_here.Invalidate();
[6b061db]1407    if (line_active || MeasuringLineActive())
1408        RefreshLine(old, m_there, m_here);
[7a89dc2]1409}
1410
[82c3731]1411void GfxCore::SetHere(const Point &p)
[c6d95d8]1412{
[6b061db]1413    bool line_active = MeasuringLineActive();
[5876fcb]1414    Point old = m_here;
[82c3731]1415    m_here = p;
[6b061db]1416    if (line_active || MeasuringLineActive())
1417        RefreshLine(old, m_there, m_here);
[c00c6713]1418    m_here_is_temporary = false;
[156dc16]1419}
1420
[5876fcb]1421void GfxCore::SetThere()
[156dc16]1422{
[d67450e]1423    if (!m_there.IsValid()) return;
[5876fcb]1424    Point old = m_there;
[d67450e]1425    m_there.Invalidate();
[0580c6a]1426    RefreshLine(m_here, old, m_there);
[156dc16]1427}
1428
[82c3731]1429void GfxCore::SetThere(const Point &p)
[156dc16]1430{
[5876fcb]1431    Point old = m_there;
[82c3731]1432    m_there = p;
[0580c6a]1433    RefreshLine(m_here, old, m_there);
[156dc16]1434}
1435
[5876fcb]1436void GfxCore::CreateHitTestGrid()
[156dc16]1437{
[00a68e0]1438    // Clear hit-test grid.
[5876fcb]1439    for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
[429465a]1440        m_PointGrid[i].clear();
[5876fcb]1441    }
[156dc16]1442
[5876fcb]1443    // Fill the grid.
1444    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1445    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1446    while (pos != end) {
[429465a]1447        LabelInfo* label = *pos++;
[33b2094]1448
[429465a]1449        if (!((m_Surface && label->IsSurface()) ||
[dc42b8e]1450              (m_Legs && label->IsUnderground()) ||
1451              (!label->IsSurface() && !label->IsUnderground()))) {
1452            // if this station isn't to be displayed, skip to the next
1453            // (last case is for stns with no legs attached)
[429465a]1454            continue;
1455        }
[33b2094]1456
[429465a]1457        // Calculate screen coordinates.
[f6d8375]1458        double cx, cy, cz;
[d67450e]1459        Transform(*label, &cx, &cy, &cz);
[90430f2]1460        if (cx < 0 || cx >= GetXSize()) continue;
1461        if (cy < 0 || cy >= GetYSize()) continue;
[33b2094]1462
[90430f2]1463        cy = GetYSize() - cy;
[00a68e0]1464
[429465a]1465        // On-screen, so add to hit-test grid...
[90430f2]1466        int grid_x = int((cx * (HITTEST_SIZE - 1)) / GetXSize());
1467        int grid_y = int((cy * (HITTEST_SIZE - 1)) / GetYSize());
[33b2094]1468
[429465a]1469        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
[33b2094]1470    }
1471
[00a68e0]1472    m_HitTestGridValid = true;
[33b2094]1473}
[c6d95d8]1474
[2a02de2]1475//
[5876fcb]1476//  Methods for controlling the orientation of the survey
[2a02de2]1477//
1478
[5876fcb]1479void GfxCore::TurnCave(Double angle)
[156dc16]1480{
[5876fcb]1481    // Turn the cave around its z-axis by a given angle.
[156dc16]1482
[5876fcb]1483    m_PanAngle += angle;
[e577f89]1484    if (m_PanAngle >= 360.0) {
1485        m_PanAngle -= 360.0;
[5876fcb]1486    } else if (m_PanAngle < 0.0) {
[e577f89]1487        m_PanAngle += 360.0;
[156dc16]1488    }
[33b2094]1489
[00a68e0]1490    m_HitTestGridValid = false;
[c00c6713]1491    if (m_here_is_temporary) SetHere();
[00a68e0]1492
[08253d9]1493    SetRotation(m_PanAngle, m_TiltAngle);
[156dc16]1494}
1495
[5876fcb]1496void GfxCore::TurnCaveTo(Double angle)
[d80805e]1497{
[3ddd351]1498    timer.Start(drawtime);
1499    int new_switching_to = ((int)angle) / 90 + NORTH;
1500    if (new_switching_to == m_SwitchingTo) {
1501        // A second order to switch takes us there right away
1502        TurnCave(angle - m_PanAngle);
1503        m_SwitchingTo = 0;
1504        ForceRefresh();
1505    } else {
1506        m_SwitchingTo = new_switching_to;
1507    }
[d80805e]1508}
1509
[5876fcb]1510void GfxCore::TiltCave(Double tilt_angle)
[156dc16]1511{
[5876fcb]1512    // Tilt the cave by a given angle.
[e577f89]1513    if (m_TiltAngle + tilt_angle > 90.0) {
[08253d9]1514        m_TiltAngle = 90.0;
[e577f89]1515    } else if (m_TiltAngle + tilt_angle < -90.0) {
[08253d9]1516        m_TiltAngle = -90.0;
1517    } else {
1518        m_TiltAngle += tilt_angle;
[d80805e]1519    }
1520
[00a68e0]1521    m_HitTestGridValid = false;
[c00c6713]1522    if (m_here_is_temporary) SetHere();
[00a68e0]1523
[08253d9]1524    SetRotation(m_PanAngle, m_TiltAngle);
[5ffa439]1525}
1526
[5876fcb]1527void GfxCore::TranslateCave(int dx, int dy)
[5ffa439]1528{
[33b2094]1529    AddTranslationScreenCoordinates(dx, dy);
[00a68e0]1530    m_HitTestGridValid = false;
1531
[c00c6713]1532    if (m_here_is_temporary) SetHere();
1533
[33b2094]1534    ForceRefresh();
1535}
[5876fcb]1536
[33b2094]1537void GfxCore::DragFinished()
1538{
[76dd228]1539    m_MouseOutsideCompass = m_MouseOutsideElev = false;
[5876fcb]1540    ForceRefresh();
[2173dbd]1541}
1542
[d877aa2]1543void GfxCore::ClearCoords()
1544{
1545    m_Parent->ClearCoords();
1546}
1547
[5876fcb]1548void GfxCore::SetCoords(wxPoint point)
[fd6e0d5]1549{
[0874c07e]1550    // We can't work out 2D coordinates from a perspective view, and it
1551    // doesn't really make sense to show coordinates while we're animating.
1552    if (GetPerspective() || Animating()) return;
[0a811ab]1553
[5876fcb]1554    // Update the coordinate or altitude display, given the (x, y) position in
1555    // window coordinates.  The relevant display is updated depending on
1556    // whether we're in plan or elevation view.
1557
[f6d8375]1558    double cx, cy, cz;
[5876fcb]1559
[a2b3d62]1560    SetDataTransform();
[90430f2]1561    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
[5876fcb]1562
[0633bcc]1563    if (ShowingPlan()) {
[d67450e]1564        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1565                            cy + m_Parent->GetOffset().GetY());
[0633bcc]1566    } else if (ShowingElevation()) {
[d67450e]1567        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ());
[d479c15]1568    } else {
[429465a]1569        m_Parent->ClearCoords();
[a2b3d62]1570    }
[fd6e0d5]1571}
1572
[1eeb55a]1573int GfxCore::GetCompassXPosition() const
[1fd2edb]1574{
[f433fda]1575    // Return the x-coordinate of the centre of the compass in window
1576    // coordinates.
[90430f2]1577    return GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1578}
1579
[1eeb55a]1580int GfxCore::GetClinoXPosition() const
[1fd2edb]1581{
[f433fda]1582    // Return the x-coordinate of the centre of the compass in window
1583    // coordinates.
[90430f2]1584    return GetXSize() - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1585}
1586
[1eeb55a]1587int GfxCore::GetIndicatorYPosition() const
[dfe4454c]1588{
[f433fda]1589    // Return the y-coordinate of the centre of the indicators in window
1590    // coordinates.
[90430f2]1591    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
[5876fcb]1592}
[fa42426]1593
[1eeb55a]1594int GfxCore::GetIndicatorRadius() const
[5876fcb]1595{
1596    // Return the radius of each indicator.
[1eeb55a]1597    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
[5876fcb]1598}
[dfe4454c]1599
[14acdae]1600bool GfxCore::PointWithinCompass(wxPoint point) const
[5876fcb]1601{
[f433fda]1602    // Determine whether a point (in window coordinates) lies within the
1603    // compass.
[e2c1671]1604    if (!ShowingCompass()) return false;
1605
[33b2094]1606    glaCoord dx = point.x - GetCompassXPosition();
1607    glaCoord dy = point.y - GetIndicatorYPosition();
1608    glaCoord radius = GetIndicatorRadius();
[f433fda]1609
[5876fcb]1610    return (dx * dx + dy * dy <= radius * radius);
1611}
[fa42426]1612
[14acdae]1613bool GfxCore::PointWithinClino(wxPoint point) const
[5876fcb]1614{
1615    // Determine whether a point (in window coordinates) lies within the clino.
[e2c1671]1616    if (!ShowingClino()) return false;
1617
[33b2094]1618    glaCoord dx = point.x - GetClinoXPosition();
1619    glaCoord dy = point.y - GetIndicatorYPosition();
1620    glaCoord radius = GetIndicatorRadius();
[f433fda]1621
[5876fcb]1622    return (dx * dx + dy * dy <= radius * radius);
[dfe4454c]1623}
[8000d8f]1624
[14acdae]1625bool GfxCore::PointWithinScaleBar(wxPoint point) const
[5876fcb]1626{
[e2c1671]1627    // Determine whether a point (in window coordinates) lies within the scale
1628    // bar.
1629    if (!ShowingScaleBar()) return false;
[8000d8f]1630
[e2c1671]1631    return (point.x >= SCALE_BAR_OFFSET_X &&
1632            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
[90430f2]1633            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1634            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
[5876fcb]1635}
[8000d8f]1636
[d43fa84]1637bool GfxCore::PointWithinColourKey(wxPoint point) const
1638{
1639    // Determine whether a point (in window coordinates) lies within the key.
[62da267]1640    point.x -= GetXSize() - KEY_OFFSET_X;
1641    point.y = KEY_OFFSET_Y - point.y;
[fcc3741]1642    return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
1643            point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
[d43fa84]1644}
1645
[5876fcb]1646void GfxCore::SetCompassFromPoint(wxPoint point)
[8000d8f]1647{
[d877aa2]1648    // Given a point in window coordinates, set the heading of the survey.  If
1649    // the point is outside the compass, it snaps to 45 degree intervals;
1650    // otherwise it operates as normal.
[8000d8f]1651
[5876fcb]1652    wxCoord dx = point.x - GetCompassXPosition();
1653    wxCoord dy = point.y - GetIndicatorYPosition();
1654    wxCoord radius = GetIndicatorRadius();
[7aa15c0]1655
[0580c6a]1656    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
[5876fcb]1657    if (dx * dx + dy * dy <= radius * radius) {
[3ddd351]1658        TurnCave(angle - m_PanAngle);
[429465a]1659        m_MouseOutsideCompass = false;
[e577f89]1660    } else {
[3ddd351]1661        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
[429465a]1662        m_MouseOutsideCompass = true;
[7aa15c0]1663    }
[8000d8f]1664
[5876fcb]1665    ForceRefresh();
1666}
1667
1668void GfxCore::SetClinoFromPoint(wxPoint point)
1669{
[d877aa2]1670    // Given a point in window coordinates, set the elevation of the survey.
1671    // If the point is outside the clino, it snaps to 90 degree intervals;
1672    // otherwise it operates as normal.
[8000d8f]1673
[33b2094]1674    glaCoord dx = point.x - GetClinoXPosition();
1675    glaCoord dy = point.y - GetIndicatorYPosition();
1676    glaCoord radius = GetIndicatorRadius();
[f433fda]1677
[5876fcb]1678    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
[7a57dc7]1679        TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
[429465a]1680        m_MouseOutsideElev = false;
[e577f89]1681    } else if (dy >= INDICATOR_MARGIN) {
[7a57dc7]1682        TiltCave(-90.0 - m_TiltAngle);
[429465a]1683        m_MouseOutsideElev = true;
[e577f89]1684    } else if (dy <= -INDICATOR_MARGIN) {
[7a57dc7]1685        TiltCave(90.0 - m_TiltAngle);
[429465a]1686        m_MouseOutsideElev = true;
[e577f89]1687    } else {
[429465a]1688        TiltCave(-m_TiltAngle);
1689        m_MouseOutsideElev = true;
[5876fcb]1690    }
[8000d8f]1691
[5876fcb]1692    ForceRefresh();
[8000d8f]1693}
1694
[5876fcb]1695void GfxCore::SetScaleBarFromOffset(wxCoord dx)
[8000d8f]1696{
[5876fcb]1697    // Set the scale of the survey, given an offset as to how much the mouse has
1698    // been dragged over the scalebar since the last scale change.
[8000d8f]1699
[5b7164d]1700    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
[5876fcb]1701    ForceRefresh();
1702}
[8000d8f]1703
[5876fcb]1704void GfxCore::RedrawIndicators()
1705{
1706    // Redraw the compass and clino indicators.
[8000d8f]1707
[90430f2]1708    const wxRect r(GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
[429465a]1709                     INDICATOR_GAP,
[90430f2]1710                   GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
[429465a]1711                   INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1712                   INDICATOR_BOX_SIZE);
[f433fda]1713
[5876fcb]1714    Refresh(false, &r);
[8000d8f]1715}
1716
[5876fcb]1717void GfxCore::StartRotation()
[8000d8f]1718{
[5876fcb]1719    // Start the survey rotating.
[f433fda]1720
[5876fcb]1721    m_Rotating = true;
1722    timer.Start(drawtime);
1723}
[8000d8f]1724
[5876fcb]1725void GfxCore::ToggleRotation()
1726{
1727    // Toggle the survey rotation on/off.
[f433fda]1728
[5876fcb]1729    if (m_Rotating) {
[2a3d328]1730        StopRotation();
1731    } else {
1732        StartRotation();
[5876fcb]1733    }
1734}
[8000d8f]1735
[5876fcb]1736void GfxCore::StopRotation()
1737{
1738    // Stop the survey rotating.
[8000d8f]1739
[5876fcb]1740    m_Rotating = false;
[33b2094]1741    ForceRefresh();
[5876fcb]1742}
[8000d8f]1743
[eef68f9]1744bool GfxCore::IsExtendedElevation() const
[5876fcb]1745{
[eef68f9]1746    return m_Parent->IsExtendedElevation();
[5876fcb]1747}
[8000d8f]1748
[5876fcb]1749void GfxCore::ReverseRotation()
1750{
1751    // Reverse the direction of rotation.
[8000d8f]1752
[5876fcb]1753    m_RotationStep = -m_RotationStep;
1754}
[8000d8f]1755
[5876fcb]1756void GfxCore::RotateSlower(bool accel)
1757{
1758    // Decrease the speed of rotation, optionally by an increased amount.
[8000d8f]1759
[5876fcb]1760    m_RotationStep /= accel ? 1.44 : 1.2;
[e577f89]1761    if (m_RotationStep < 1.0) {
1762        m_RotationStep = 1.0;
[1690fa9]1763    }
[8000d8f]1764}
1765
[5876fcb]1766void GfxCore::RotateFaster(bool accel)
1767{
1768    // Increase the speed of rotation, optionally by an increased amount.
1769
1770    m_RotationStep *= accel ? 1.44 : 1.2;
[e577f89]1771    if (m_RotationStep > 450.0) {
1772        m_RotationStep = 450.0;
[1690fa9]1773    }
[5876fcb]1774}
[8000d8f]1775
[5876fcb]1776void GfxCore::SwitchToElevation()
[8000d8f]1777{
[5876fcb]1778    // Perform an animated switch to elevation view.
[8000d8f]1779
[5876fcb]1780    switch (m_SwitchingTo) {
[429465a]1781        case 0:
1782            timer.Start(drawtime);
1783            m_SwitchingTo = ELEVATION;
1784            break;
[f433fda]1785
[429465a]1786        case PLAN:
1787            m_SwitchingTo = ELEVATION;
1788            break;
[f433fda]1789
[429465a]1790        case ELEVATION:
1791            // a second order to switch takes us there right away
1792            TiltCave(-m_TiltAngle);
1793            m_SwitchingTo = 0;
1794            ForceRefresh();
[5876fcb]1795    }
[8000d8f]1796}
1797
[5876fcb]1798void GfxCore::SwitchToPlan()
[8000d8f]1799{
[5876fcb]1800    // Perform an animated switch to plan view.
[8000d8f]1801
[5876fcb]1802    switch (m_SwitchingTo) {
[429465a]1803        case 0:
1804            timer.Start(drawtime);
1805            m_SwitchingTo = PLAN;
1806            break;
[f433fda]1807
[429465a]1808        case ELEVATION:
1809            m_SwitchingTo = PLAN;
1810            break;
[8000d8f]1811
[429465a]1812        case PLAN:
[0580c6a]1813            // A second order to switch takes us there right away
[7a57dc7]1814            TiltCave(-90.0 - m_TiltAngle);
[429465a]1815            m_SwitchingTo = 0;
1816            ForceRefresh();
[8000d8f]1817    }
[5876fcb]1818}
[8000d8f]1819
[d1628e8e]1820void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
1821{
1822
1823    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
[d0f5918]1824    Double scale = HUGE_VAL;
[d1628e8e]1825    const Vector3 ext = m_Parent->GetExtent();
1826    if (xmax > xmin) {
1827        Double s = ext.GetX() / (xmax - xmin);
1828        if (s < scale) scale = s;
1829    }
1830    if (ymax > ymin) {
1831        Double s = ext.GetY() / (ymax - ymin);
1832        if (s < scale) scale = s;
1833    }
1834    if (!ShowingPlan() && zmax > zmin) {
1835        Double s = ext.GetZ() / (zmax - zmin);
1836        if (s < scale) scale = s;
1837    }
[d0f5918]1838    if (scale != HUGE_VAL) SetScale(scale);
[d1628e8e]1839    ForceRefresh();
1840}
1841
[14acdae]1842bool GfxCore::CanRaiseViewpoint() const
[5876fcb]1843{
1844    // Determine if the survey can be viewed from a higher angle of elevation.
[f433fda]1845
[7a57dc7]1846    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
[8000d8f]1847}
1848
[14acdae]1849bool GfxCore::CanLowerViewpoint() const
[2effbf1]1850{
[5876fcb]1851    // Determine if the survey can be viewed from a lower angle of elevation.
[2effbf1]1852
[7a57dc7]1853    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
[5876fcb]1854}
[2effbf1]1855
[78c67a6]1856bool GfxCore::HasDepth() const
[bd21214]1857{
[78c67a6]1858    return m_Parent->GetDepthExtent() == 0.0;
[bd21214]1859}
1860
[843ee7b]1861bool GfxCore::HasErrorInformation() const
[d4650b3]1862{
[843ee7b]1863    return m_Parent->HasErrorInformation();
[d4650b3]1864}
1865
[843ee7b]1866bool GfxCore::HasDateInformation() const
[c61aa79]1867{
[843ee7b]1868    return m_Parent->GetDateMin() >= 0;
[c61aa79]1869}
1870
[14acdae]1871bool GfxCore::ShowingPlan() const
[5876fcb]1872{
1873    // Determine if the survey is in plan view.
[f433fda]1874
[7a57dc7]1875    return (m_TiltAngle == -90.0);
[2effbf1]1876}
1877
[14acdae]1878bool GfxCore::ShowingElevation() const
[8000d8f]1879{
[5876fcb]1880    // Determine if the survey is in elevation view.
[f433fda]1881
[5876fcb]1882    return (m_TiltAngle == 0.0);
[8000d8f]1883}
1884
[14acdae]1885bool GfxCore::ShowingMeasuringLine() const
[8000d8f]1886{
[5876fcb]1887    // Determine if the measuring line is being shown.
[f433fda]1888
[c00c6713]1889    return (m_there.IsValid() && m_here.IsValid());
[8000d8f]1890}
1891
[eff44b9]1892void GfxCore::ToggleFlag(bool* flag, int update)
[5876fcb]1893{
1894    *flag = !*flag;
[6747314]1895    if (update == UPDATE_BLOBS) {
[eff44b9]1896        UpdateBlobs();
[ef1870d]1897    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
1898        UpdateBlobs();
1899        InvalidateList(LIST_CROSSES);
[6cd6bbe]1900    }
[eff44b9]1901    ForceRefresh();
[5876fcb]1902}
[93744a5]1903
[14acdae]1904int GfxCore::GetNumEntrances() const
[4b1fc48]1905{
[5876fcb]1906    return m_Parent->GetNumEntrances();
1907}
[bd7a61b]1908
[14acdae]1909int GfxCore::GetNumFixedPts() const
[5876fcb]1910{
1911    return m_Parent->GetNumFixedPts();
1912}
[7757a4ed]1913
[14acdae]1914int GfxCore::GetNumExportedPts() const
[5876fcb]1915{
1916    return m_Parent->GetNumExportedPts();
1917}
1918
1919void GfxCore::ClearTreeSelection()
1920{
1921    m_Parent->ClearTreeSelection();
1922}
1923
[82c3731]1924void GfxCore::CentreOn(const Point &p)
[5876fcb]1925{
[d67450e]1926    SetTranslation(-p);
[00a68e0]1927    m_HitTestGridValid = false;
[f433fda]1928
[5876fcb]1929    ForceRefresh();
[4b1fc48]1930}
[5876fcb]1931
[33b2094]1932void GfxCore::ForceRefresh()
1933{
1934    Refresh(false);
1935}
1936
[d2fcc9b]1937void GfxCore::GenerateList(unsigned int l)
[33b2094]1938{
[9eb58d0]1939    assert(m_HaveData);
[3ddcad8]1940
[d2fcc9b]1941    switch (l) {
[fe665c4]1942        case LIST_COMPASS:
1943            DrawCompass();
1944            break;
1945        case LIST_CLINO:
1946            DrawClino();
1947            break;
1948        case LIST_CLINO_BACK:
1949            DrawClinoBack();
1950            break;
[9c37beb]1951        case LIST_SCALE_BAR:
1952            DrawScaleBar();
1953            break;
[e2ea75a]1954        case LIST_DEPTH_KEY:
1955            DrawDepthKey();
[252d759]1956            break;
[e2ea75a]1957        case LIST_DATE_KEY:
1958            DrawDateKey();
[d4650b3]1959            break;
[e2ea75a]1960        case LIST_ERROR_KEY:
1961            DrawErrorKey();
[c61aa79]1962            break;
[d2fcc9b]1963        case LIST_UNDERGROUND_LEGS:
1964            GenerateDisplayList();
1965            break;
1966        case LIST_TUBES:
1967            GenerateDisplayListTubes();
1968            break;
1969        case LIST_SURFACE_LEGS:
1970            GenerateDisplayListSurface();
1971            break;
[86fe6e4]1972        case LIST_BLOBS:
1973            GenerateBlobsDisplayList();
[37d7084]1974            break;
[86fe6e4]1975        case LIST_CROSSES: {
1976            BeginCrosses();
1977            SetColour(col_LIGHT_GREY);
1978            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1979            while (pos != m_Parent->GetLabelsEnd()) {
1980                const LabelInfo* label = *pos++;
1981
1982                if ((m_Surface && label->IsSurface()) ||
1983                    (m_Legs && label->IsUnderground()) ||
1984                    (!label->IsSurface() && !label->IsUnderground())) {
1985                    // Check if this station should be displayed
1986                    // (last case is for stns with no legs attached)
1987                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
1988                }
1989            }
1990            EndCrosses();
1991            break;
1992        }
[37d7084]1993        case LIST_GRID:
1994            DrawGrid();
[d2fcc9b]1995            break;
[86fe6e4]1996        case LIST_SHADOW:
1997            GenerateDisplayListShadow();
[d2fcc9b]1998            break;
1999        default:
2000            assert(false);
2001            break;
2002    }
2003}
2004
[d67450e]2005void GfxCore::ToggleSmoothShading()
2006{
2007    GLACanvas::ToggleSmoothShading();
2008    InvalidateList(LIST_TUBES);
2009    ForceRefresh();
2010}
2011
[d2fcc9b]2012void GfxCore::GenerateDisplayList()
2013{
2014    // Generate the display list for the underground legs.
[c61aa79]2015    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2016    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[5fc8d1f]2017
2018    /* We draw the faded splays first, so that they are behind
2019       the centerline in case of any conflicts */
2020    if(m_Splays == SPLAYS_SHOW_FADED)
2021    {
2022        SwitchToHalfPens();
2023        while (trav != tend) {
2024            if((*trav).isSplay)
2025                (this->*AddPoly)(*trav);
2026            ++trav;
2027        }
2028        SwitchToFullPens();
2029        trav = m_Parent->traverses_begin();
2030    }
2031
[3ddcad8]2032    while (trav != tend) {
[5fc8d1f]2033        if(m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
2034            (this->*AddPoly)(*trav);
[3ddcad8]2035        ++trav;
2036    }
[33b2094]2037}
2038
[9eb58d0]2039void GfxCore::GenerateDisplayListTubes()
[33b2094]2040{
[9eb58d0]2041    // Generate the display list for the tubes.
[fc68ad5]2042    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2043    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
[3ddcad8]2044    while (trav != tend) {
2045        SkinPassage(*trav);
2046        ++trav;
2047    }
[9eb58d0]2048}
[33b2094]2049
[9eb58d0]2050void GfxCore::GenerateDisplayListSurface()
2051{
2052    // Generate the display list for the surface legs.
[3ddcad8]2053    EnableDashedLines();
[c61aa79]2054    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2055    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
[3ddcad8]2056    while (trav != tend) {
[c61aa79]2057        if (m_ColourBy == COLOUR_BY_ERROR) {
2058            AddPolylineError(*trav);
2059        } else {
2060            AddPolyline(*trav);
2061        }
[3ddcad8]2062        ++trav;
2063    }
2064    DisableDashedLines();
[d9b3270]2065}
[33b2094]2066
[37d7084]2067void GfxCore::GenerateDisplayListShadow()
[f4c5932]2068{
2069    SetColour(col_BLACK);
[c61aa79]2070    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2071    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[f4c5932]2072    while (trav != tend) {
2073        AddPolylineShadow(*trav);
2074        ++trav;
2075    }
2076}
2077
[d2fcc9b]2078// Plot blobs.
[d9b3270]2079void GfxCore::GenerateBlobsDisplayList()
2080{
[e633bb1]2081    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2082          m_Parent->GetNumHighlightedPts()))
2083        return;
[429465a]2084
[e633bb1]2085    // Plot blobs.
2086    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2087    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2088    BeginBlobs();
2089    while (pos != m_Parent->GetLabelsEnd()) {
[429465a]2090        const LabelInfo* label = *pos++;
2091
2092        // When more than one flag is set on a point:
2093        // search results take priority over entrance highlighting
2094        // which takes priority over fixed point
2095        // highlighting, which in turn takes priority over exported
2096        // point highlighting.
2097
2098        if (!((m_Surface && label->IsSurface()) ||
2099              (m_Legs && label->IsUnderground()) ||
2100              (!label->IsSurface() && !label->IsUnderground()))) {
2101            // if this station isn't to be displayed, skip to the next
2102            // (last case is for stns with no legs attached)
2103            continue;
2104        }
2105
[e633bb1]2106        gla_colour col;
2107
[429465a]2108        if (label->IsHighLighted()) {
2109            col = col_YELLOW;
2110        } else if (m_Entrances && label->IsEntrance()) {
2111            col = col_GREEN;
2112        } else if (m_FixedPts && label->IsFixedPt()) {
2113            col = col_RED;
2114        } else if (m_ExportedPts && label->IsExportedPt()) {
2115            col = col_TURQUOISE;
2116        } else {
2117            continue;
2118        }
2119
[e633bb1]2120        // Stations are sorted by blob type, so colour changes are infrequent.
2121        if (col != prev_col) {
[aa048c3]2122            SetColour(col);
[e633bb1]2123            prev_col = col;
[429465a]2124        }
[e633bb1]2125        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
[d9b3270]2126    }
[e633bb1]2127    EndBlobs();
[33b2094]2128}
2129
[6747314]2130void GfxCore::DrawIndicators()
[33b2094]2131{
[97ea48d]2132    // Draw colour key.
2133    if (m_ColourKey) {
[62c5fc6]2134        if (m_ColourBy == COLOUR_BY_DEPTH) {
[62da267]2135            DrawList2D(LIST_DEPTH_KEY, GetXSize() - KEY_OFFSET_X,
2136                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2137        } else if (m_ColourBy == COLOUR_BY_DATE) {
[62da267]2138            DrawList2D(LIST_DATE_KEY, GetXSize() - KEY_OFFSET_X,
2139                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2140        } else if (m_ColourBy == COLOUR_BY_ERROR) {
[62da267]2141            DrawList2D(LIST_ERROR_KEY, GetXSize() - KEY_OFFSET_X,
2142                       GetYSize() - KEY_OFFSET_Y, 0);
[1b164a0]2143        }
[33b2094]2144    }
[56da40e]2145
[203d2a7]2146    // Draw compass or elevation/heading indicators.
[eef68f9]2147    if (m_Compass || m_Clino) {
2148        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
[203d2a7]2149    }
[f433fda]2150
[56da40e]2151    // Draw scalebar.
2152    if (m_Scalebar) {
[9c37beb]2153        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
[56da40e]2154    }
[33b2094]2155}
2156
[f336ab9]2157void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2158                                    glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]2159                                    Double factor)
[f383708]2160{
[da6c802]2161    SetColour(GetSurfacePen(), factor); // FIXME : assumes surface pen is white!
[b839829]2162    PlaceVertex(v, tex_x, tex_y);
[da6c802]2163}
[f433fda]2164
[b839829]2165void GfxCore::SetDepthColour(Double z, Double factor) {
[da6c802]2166    // Set the drawing colour based on the altitude.
[78c67a6]2167    Double z_ext = m_Parent->GetDepthExtent();
[f383708]2168
[b839829]2169    z -= m_Parent->GetDepthMin();
[f383708]2170    // points arising from tubes may be slightly outside the limits...
[78c67a6]2171    if (z < 0) z = 0;
2172    if (z > z_ext) z = z_ext;
[a6f081c]2173
[2a9d2fa]2174    if (z == 0) {
2175        SetColour(GetPen(0), factor);
2176        return;
2177    }
2178
2179    assert(z_ext > 0.0);
[78c67a6]2180    Double how_far = z / z_ext;
[f383708]2181    assert(how_far >= 0.0);
2182    assert(how_far <= 1.0);
2183
[97ea48d]2184    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[0e69efe]2185    GLAPen pen1 = GetPen(band);
[97ea48d]2186    if (band < GetNumColourBands() - 1) {
[d4650b3]2187        const GLAPen& pen2 = GetPen(band + 1);
[f433fda]2188
[97ea48d]2189        Double interval = z_ext / (GetNumColourBands() - 1);
[78c67a6]2190        Double into_band = z / interval - band;
[f433fda]2191
[d4650b3]2192//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2193//             z_offset, interval, band);
2194        // FIXME: why do we need to clamp here?  Is it because the walls can
2195        // extend further up/down than the centre-line?
2196        if (into_band < 0.0) into_band = 0.0;
2197        if (into_band > 1.0) into_band = 1.0;
2198        assert(into_band >= 0.0);
2199        assert(into_band <= 1.0);
[f433fda]2200
[d4650b3]2201        pen1.Interpolate(pen2, into_band);
2202    }
[aa048c3]2203    SetColour(pen1, factor);
[b839829]2204}
[f383708]2205
[b839829]2206void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2207{
2208    SetDepthColour(v.GetZ(), factor);
[d67450e]2209    PlaceVertex(v);
[f383708]2210}
2211
[b839829]2212void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
[f336ab9]2213                                         glaTexCoord tex_x, glaTexCoord tex_y,
[b839829]2214                                         Double factor)
2215{
2216    SetDepthColour(v.GetZ(), factor);
2217    PlaceVertex(v, tex_x, tex_y);
2218}
2219
[82f584f]2220void GfxCore::SplitLineAcrossBands(int band, int band2,
[4a0e6b35]2221                                   const Vector3 &p, const Vector3 &q,
[82f584f]2222                                   Double factor)
[b5d64e6]2223{
[4a0e6b35]2224    const int step = (band < band2) ? 1 : -1;
[b5d64e6]2225    for (int i = band; i != band2; i += step) {
[4a0e6b35]2226        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2227
2228        // Find the intersection point of the line p -> q
2229        // with the plane parallel to the xy-plane with z-axis intersection z.
[d67450e]2230        assert(q.GetZ() - p.GetZ() != 0.0);
[4a0e6b35]2231
[d67450e]2232        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
[4a0e6b35]2233//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2234
[d67450e]2235        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2236        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
[4a0e6b35]2237
[d67450e]2238        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
[b5d64e6]2239    }
2240}
2241
[14acdae]2242int GfxCore::GetDepthColour(Double z) const
[b5d64e6]2243{
[82f584f]2244    // Return the (0-based) depth colour band index for a z-coordinate.
[78c67a6]2245    Double z_ext = m_Parent->GetDepthExtent();
2246    z -= m_Parent->GetDepthMin();
[2ba3882]2247    // We seem to get rounding differences causing z to sometimes be slightly
[0a2aab8]2248    // less than GetDepthMin() here, and it can certainly be true for passage
2249    // tubes, so just clamp the value to 0.
[2ba3882]2250    if (z <= 0) return 0;
[2a9d2fa]2251    assert(z_ext > 0.0);
[6027220]2252    // We seem to get rounding differences causing z to sometimes exceed z_ext
[0a2aab8]2253    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2254    // can certainly be true for passage tubes, so just clamp the value.
2255    if (z >= z_ext) return GetNumColourBands() - 1;
[97ea48d]2256    return int(z / z_ext * (GetNumColourBands() - 1));
[b5d64e6]2257}
2258
[14acdae]2259Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
[b5d64e6]2260{
[82f584f]2261    // Return the z-coordinate of the depth colour boundary between
2262    // two adjacent depth colour bands (specified by 0-based indices).
2263
2264    assert((a == b - 1) || (a == b + 1));
[97ea48d]2265    if (GetNumColourBands() == 1) return 0;
[82f584f]2266
2267    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
[78c67a6]2268    Double z_ext = m_Parent->GetDepthExtent();
[2a9d2fa]2269    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
[b5d64e6]2270}
2271
[c61aa79]2272void GfxCore::AddPolyline(const traverse & centreline)
[da6c802]2273{
2274    BeginPolyline();
2275    SetColour(GetSurfacePen());
[d4650b3]2276    vector<PointInfo>::const_iterator i = centreline.begin();
[d67450e]2277    PlaceVertex(*i);
[da6c802]2278    ++i;
2279    while (i != centreline.end()) {
[d67450e]2280        PlaceVertex(*i);
[da6c802]2281        ++i;
2282    }
2283    EndPolyline();
2284}
[2a3d328]2285
[c61aa79]2286void GfxCore::AddPolylineShadow(const traverse & centreline)
[f4c5932]2287{
2288    BeginPolyline();
[78c67a6]2289    const double z = -0.5 * m_Parent->GetZExtent();
[d4650b3]2290    vector<PointInfo>::const_iterator i = centreline.begin();
[78c67a6]2291    PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]2292    ++i;
2293    while (i != centreline.end()) {
[78c67a6]2294        PlaceVertex(i->GetX(), i->GetY(), z);
[f4c5932]2295        ++i;
2296    }
2297    EndPolyline();
2298}
2299
[c61aa79]2300void GfxCore::AddPolylineDepth(const traverse & centreline)
[da6c802]2301{
2302    BeginPolyline();
[d4650b3]2303    vector<PointInfo>::const_iterator i, prev_i;
[da6c802]2304    i = centreline.begin();
[ee7af72]2305    int band0 = GetDepthColour(i->GetZ());
[d67450e]2306    PlaceVertexWithDepthColour(*i);
[da6c802]2307    prev_i = i;
2308    ++i;
2309    while (i != centreline.end()) {
[ee7af72]2310        int band = GetDepthColour(i->GetZ());
[da6c802]2311        if (band != band0) {
[d67450e]2312            SplitLineAcrossBands(band0, band, *prev_i, *i);
[da6c802]2313            band0 = band;
2314        }
[d67450e]2315        PlaceVertexWithDepthColour(*i);
[da6c802]2316        prev_i = i;
2317        ++i;
2318    }
2319    EndPolyline();
2320}
2321
[f433fda]2322void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
[14acdae]2323                               const Vector3 &c, const Vector3 &d)
[da6c802]2324{
2325    Vector3 normal = (a - c) * (d - b);
2326    normal.normalise();
2327    Double factor = dot(normal, light) * .3 + .7;
[f336ab9]2328    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2329    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
[9b57c71b]2330    // FIXME: should plot triangles instead to avoid rendering glitches.
[da6c802]2331    BeginQuadrilaterals();
[b839829]2332    PlaceVertexWithColour(a, 0, 0, factor);
2333    PlaceVertexWithColour(b, w, 0, factor);
2334    PlaceVertexWithColour(c, w, h, factor);
2335    PlaceVertexWithColour(d, 0, h, factor);
[da6c802]2336    EndQuadrilaterals();
2337}
2338
2339void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2340                                    const Vector3 &c, const Vector3 &d)
[2b02270]2341{
2342    Vector3 normal = (a - c) * (d - b);
2343    normal.normalise();
2344    Double factor = dot(normal, light) * .3 + .7;
2345    int a_band, b_band, c_band, d_band;
[d67450e]2346    a_band = GetDepthColour(a.GetZ());
[97ea48d]2347    a_band = min(max(a_band, 0), GetNumColourBands());
[d67450e]2348    b_band = GetDepthColour(b.GetZ());
[97ea48d]2349    b_band = min(max(b_band, 0), GetNumColourBands());
[d67450e]2350    c_band = GetDepthColour(c.GetZ());
[97ea48d]2351    c_band = min(max(c_band, 0), GetNumColourBands());
[d67450e]2352    d_band = GetDepthColour(d.GetZ());
[97ea48d]2353    d_band = min(max(d_band, 0), GetNumColourBands());
[97fb83a]2354    // All this splitting is incorrect - we need to make a separate polygon
2355    // for each depth band...
[f336ab9]2356    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2357    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
[b5d64e6]2358    BeginPolygon();
[d67450e]2359////    PlaceNormal(normal);
[b839829]2360    PlaceVertexWithDepthColour(a, 0, 0, factor);
[2b02270]2361    if (a_band != b_band) {
[b5d64e6]2362        SplitLineAcrossBands(a_band, b_band, a, b, factor);
[2b02270]2363    }
[b839829]2364    PlaceVertexWithDepthColour(b, w, 0, factor);
[2b02270]2365    if (b_band != c_band) {
[b5d64e6]2366        SplitLineAcrossBands(b_band, c_band, b, c, factor);
[2b02270]2367    }
[b839829]2368    PlaceVertexWithDepthColour(c, w, h, factor);
[2b02270]2369    if (c_band != d_band) {
[b5d64e6]2370        SplitLineAcrossBands(c_band, d_band, c, d, factor);
[2b02270]2371    }
[b839829]2372    PlaceVertexWithDepthColour(d, 0, h, factor);
[2b02270]2373    if (d_band != a_band) {
[b5d64e6]2374        SplitLineAcrossBands(d_band, a_band, d, a, factor);
[2b02270]2375    }
[b5d64e6]2376    EndPolygon();
[2b02270]2377}
2378
[1ee204e]2379void GfxCore::SetColourFromDate(int date, Double factor)
[d4650b3]2380{
2381    // Set the drawing colour based on a date.
2382
[1ee204e]2383    if (date == -1) {
[2043961]2384        // Undated.
[d4650b3]2385        SetColour(GetSurfacePen(), factor);
2386        return;
2387    }
2388
[1ee204e]2389    int date_offset = date - m_Parent->GetDateMin();
[2043961]2390    if (date_offset == 0) {
2391        // Earliest date - handle as a special case for the single date case.
2392        SetColour(GetPen(0), factor);
2393        return;
2394    }
[d4650b3]2395
[2043961]2396    int date_ext = m_Parent->GetDateExtent();
[d4650b3]2397    Double how_far = (Double)date_offset / date_ext;
2398    assert(how_far >= 0.0);
2399    assert(how_far <= 1.0);
2400
[97ea48d]2401    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[d4650b3]2402    GLAPen pen1 = GetPen(band);
[97ea48d]2403    if (band < GetNumColourBands() - 1) {
[d4650b3]2404        const GLAPen& pen2 = GetPen(band + 1);
2405
[97ea48d]2406        Double interval = date_ext / (GetNumColourBands() - 1);
[d4650b3]2407        Double into_band = date_offset / interval - band;
2408
2409//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2410//             z_offset, interval, band);
2411        // FIXME: why do we need to clamp here?  Is it because the walls can
2412        // extend further up/down than the centre-line?
2413        if (into_band < 0.0) into_band = 0.0;
2414        if (into_band > 1.0) into_band = 1.0;
2415        assert(into_band >= 0.0);
2416        assert(into_band <= 1.0);
2417
2418        pen1.Interpolate(pen2, into_band);
2419    }
2420    SetColour(pen1, factor);
2421}
2422
[c61aa79]2423void GfxCore::AddPolylineDate(const traverse & centreline)
[d4650b3]2424{
2425    BeginPolyline();
2426    vector<PointInfo>::const_iterator i, prev_i;
2427    i = centreline.begin();
[1ee204e]2428    int date = i->GetDate();
[d4650b3]2429    SetColourFromDate(date, 1.0);
[d67450e]2430    PlaceVertex(*i);
[d4650b3]2431    prev_i = i;
2432    while (++i != centreline.end()) {
[1ee204e]2433        int newdate = i->GetDate();
[d4650b3]2434        if (newdate != date) {
2435            EndPolyline();
2436            BeginPolyline();
2437            date = newdate;
2438            SetColourFromDate(date, 1.0);
[d67450e]2439            PlaceVertex(*prev_i);
[d4650b3]2440        }
[d67450e]2441        PlaceVertex(*i);
[d4650b3]2442        prev_i = i;
2443    }
2444    EndPolyline();
2445}
2446
[1ee204e]2447static int static_date_hack; // FIXME
[d4650b3]2448
2449void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2450                                   const Vector3 &c, const Vector3 &d)
2451{
2452    Vector3 normal = (a - c) * (d - b);
2453    normal.normalise();
2454    Double factor = dot(normal, light) * .3 + .7;
2455    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2456    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2457    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2458    BeginQuadrilaterals();
[d67450e]2459////    PlaceNormal(normal);
[d4650b3]2460    SetColourFromDate(static_date_hack, factor);
[b839829]2461    PlaceVertex(a, 0, 0);
2462    PlaceVertex(b, w, 0);
2463    PlaceVertex(c, w, h);
2464    PlaceVertex(d, 0, h);
2465    EndQuadrilaterals();
[d4650b3]2466}
2467
[c61aa79]2468static double static_E_hack; // FIXME
2469
2470void GfxCore::SetColourFromError(double E, Double factor)
2471{
2472    // Set the drawing colour based on an error value.
2473
2474    if (E < 0) {
2475        SetColour(GetSurfacePen(), factor);
2476        return;
2477    }
2478
2479    Double how_far = E / MAX_ERROR;
2480    assert(how_far >= 0.0);
2481    if (how_far > 1.0) how_far = 1.0;
2482
[97ea48d]2483    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[c61aa79]2484    GLAPen pen1 = GetPen(band);
[97ea48d]2485    if (band < GetNumColourBands() - 1) {
[c61aa79]2486        const GLAPen& pen2 = GetPen(band + 1);
2487
[97ea48d]2488        Double interval = MAX_ERROR / (GetNumColourBands() - 1);
[c61aa79]2489        Double into_band = E / interval - band;
2490
2491//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2492//             z_offset, interval, band);
2493        // FIXME: why do we need to clamp here?  Is it because the walls can
2494        // extend further up/down than the centre-line?
2495        if (into_band < 0.0) into_band = 0.0;
2496        if (into_band > 1.0) into_band = 1.0;
2497        assert(into_band >= 0.0);
2498        assert(into_band <= 1.0);
2499
2500        pen1.Interpolate(pen2, into_band);
2501    }
2502    SetColour(pen1, factor);
2503}
2504
2505void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2506                                    const Vector3 &c, const Vector3 &d)
2507{
2508    Vector3 normal = (a - c) * (d - b);
2509    normal.normalise();
2510    Double factor = dot(normal, light) * .3 + .7;
2511    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2512    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2513    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2514    BeginQuadrilaterals();
[c61aa79]2515////    PlaceNormal(normal);
2516    SetColourFromError(static_E_hack, factor);
[b839829]2517    PlaceVertex(a, 0, 0);
2518    PlaceVertex(b, w, 0);
2519    PlaceVertex(c, w, h);
2520    PlaceVertex(d, 0, h);
2521    EndQuadrilaterals();
[c61aa79]2522}
2523
2524void GfxCore::AddPolylineError(const traverse & centreline)
2525{
2526    BeginPolyline();
2527    SetColourFromError(centreline.E, 1.0);
2528    vector<PointInfo>::const_iterator i;
2529    for(i = centreline.begin(); i != centreline.end(); ++i) {
2530        PlaceVertex(*i);
2531    }
2532    EndPolyline();
2533}
2534
[da6c802]2535void
[384534c]2536GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
[3ddcad8]2537{
[b3852b5]2538    assert(centreline.size() > 1);
[3ddcad8]2539    Vector3 U[4];
[ee05463]2540    XSect prev_pt_v;
[3ddcad8]2541    Vector3 last_right(1.0, 0.0, 0.0);
2542
[c61aa79]2543//  FIXME: it's not simple to set the colour of a tube based on error...
2544//    static_E_hack = something...
[fc68ad5]2545    vector<XSect>::iterator i = centreline.begin();
[ee05463]2546    vector<XSect>::size_type segment = 0;
[3ddcad8]2547    while (i != centreline.end()) {
2548        // get the coordinates of this vertex
[fc68ad5]2549        XSect & pt_v = *i++;
[3ddcad8]2550
2551        double z_pitch_adjust = 0.0;
2552        bool cover_end = false;
2553
2554        Vector3 right, up;
2555
2556        const Vector3 up_v(0.0, 0.0, 1.0);
2557
2558        if (segment == 0) {
2559            assert(i != centreline.end());
2560            // first segment
2561
2562            // get the coordinates of the next vertex
[ee05463]2563            const XSect & next_pt_v = *i;
[3ddcad8]2564
2565            // calculate vector from this pt to the next one
[d67450e]2566            Vector3 leg_v = next_pt_v - pt_v;
[3ddcad8]2567
2568            // obtain a vector in the LRUD plane
2569            right = leg_v * up_v;
2570            if (right.magnitude() == 0) {
2571                right = last_right;
2572                // Obtain a second vector in the LRUD plane,
2573                // perpendicular to the first.
[760ad29d]2574                //up = right * leg_v;
2575                up = up_v;
[3ddcad8]2576            } else {
2577                last_right = right;
2578                up = up_v;
[da6c802]2579            }
2580
[3ddcad8]2581            cover_end = true;
[d4650b3]2582            static_date_hack = next_pt_v.GetDate();
[3ddcad8]2583        } else if (segment + 1 == centreline.size()) {
2584            // last segment
2585
2586            // Calculate vector from the previous pt to this one.
[d67450e]2587            Vector3 leg_v = pt_v - prev_pt_v;
[3ddcad8]2588
2589            // Obtain a horizontal vector in the LRUD plane.
2590            right = leg_v * up_v;
2591            if (right.magnitude() == 0) {
[d67450e]2592                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
[3ddcad8]2593                // Obtain a second vector in the LRUD plane,
2594                // perpendicular to the first.
[760ad29d]2595                //up = right * leg_v;
2596                up = up_v;
[3ddcad8]2597            } else {
2598                last_right = right;
2599                up = up_v;
2600            }
[da6c802]2601
[3ddcad8]2602            cover_end = true;
[d4650b3]2603            static_date_hack = pt_v.GetDate();
[3ddcad8]2604        } else {
2605            assert(i != centreline.end());
2606            // Intermediate segment.
2607
2608            // Get the coordinates of the next vertex.
[ee05463]2609            const XSect & next_pt_v = *i;
[3ddcad8]2610
2611            // Calculate vectors from this vertex to the
2612            // next vertex, and from the previous vertex to
2613            // this one.
[d67450e]2614            Vector3 leg1_v = pt_v - prev_pt_v;
2615            Vector3 leg2_v = next_pt_v - pt_v;
[3ddcad8]2616
2617            // Obtain horizontal vectors perpendicular to
2618            // both legs, then normalise and average to get
2619            // a horizontal bisector.
2620            Vector3 r1 = leg1_v * up_v;
2621            Vector3 r2 = leg2_v * up_v;
2622            r1.normalise();
2623            r2.normalise();
2624            right = r1 + r2;
2625            if (right.magnitude() == 0) {
2626                // This is the "mid-pitch" case...
2627                right = last_right;
2628            }
2629            if (r1.magnitude() == 0) {
2630                Vector3 n = leg1_v;
2631                n.normalise();
[d67450e]2632                z_pitch_adjust = n.GetZ();
2633                //up = Vector3(0, 0, leg1_v.GetZ());
[760ad29d]2634                //up = right * up;
2635                up = up_v;
[3ddcad8]2636
2637                // Rotate pitch section to minimise the
2638                // "tortional stress" - FIXME: use
2639                // triangles instead of rectangles?
2640                int shift = 0;
2641                Double maxdotp = 0;
2642
2643                // Scale to unit vectors in the LRUD plane.
2644                right.normalise();
2645                up.normalise();
2646                Vector3 vec = up - right;
2647                for (int orient = 0; orient <= 3; ++orient) {
[d67450e]2648                    Vector3 tmp = U[orient] - prev_pt_v;
[3ddcad8]2649                    tmp.normalise();
2650                    Double dotp = dot(vec, tmp);
2651                    if (dotp > maxdotp) {
2652                        maxdotp = dotp;
2653                        shift = orient;
2654                    }
2655                }
2656                if (shift) {
2657                    if (shift != 2) {
2658                        Vector3 temp(U[0]);
[b3852b5]2659                        U[0] = U[shift];
2660                        U[shift] = U[2];
2661                        U[2] = U[shift ^ 2];
2662                        U[shift ^ 2] = temp;
[ee7af72]2663                    } else {
[3ddcad8]2664                        swap(U[0], U[2]);
2665                        swap(U[1], U[3]);
[ee7af72]2666                    }
[3ddcad8]2667                }
2668#if 0
2669                // Check that the above code actually permuted
2670                // the vertices correctly.
2671                shift = 0;
2672                maxdotp = 0;
[b3852b5]2673                for (int j = 0; j <= 3; ++j) {
[d67450e]2674                    Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]2675                    tmp.normalise();
2676                    Double dotp = dot(vec, tmp);
2677                    if (dotp > maxdotp) {
2678                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
[b3852b5]2679                        shift = j;
[da6c802]2680                    }
[3ddcad8]2681                }
2682                if (shift) {
2683                    printf("New shift = %d!\n", shift);
2684                    shift = 0;
2685                    maxdotp = 0;
[b3852b5]2686                    for (int j = 0; j <= 3; ++j) {
[d67450e]2687                        Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]2688                        tmp.normalise();
2689                        Double dotp = dot(vec, tmp);
[b3852b5]2690                        printf("    %d : %.8f\n", j, dotp);
[da6c802]2691                    }
2692                }
[3ddcad8]2693#endif
2694            } else if (r2.magnitude() == 0) {
2695                Vector3 n = leg2_v;
2696                n.normalise();
[d67450e]2697                z_pitch_adjust = n.GetZ();
2698                //up = Vector3(0, 0, leg2_v.GetZ());
[760ad29d]2699                //up = right * up;
2700                up = up_v;
[3ddcad8]2701            } else {
2702                up = up_v;
[da6c802]2703            }
[3ddcad8]2704            last_right = right;
[d4650b3]2705            static_date_hack = pt_v.GetDate();
[da6c802]2706        }
2707
[3ddcad8]2708        // Scale to unit vectors in the LRUD plane.
2709        right.normalise();
2710        up.normalise();
[33b2094]2711
[3ddcad8]2712        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
[ce2f3ce]2713
[57a3cd4]2714        Double l = fabs(pt_v.GetL());
2715        Double r = fabs(pt_v.GetR());
2716        Double u = fabs(pt_v.GetU());
2717        Double d = fabs(pt_v.GetD());
[3ddcad8]2718
2719        // Produce coordinates of the corners of the LRUD "plane".
2720        Vector3 v[4];
[d67450e]2721        v[0] = pt_v - right * l + up * u;
2722        v[1] = pt_v + right * r + up * u;
2723        v[2] = pt_v + right * r - up * d;
2724        v[3] = pt_v - right * l - up * d;
[3ddcad8]2725
[384534c]2726        if (draw) {
2727            if (segment > 0) {
2728                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
2729                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
2730                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
2731                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
2732            }
[9eb58d0]2733
[384534c]2734            if (cover_end) {
2735                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
2736            }
[3ddcad8]2737        }
[9eb58d0]2738
[3ddcad8]2739        prev_pt_v = pt_v;
2740        U[0] = v[0];
2741        U[1] = v[1];
2742        U[2] = v[2];
2743        U[3] = v[3];
[9eb58d0]2744
[fc68ad5]2745        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
2746
[3ddcad8]2747        ++segment;
2748    }
[33b2094]2749}
[b13aee4]2750
2751void GfxCore::FullScreenMode()
2752{
[ea940373]2753    m_Parent->ViewFullScreen();
[b13aee4]2754}
[fdfa926]2755
2756bool GfxCore::IsFullScreen() const
2757{
2758    return m_Parent->IsFullScreen();
2759}
[1690fa9]2760
[46361bc]2761void
2762GfxCore::MoveViewer(double forward, double up, double right)
2763{
[e577f89]2764    double cT = cos(rad(m_TiltAngle));
2765    double sT = sin(rad(m_TiltAngle));
2766    double cP = cos(rad(m_PanAngle));
2767    double sP = sin(rad(m_PanAngle));
[7a57dc7]2768    Vector3 v_forward(cT * sP, cT * cP, sT);
2769    Vector3 v_up(sT * sP, sT * cP, -cT);
[867a1141]2770    Vector3 v_right(-cP, sP, 0);
[d4a5aaf]2771    assert(fabs(dot(v_forward, v_up)) < 1e-6);
2772    assert(fabs(dot(v_forward, v_right)) < 1e-6);
2773    assert(fabs(dot(v_right, v_up)) < 1e-6);
[46361bc]2774    Vector3 move = v_forward * forward + v_up * up + v_right * right;
[d67450e]2775    AddTranslation(-move);
[d877aa2]2776    // Show current position.
[d67450e]2777    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
[46361bc]2778    ForceRefresh();
2779}
2780
[1690fa9]2781PresentationMark GfxCore::GetView() const
2782{
[d67450e]2783    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
[7a57dc7]2784                            m_PanAngle, -m_TiltAngle, m_Scale);
[1690fa9]2785}
2786
2787void GfxCore::SetView(const PresentationMark & p)
2788{
2789    m_SwitchingTo = 0;
[d67450e]2790    SetTranslation(p - m_Parent->GetOffset());
[1690fa9]2791    m_PanAngle = p.angle;
[7a57dc7]2792    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
[08253d9]2793    SetRotation(m_PanAngle, m_TiltAngle);
[1690fa9]2794    SetScale(p.scale);
2795    ForceRefresh();
2796}
2797
[128fac4]2798void GfxCore::PlayPres(double speed, bool change_speed) {
2799    if (!change_speed || presentation_mode == 0) {
2800        if (speed == 0.0) {
2801            presentation_mode = 0;
2802            return;
2803        }
2804        presentation_mode = PLAYING;
2805        next_mark = m_Parent->GetPresMark(MARK_FIRST);
2806        SetView(next_mark);
2807        next_mark_time = 0; // There already!
2808        this_mark_total = 0;
2809        pres_reverse = (speed < 0);
2810    }
2811
[d67450e]2812    if (change_speed) pres_speed = speed;
2813
[128fac4]2814    if (speed != 0.0) {
2815        bool new_pres_reverse = (speed < 0);
2816        if (new_pres_reverse != pres_reverse) {
2817            pres_reverse = new_pres_reverse;
2818            if (pres_reverse) {
2819                next_mark = m_Parent->GetPresMark(MARK_PREV);
2820            } else {
2821                next_mark = m_Parent->GetPresMark(MARK_NEXT);
2822            }
2823            swap(this_mark_total, next_mark_time);
2824        }
2825    }
[1690fa9]2826}
[6a4cdcb6]2827
[da6c802]2828void GfxCore::SetColourBy(int colour_by) {
2829    m_ColourBy = colour_by;
2830    switch (colour_by) {
2831        case COLOUR_BY_DEPTH:
2832            AddQuad = &GfxCore::AddQuadrilateralDepth;
2833            AddPoly = &GfxCore::AddPolylineDepth;
2834            break;
[d4650b3]2835        case COLOUR_BY_DATE:
2836            AddQuad = &GfxCore::AddQuadrilateralDate;
2837            AddPoly = &GfxCore::AddPolylineDate;
2838            break;
[c61aa79]2839        case COLOUR_BY_ERROR:
2840            AddQuad = &GfxCore::AddQuadrilateralError;
2841            AddPoly = &GfxCore::AddPolylineError;
2842            break;
[da6c802]2843        default: // case COLOUR_BY_NONE:
2844            AddQuad = &GfxCore::AddQuadrilateral;
2845            AddPoly = &GfxCore::AddPolyline;
2846            break;
2847    }
2848
[d2fcc9b]2849    InvalidateList(LIST_UNDERGROUND_LEGS);
[c61aa79]2850    InvalidateList(LIST_SURFACE_LEGS);
[d2fcc9b]2851    InvalidateList(LIST_TUBES);
[da6c802]2852
2853    ForceRefresh();
2854}
2855
[6a4cdcb6]2856bool GfxCore::ExportMovie(const wxString & fnm)
2857{
2858    int width;
2859    int height;
2860    GetSize(&width, &height);
[028829f]2861    // Round up to next multiple of 2 (required by ffmpeg).
2862    width += (width & 1);
[6a4cdcb6]2863    height += (height & 1);
2864
[75d4a2b]2865    movie = new MovieMaker();
[6a4cdcb6]2866
[98a3786]2867    // FIXME: This should really use fn_str() - currently we probably can't
2868    // save to a Unicode path on wxmsw.
[75d4a2b]2869    if (!movie->Open(fnm.mb_str(), width, height)) {
[091069f]2870        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
[75d4a2b]2871        delete movie;
[81f1266]2872        movie = NULL;
[6a4cdcb6]2873        return false;
2874    }
[f433fda]2875
[d10d369]2876    PlayPres(1);
[6a4cdcb6]2877    return true;
2878}
[223f1ad]2879
[ce403f1]2880void
2881GfxCore::OnPrint(const wxString &filename, const wxString &title,
2882                 const wxString &datestamp)
2883{
2884    svxPrintDlg * p;
2885    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
2886                        m_PanAngle, m_TiltAngle,
[5624403]2887                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
[5940815]2888                        true);
[6d1bc83]2889    p->Show(true);
[ce403f1]2890}
2891
[5940815]2892void
[223f1ad]2893GfxCore::OnExport(const wxString &filename, const wxString &title)
2894{
[384534c]2895    // Fill in "right_bearing" for each cross-section.
2896    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2897    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2898    while (trav != tend) {
2899        SkinPassage(*trav, false);
2900        ++trav;
2901    }
2902
[5940815]2903    svxPrintDlg * p;
[5627cbb]2904    p = new svxPrintDlg(m_Parent, filename, title, wxString(),
[5940815]2905                        m_PanAngle, m_TiltAngle,
[5624403]2906                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
[5940815]2907                        false);
[6d1bc83]2908    p->Show(true);
[223f1ad]2909}
[e2c1671]2910
2911static wxCursor
2912make_cursor(const unsigned char * bits, const unsigned char * mask,
2913            int hotx, int hoty)
2914{
[b72f4b5]2915#if defined __WXMSW__ || defined __WXMAC__
[7f3fe6d]2916    wxBitmap cursor_bitmap(reinterpret_cast<const char *>(bits), 32, 32);
2917    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
[4dc4384]2918    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
[e2c1671]2919    wxImage cursor_image = cursor_bitmap.ConvertToImage();
2920    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
2921    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
[7f3fe6d]2922    return wxCursor(cursor_image);
[e2c1671]2923#else
2924    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
[4dc4384]2925                    (const char *)mask, wxBLACK, wxWHITE);
[e2c1671]2926#endif
2927}
2928
2929const
2930#include "hand.xbm"
2931const
2932#include "handmask.xbm"
2933
2934const
2935#include "brotate.xbm"
2936const
2937#include "brotatemask.xbm"
2938
2939const
2940#include "vrotate.xbm"
2941const
2942#include "vrotatemask.xbm"
2943
2944const
2945#include "rotate.xbm"
2946const
2947#include "rotatemask.xbm"
2948
[ecf2d23]2949const
2950#include "rotatezoom.xbm"
2951const
2952#include "rotatezoommask.xbm"
2953
[e2c1671]2954void
2955GfxCore::SetCursor(GfxCore::cursor new_cursor)
2956{
2957    // Check if we're already showing that cursor.
2958    if (current_cursor == new_cursor) return;
2959
2960    current_cursor = new_cursor;
2961    switch (current_cursor) {
2962        case GfxCore::CURSOR_DEFAULT:
2963            GLACanvas::SetCursor(wxNullCursor);
2964            break;
2965        case GfxCore::CURSOR_POINTING_HAND:
2966            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
2967            break;
2968        case GfxCore::CURSOR_DRAGGING_HAND:
2969            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
2970            break;
2971        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
2972            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
2973            break;
2974        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
2975            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
2976            break;
2977        case GfxCore::CURSOR_ROTATE_VERTICALLY:
2978            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
2979            break;
2980        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
2981            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
2982            break;
2983        case GfxCore::CURSOR_ZOOM:
2984            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
2985            break;
[ecf2d23]2986        case GfxCore::CURSOR_ZOOM_ROTATE:
2987            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
2988            break;
[e2c1671]2989    }
2990}
[6b061db]2991
2992bool GfxCore::MeasuringLineActive() const
2993{
2994    if (Animating()) return false;
2995    return (m_here.IsValid() && !m_here_is_temporary) || m_there.IsValid();
2996}
[acdb8aa]2997
2998bool GfxCore::HandleRClick(wxPoint point)
2999{
3000    if (PointWithinCompass(point)) {
3001        // Pop up menu.
3002        wxMenu menu;
[055bfc58]3003        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3004        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3005        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3006        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3007        menu.AppendSeparator();
[4d2301e]3008        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
[acdb8aa]3009        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]3010        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3011        PopupMenu(&menu);
3012        return true;
3013    }
3014
3015    if (PointWithinClino(point)) {
3016        // Pop up menu.
3017        wxMenu menu;
[055bfc58]3018        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3019        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3020        menu.AppendSeparator();
[acdb8aa]3021        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3022        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]3023        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3024        PopupMenu(&menu);
[acdb8aa]3025        return true;
3026    }
3027
3028    if (PointWithinScaleBar(point)) {
3029        // Pop up menu.
3030        wxMenu menu;
3031        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3032        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]3033        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3034        PopupMenu(&menu);
3035        return true;
3036    }
3037
3038    if (PointWithinColourKey(point)) {
3039        // Pop up menu.
3040        wxMenu menu;
[d43fa84]3041        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3042        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3043        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
3044        menu.AppendSeparator();
[97ea48d]3045        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
[d43fa84]3046        if (m_ColourBy == COLOUR_BY_DEPTH)
3047            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]3048        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3049        PopupMenu(&menu);
3050        return true;
3051    }
3052
3053    return false;
3054}
Note: See TracBrowser for help on using the repository browser.