source: git/src/gfxcore.cc @ a775268

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

src/gfxcore.cc: Remove duplicate call to PopupMenu?().

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

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