source: git/src/gfxcore.cc @ c6d5c1c

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

src/: Push survey pane size tracking down into GLACanvas, and
automatically track which lists should be invalidated on a
changes in the width or the height of the pane.

git-svn-id: file:///home/survex-svn/survex/trunk@3786 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

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