source: git/src/gfxcore.cc @ 419befc

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 419befc was 5624403, checked in by Olly Betts <olly@…>, 13 years ago

src/gfxcore.cc,src/printwx.cc,src/printwx.h: Default the export/print
settings for passage related things to the "tubes" setting in the
OpenGL view.

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