OpenCPN Partial API docs
Loading...
Searching...
No Matches
gl_chart_canvas.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2014 by David S. Register *
3 * Copyright (C) 2014 Sean D'Epagnier
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
17 ***************************************************************************/
18
24
25// For compilers that support precompilation, includes "wx.h".
26#include <wx/wxprec.h>
27
28#ifndef WX_PRECOMP
29#include <wx/wx.h>
30#endif // precompiled headers
31
32#include "dychart.h"
33
34#include <algorithm>
35#include <stdint.h>
36#include <vector>
37
38#include <wx/brush.h>
39#include <wx/colour.h>
40#include <wx/dcmemory.h>
41#include <wx/dynarray.h>
42#include <wx/event.h>
43#include <wx/font.h>
44#include <wx/gdicmn.h>
45#include <wx/glcanvas.h>
46#include <wx/image.h>
47#include <wx/log.h>
48#include <wx/pen.h>
49#include <wx/progdlg.h>
50#include <wx/stopwatch.h>
51#include <wx/string.h>
52#include <wx/tokenzr.h>
53#include <wx/utils.h>
54#include <wx/window.h>
55
56#include "ocpn-nlohmann/json.hpp"
57
58#include "model/base_platform.h"
59#include "model/config_vars.h"
60#include "model/gui_vars.h"
61#include "model/own_ship.h"
62#include "model/plugin_comm.h"
63#include "model/route.h"
64#include "model/routeman.h"
65#include "model/track.h"
66
67#include "ais.h"
68#include "chartbase.h"
69#include "chart_ctx_factory.h"
70#include "chartdb.h"
71#include "chartimg.h"
72#include "chcanv.h"
73#include "ch_info_win.h"
74#include "cm93.h" // for chart outline draw
75#include "color_handler.h"
76#include "compass.h"
77#include "emboss_data.h"
78#include "font_mgr.h"
79#include "gl_chart_canvas.h"
80#include "gl_tex_cache.h"
81#include "gshhs.h"
82#include "ienc_toolbar.h"
83#include "lz4.h"
84#include "mbtiles.h"
85#include "mipmap/mipmap.h"
86#include "mui_bar.h"
87#include "navutil.h"
88#include "ocpn_platform.h"
89#include "piano.h"
90#include "pluginmanager.h"
91#include "quilt.h"
92#include "rollover_win.h"
93#include "route_gui.h"
94#include "route_point_gui.h"
95#include "s52plib.h"
96#include "s57chart.h" // for ArrayOfS57Obj
97#include "s57_load.h"
98#include "s57_ocpn_utils.h"
99#include "shapefile_basemap.h"
100#include "tcmgr.h"
101#include "toolbar.h"
102#include "TexFont.h"
103#include "thumbwin.h"
104#include "toolbar.h"
105#include "track_gui.h"
106#include "viewport.h"
107
108#ifdef USE_ANDROID_GLES2
109#include <GLES2/gl2.h>
110#include "linmath.h"
111#include "shaders.h"
112#endif
113
114#ifdef __ANDROID__
115#include "androidUTIL.h"
116#elif defined(__WXQT__) || defined(__WXGTK__)
117#include <GL/glx.h>
118#endif
119
120#ifndef GL_ETC1_RGB8_OES
121#define GL_ETC1_RGB8_OES 0x8D64
122#endif
123
124#ifndef GL_DEPTH_STENCIL_ATTACHMENT
125#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
126#endif
127
128#ifdef __WXMSW__
129#define printf printf2
130int __cdecl printf2(const char *format, ...);
131#endif
132
133#if defined(__ANDROID__)
134#include "androidUTIL.h"
135#elif defined(__WXQT__) || defined(__WXGTK__) || defined(FLATPAK)
136#include <GL/glew.h>
137#endif
138
139#ifdef __ANDROID__
140// arm gcc compiler has a lot of trouble passing doubles as function aruments.
141// We don't really need double precision here, so fix with a (faster) macro.
142extern "C" void glOrthof(float left, float right, float bottom, float top,
143 float near, float far);
144#define glOrtho(a, b, c, d, e, f) \
145 ; \
146 glOrthof(a, b, c, d, e, f);
147
148#endif
149
150#ifdef USE_ANDROID_GLES2
151#include <GLES2/gl2.h>
152#endif
153
154#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
155#include "linmath.h"
156#include "shaders.h"
158#endif
159
160#if defined(__UNIX__) && !defined(__WXOSX__)
161// high resolution stopwatch for profiling
162class OCPNStopWatch {
163public:
164 OCPNStopWatch() { Reset(); }
165 void Reset() { clock_gettime(CLOCK_REALTIME, &tp); }
166
167 double GetTime() {
168 timespec tp_end;
169 clock_gettime(CLOCK_REALTIME, &tp_end);
170 return (tp_end.tv_sec - tp.tv_sec) * 1.e3 +
171 (tp_end.tv_nsec - tp.tv_nsec) / 1.e6;
172 }
173
174private:
175 timespec tp;
176};
177#endif
178
179// extern GLenum g_texture_rectangle_format;
180
181extern bool g_running;
182
183static wxColor s_regionColor;
184static float g_GLMinCartographicLineWidth;
185// MacOS has some missing parts:
186#ifndef APIENTRY
187#define APIENTRY
188#endif
189#ifndef APIENTRYP
190#define APIENTRYP APIENTRY *
191#endif
192#ifndef GLAPI
193#define GLAPI extern
194#endif
195
196#ifndef GL_COMPRESSED_RGB_FXT1_3DFX
197#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0
198#endif
199
200GLuint g_raster_format = GL_RGB;
201
202// OpenGL/GLES bindings
203PFNGLGENFRAMEBUFFERSEXTPROC s_glGenFramebuffers;
204PFNGLGENRENDERBUFFERSEXTPROC s_glGenRenderbuffers;
205PFNGLFRAMEBUFFERTEXTURE2DEXTPROC s_glFramebufferTexture2D;
206PFNGLBINDFRAMEBUFFEREXTPROC s_glBindFramebuffer;
207PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC s_glFramebufferRenderbuffer;
208PFNGLRENDERBUFFERSTORAGEEXTPROC s_glRenderbufferStorage;
209PFNGLBINDRENDERBUFFEREXTPROC s_glBindRenderbuffer;
210PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC s_glCheckFramebufferStatus;
211PFNGLDELETEFRAMEBUFFERSEXTPROC s_glDeleteFramebuffers;
212PFNGLDELETERENDERBUFFERSEXTPROC s_glDeleteRenderbuffers;
213
214PFNGLCOMPRESSEDTEXIMAGE2DPROC s_glCompressedTexImage2D;
215PFNGLGETCOMPRESSEDTEXIMAGEPROC s_glGetCompressedTexImage;
216
217// Vertex Buffer Object (VBO) support
218PFNGLGENBUFFERSPROC s_glGenBuffers;
219PFNGLBINDBUFFERPROC s_glBindBuffer;
220PFNGLBUFFERDATAPROC s_glBufferData;
221PFNGLDELETEBUFFERSPROC s_glDeleteBuffers;
222
223#ifndef USE_ANDROID_GLES2
224// #define glDeleteFramebuffers(a, b) (s_glDeleteFramebuffers)(a, b);
225// #define glDeleteRenderbuffers(a, b) (s_glDeleteRenderbuffers)(a, b);
226#endif
227
228typedef void(APIENTRYP PFNGLGETBUFFERPARAMETERIV)(GLenum target, GLenum value,
229 GLint *data);
230PFNGLGETBUFFERPARAMETERIV s_glGetBufferParameteriv;
231
232static bool b_timeGL;
233static int panx, pany;
234
235bool g_true_zoom;
236
237#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
238std::vector<GLfloat> s_tess_vertex_work;
239static GLenum s_tess_mode;
240static ViewPort s_tessVP;
241#endif
242
243bool glChartCanvas::s_b_useScissorTest;
244bool glChartCanvas::s_b_useStencil;
245bool glChartCanvas::s_b_useStencilAP;
246bool glChartCanvas::s_b_useFBO;
247
248#if 0
249/* for debugging */
250static void print_region(OCPNRegion &Region)
251{
252 OCPNRegionIterator upd ( Region );
253 while ( upd.HaveRects() )
254 {
255 wxRect rect = upd.GetRect();
256 printf("[(%d, %d) (%d, %d)] ", rect.x, rect.y, rect.width, rect.height);
257 upd.NextRect();
258 }
259}
260
261#endif
262
263GLboolean QueryExtension(const char *extName) {
264 /*
265 ** Search for extName in the extensions string. Use of strstr()
266 ** is not sufficient because extension names can be prefixes of
267 ** other extension names. Could use strtok() but the constant
268 ** string returned by glGetString might be in read-only memory.
269 */
270 char *p;
271 char *end;
272 int extNameLen;
273
274 extNameLen = strlen(extName);
275
276 p = (char *)glGetString(GL_EXTENSIONS);
277 if (NULL == p) {
278 return GL_FALSE;
279 }
280
281 end = p + strlen(p);
282
283 while (p < end) {
284 int n = strcspn(p, " ");
285 if ((extNameLen == n) && (strncmp(extName, p, n) == 0)) {
286 return GL_TRUE;
287 }
288 p += (n + 1);
289 }
290 return GL_FALSE;
291}
292
293int test_attribs[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE,
294 16, WX_GL_STENCIL_SIZE, 8,
295 0};
296
297glTestCanvas::glTestCanvas(wxWindow *parent)
298 : wxGLCanvas(parent, wxID_ANY, test_attribs, wxDefaultPosition,
299 wxSize(2, 2)) {}
300
301// This attribute set works OK with vesa software only OpenGL renderer
302int attribs[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE,
303 16, WX_GL_STENCIL_SIZE, 8,
304 0};
305BEGIN_EVENT_TABLE(glChartCanvas, wxGLCanvas)
306EVT_PAINT(glChartCanvas::OnPaint)
307EVT_ACTIVATE(glChartCanvas::OnActivate)
308EVT_SIZE(glChartCanvas::OnSize)
309EVT_MOUSE_EVENTS(glChartCanvas::MouseEvent)
310END_EVENT_TABLE()
311
312glChartCanvas::glChartCanvas(wxWindow *parent, wxGLCanvas *share)
313 : wxGLCanvas(parent, wxID_ANY, attribs, wxDefaultPosition, wxSize(256, 256),
314 wxFULL_REPAINT_ON_RESIZE | wxBG_STYLE_CUSTOM, "")
315
316{
317 m_pParentCanvas = dynamic_cast<ChartCanvas *>(parent);
318
319 Init();
320}
321
322std::unordered_map<wxPenStyle, std::array<wxDash, 2>> glChartCanvas::dash_map =
323 {
324 {wxPENSTYLE_DOT, {1, 1}},
325 {wxPENSTYLE_LONG_DASH, {5, 5}},
326 {wxPENSTYLE_SHORT_DASH, {1, 5}},
327 {wxPENSTYLE_DOT_DASH, {5, 1}},
328};
329
330void glChartCanvas::Init() {
331 m_bsetup = false;
332
333 // m_pParentCanvas = dynamic_cast<ChartCanvas *>( GetParent() );
334
335 SetBackgroundStyle(wxBG_STYLE_CUSTOM); // on WXMSW, this prevents flashing
336
337 m_cache_current_ch = NULL;
338
339 m_b_paint_enable = true;
340 m_in_glpaint = false;
341
342 m_cache_tex[0] = m_cache_tex[1] = 0;
343 m_cache_page = 0;
344
345 m_b_BuiltFBO = false;
346 m_b_DisableFBO = false;
347
348 ownship_tex = 0;
349 ownship_color = -1;
350
351 m_piano_tex = 0;
352
353 m_binPinch = false;
354 m_binPan = false;
355 m_bpinchGuard = false;
356 m_binGesture = false;
357 m_first_zout = false;
358 g_true_zoom = true;
359
360 b_timeGL = true;
361 m_last_render_time = -1;
362
363 m_LRUtime = 0;
364
365 m_tideTex = 0;
366 m_currentTex = 0;
367
368 m_gldc.SetGLCanvas(this);
369 m_gldc.SetDPIFactor(g_BasePlatform->GetDisplayDIPMult(GetParent()));
370
371 m_displayScale = 1.0;
372#if defined(__WXOSX__) || defined(__WXGTK3__)
373 // Support scaled HDPI displays.
374 m_displayScale = GetContentScaleFactor();
375#endif
376 m_pParentCanvas->VPoint.SetPixelScale(m_displayScale);
377
378#ifdef __ANDROID__
379 // Create/connect a dynamic event handler slot for gesture and some timer
380 // events
381 Connect(
382 wxEVT_QT_PANGESTURE,
383 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::OnEvtPanGesture,
384 NULL, this);
385
386 Connect(
387 wxEVT_QT_PINCHGESTURE,
388 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::OnEvtPinchGesture,
389 NULL, this);
390
391 Connect(GESTURE_EVENT_TIMER, wxEVT_TIMER,
392 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::
393 onGestureTimerEvent,
394 NULL, this);
395
396 Connect(GESTURE_FINISH_TIMER, wxEVT_TIMER,
397 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::
398 onGestureFinishTimerEvent,
399 NULL, this);
400
401 Connect(
402 ZOOM_TIMER, wxEVT_TIMER,
403 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::onZoomTimerEvent,
404 NULL, this);
405
406 m_gestureEeventTimer.SetOwner(this, GESTURE_EVENT_TIMER);
407 m_gestureFinishTimer.SetOwner(this, GESTURE_FINISH_TIMER);
408 zoomTimer.SetOwner(this, ZOOM_TIMER);
409
410#ifdef USE_ANDROID_GLES2
411// Connect(
412// TEX_FADE_TIMER, wxEVT_TIMER,
413// (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::onFadeTimerEvent,
414// NULL, this);
415// m_fadeTimer.SetOwner(this, TEX_FADE_TIMER);
416#endif
417
418#else
419#ifdef HAVE_WX_GESTURE_EVENTS
420
421 Connect(GESTURE_EVENT_TIMER, wxEVT_TIMER,
422 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::
423 onGestureTimerEvent,
424 NULL, this);
425
426 Connect(GESTURE_FINISH_TIMER, wxEVT_TIMER,
427 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::
428 onGestureFinishTimerEvent,
429 NULL, this);
430
431 Connect(
432 ZOOM_TIMER, wxEVT_TIMER,
433 (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::onZoomTimerEvent,
434 NULL, this);
435
436 m_gestureEeventTimer.SetOwner(this, GESTURE_EVENT_TIMER);
437 m_gestureFinishTimer.SetOwner(this, GESTURE_FINISH_TIMER);
438 zoomTimer.SetOwner(this, ZOOM_TIMER);
439 m_zoom_inc = 1.0;
440#endif
441#endif
442
443 m_bgestureGuard = false;
444 m_total_zoom_val = 1.0;
445 m_step_zoom_val = 1.0;
446
447// Gesture support for platforms other than Android
448#ifdef HAVE_WX_GESTURE_EVENTS
449 if (!EnableTouchEvents(wxTOUCH_ZOOM_GESTURE | wxTOUCH_PRESS_GESTURES)) {
450 wxLogError("Failed to enable touch events");
451 }
452
453 // Bind(wxEVT_GESTURE_PAN, &glChartCanvas::OnEvtPanGesture, this);
454 // Connect(
455 // wxEVT_GESTURE_PAN,
456 // (wxObjectEventFunction)(wxEventFunction)&glChartCanvas::OnEvtPanGesture,
457 // NULL, this);
458
459 Bind(wxEVT_GESTURE_ZOOM, &glChartCanvas::OnEvtZoomGesture, this);
460
461 Bind(wxEVT_LONG_PRESS, &ChartCanvas::OnLongPress, m_pParentCanvas);
462 Bind(wxEVT_PRESS_AND_TAP, &ChartCanvas::OnPressAndTap, m_pParentCanvas);
463
464 Bind(wxEVT_RIGHT_UP, &ChartCanvas::OnRightUp, m_pParentCanvas);
465 Bind(wxEVT_RIGHT_DOWN, &ChartCanvas::OnRightDown, m_pParentCanvas);
466
467 Bind(wxEVT_LEFT_UP, &ChartCanvas::OnLeftUp, m_pParentCanvas);
468 Bind(wxEVT_LEFT_DOWN, &ChartCanvas::OnLeftDown, m_pParentCanvas);
469
470 Bind(wxEVT_MOUSEWHEEL, &ChartCanvas::OnWheel, m_pParentCanvas);
471 Bind(wxEVT_MOTION, &ChartCanvas::OnMotion, m_pParentCanvas);
472#endif /* HAVE_WX_GESTURE_EVENTS */
473
474 if (!g_glTextureManager) g_glTextureManager = new glTextureManager;
475}
476
477glChartCanvas::~glChartCanvas() {
478#ifdef __ANDROID__
479 unloadShaders();
480#endif
481}
482
483int glChartCanvas::GetCanvasIndex() { return m_pParentCanvas->m_canvasIndex; }
484
485void glChartCanvas::FlushFBO() {
486 if (m_bsetup) BuildFBO();
487}
488
489void glChartCanvas::OnActivate(wxActivateEvent &event) {
490 m_pParentCanvas->OnActivate(event);
491}
492
493void glChartCanvas::OnSize(wxSizeEvent &event) {
494 // Set the shader viewport transform matrix
495 // Always safe, simple math based on parent VP
496 ViewPort *vp = m_pParentCanvas->GetpVP();
497 vp->SetVPTransformMatrix();
498
499#ifndef __ANDROID__
500 if (!m_bsetup) return;
501#endif
502 if (!IsShown()) return;
503
504 SetCurrent(*m_pcontext);
505
506 if (!g_bopengl) {
507 // Invoked immediately after user has disabled OpenGL.
508 SetSize(GetSize().x, GetSize().y);
509 event.Skip();
510 return;
511 }
512
513 // this is also necessary to update the context on some platforms
514 // OnSize can be called with a different OpenGL context (when a plugin uses a
515 // different GL context).
516 if (m_pcontext && IsShown()) {
517 SetCurrent(*m_pcontext);
518 }
519
520 wxLogDebug("BuildFBO 3");
521 BuildFBO();
522 event.Skip();
523}
524
525void glChartCanvas::MouseEvent(wxMouseEvent &event) {
526 if (m_pParentCanvas->MouseEventOverlayWindows(event)) return;
527
528#ifndef __ANDROID__
529 if (m_pParentCanvas->MouseEventSetup(event))
530 return; // handled, no further action required
531
532 bool obj_proc = m_pParentCanvas->MouseEventProcessObjects(event);
533
534 if (!obj_proc && !m_pParentCanvas->singleClickEventIsValid)
535 m_pParentCanvas->MouseEventProcessCanvas(event);
536
537 if (!g_btouch) m_pParentCanvas->SetCanvasCursor(event);
538
539#else
540
541 if (m_bgestureGuard) {
542 m_pParentCanvas->r_rband.x = 0; // turn off rubberband temporarily
543
544 // Sometimes we get a Gesture Pan start on a simple tap operation.
545 // When this happens, we usually get no Gesture Finished event.
546 // So, we need to process the next LeftUp event normally, to handle things
547 // like Measure and Route Create.
548
549 // Allow LeftUp() event through if the pan action is very small
550 // Otherwise, drop the LeftUp() event, since it is not wanted for a Pan
551 // Gesture.
552 if (event.LeftUp()) {
553 // qDebug() << panx << pany;
554 if ((abs(panx) > 2) || (abs(pany) > 2)) {
555 return;
556 } else { // Cancel the in=process Gesture state
557 m_gestureEeventTimer.Start(10, wxTIMER_ONE_SHOT); // Short Circuit
558 }
559 } else
560 return;
561 }
562
563 if (m_pParentCanvas->MouseEventSetup(event, false)) {
564 if (!event.LeftDClick()) {
565 return; // handled, no further action required
566 }
567 }
568
569 if (m_binPan && event.RightDown()) {
570 qDebug() << "Skip right on pan";
571 return;
572 } else {
573 bool obj_proc = m_pParentCanvas->MouseEventProcessObjects(event);
574
575 if (!obj_proc && !m_pParentCanvas->singleClickEventIsValid) {
576 if (!m_bgestureGuard)
577 m_pParentCanvas->MouseEventProcessCanvas(
578 event); // This is where a physical mouse gets processed, if
579 // detected
580 }
581 }
582
583#endif
584}
585
586#ifndef GL_MAX_RENDERBUFFER_SIZE
587#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
588#endif
589
590#ifndef USE_ANDROID_GLES2
591bool glChartCanvas::buildFBOSize(int fboSize) {
592 bool retVal = true;
593 if (IsShown()) SetCurrent(*m_pcontext);
594
595 if (m_b_BuiltFBO) {
596 glDeleteTextures(2, m_cache_tex);
597 glDeleteFramebuffers(1, &m_fb0);
598 glDeleteRenderbuffers(1, &m_renderbuffer);
599 m_b_BuiltFBO = false;
600 }
601
602 if (m_b_DisableFBO) return false;
603
604#ifdef __ANDROID__
605 // We use the smallest possible (POT) FBO
606 int rb_x = GetSize().x;
607 int rb_y = GetSize().y;
608 int i = 1;
609 while (i < rb_x) i <<= 1;
610 rb_x = i;
611
612 i = 1;
613 while (i < rb_y) i <<= 1;
614 rb_y = i;
615
616 m_cache_tex_x = wxMax(rb_x, rb_y);
617 m_cache_tex_y = wxMax(rb_x, rb_y);
618
619#else
620 m_cache_tex_x = GetSize().x * m_displayScale;
621 m_cache_tex_y = GetSize().y * m_displayScale;
622#endif
623
624 int err = GL_NO_ERROR;
625 GLint params;
626 glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &params);
627
628 err = glGetError();
629 if (err == GL_INVALID_ENUM) {
630 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &params);
631 err = glGetError();
632 }
633
634 if (err == GL_NO_ERROR) {
635 if (fboSize > params) {
636 wxLogMessage(
637 " OpenGL-> Requested Framebuffer size exceeds "
638 "GL_MAX_RENDERBUFFER_SIZE");
639 return false;
640 }
641 }
642
643 glGenFramebuffers(1, &m_fb0);
644 err = glGetError();
645 if (err) {
646 wxString msg;
647 msg.Printf(" OpenGL-> Framebuffer GenFramebuffers error: %08X", err);
648 wxLogMessage(msg);
649 retVal = false;
650 }
651
652 glGenRenderbuffers(1, &m_renderbuffer);
653 err = glGetError();
654 if (err) {
655 wxString msg;
656 msg.Printf(" OpenGL-> Framebuffer GenRenderbuffers error: %08X", err);
657 wxLogMessage(msg);
658 retVal = false;
659 }
660
661 glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fb0);
662 err = glGetError();
663 if (err) {
664 wxString msg;
665 msg.Printf(" OpenGL-> Framebuffer BindFramebuffers error: %08X", err);
666 wxLogMessage(msg);
667 retVal = false;
668 }
669
670 // initialize color textures
671 glGenTextures(2, m_cache_tex);
672 for (int i = 0; i < 2; i++) {
673 glBindTexture(g_texture_rectangle_format, m_cache_tex[i]);
674 glTexParameterf(g_texture_rectangle_format, GL_TEXTURE_MIN_FILTER,
675 GL_NEAREST);
676 glTexParameteri(g_texture_rectangle_format, GL_TEXTURE_MAG_FILTER,
677 GL_NEAREST);
678 glTexImage2D(g_texture_rectangle_format, 0, GL_RGBA, m_cache_tex_x,
679 m_cache_tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
680 }
681
682 glBindRenderbuffer(GL_RENDERBUFFER_EXT, m_renderbuffer);
683
684 if (m_b_useFBOStencil) {
685 // initialize composite depth/stencil renderbuffer
686 glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT,
687 m_cache_tex_x, m_cache_tex_y);
688
689 int err = glGetError();
690 if (err) {
691 wxString msg;
692 msg.Printf(" OpenGL-> glRenderbufferStorage error: %08X", err);
693 wxLogMessage(msg);
694 }
695
696 glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
697 GL_RENDERBUFFER_EXT, m_renderbuffer);
698 err = glGetError();
699 if (err) {
700 wxString msg;
701 msg.Printf(" OpenGL-> glFramebufferRenderbuffer depth error: %08X",
702 err);
703 wxLogMessage(msg);
704 }
705
706 glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
707 GL_RENDERBUFFER_EXT, m_renderbuffer);
708 err = glGetError();
709 if (err) {
710 wxString msg;
711 msg.Printf(" OpenGL-> glFramebufferRenderbuffer stencil error: %08X",
712 err);
713 wxLogMessage(msg);
714 }
715
716 } else {
717 GLenum depth_format = GL_DEPTH_COMPONENT24;
718
719 // Need to check for availability of 24 bit depth buffer extension on
720 // GLES
721#ifdef ocpnUSE_GLES
722 if (!QueryExtension("GL_OES_depth24")) depth_format = GL_DEPTH_COMPONENT16;
723#endif
724
725 // initialize depth renderbuffer
726 glRenderbufferStorage(GL_RENDERBUFFER_EXT, depth_format, m_cache_tex_x,
727 m_cache_tex_y);
728 int err = glGetError();
729 if (err) {
730 wxString msg;
731 msg.Printf(" OpenGL-> Framebuffer Depth Buffer Storage error: %08X",
732 err);
733 wxLogMessage(msg);
734 retVal = false;
735 }
736
737 glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
738 GL_RENDERBUFFER_EXT, m_renderbuffer);
739
740 err = glGetError();
741 if (err) {
742 wxString msg;
743 msg.Printf(" OpenGL-> Framebuffer Depth Buffer Attach error: %08X",
744 err);
745 wxLogMessage(msg);
746 retVal = false;
747 }
748 }
749
750 glBindTexture(GL_TEXTURE_2D, 0);
751 glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
752
753 // Check framebuffer completeness at the end of initialization.
754 glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fb0);
755
756 glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
757 g_texture_rectangle_format, m_cache_tex[0], 0);
758
759 GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
760
761 glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
762
763 if (fb_status != GL_FRAMEBUFFER_COMPLETE_EXT) {
764 wxString msg;
765 msg.Printf(" OpenGL-> buildFBOSize->Framebuffer Incomplete: %08X",
766 fb_status);
767 wxLogMessage(msg);
768 retVal = false;
769 }
770
771 return retVal;
772}
773#endif
774
775#ifdef USE_ANDROID_GLES2
776bool glChartCanvas::buildFBOSize(int fboSize) {
777 bool retVal = true;
778
779 // We use the smallest possible (POT) FBO
780 int rb_x = GetSize().x;
781 int rb_y = GetSize().y;
782 int i = 1;
783 while (i < rb_x) i <<= 1;
784 rb_x = i;
785
786 i = 1;
787 while (i < rb_y) i <<= 1;
788 rb_y = i;
789
790 m_cache_tex_x = wxMax(rb_x, rb_y);
791 m_cache_tex_y = wxMax(rb_x, rb_y);
792
793 // qDebug() << "FBO Size: " << GetSize().x << GetSize().y << m_cache_tex_x;
794
795 int err = GL_NO_ERROR;
796 GLint params;
797 glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &params);
798
799 err = glGetError();
800 if (err == GL_INVALID_ENUM) {
801 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &params);
802 err = glGetError();
803 }
804
805 if (err == GL_NO_ERROR) {
806 if (fboSize > params) {
807 wxLogMessage(
808 " OpenGL-> Requested Framebuffer size exceeds "
809 "GL_MAX_RENDERBUFFER_SIZE");
810 return false;
811 }
812 }
813
814 glGenFramebuffers(1, &m_fb0);
815 err = glGetError();
816 if (err) {
817 wxString msg;
818 msg.Printf(" OpenGL-> Framebuffer GenFramebuffers error: %08X", err);
819 wxLogMessage(msg);
820 retVal = false;
821 }
822
823 glGenRenderbuffers(1, &m_renderbuffer);
824 err = glGetError();
825 if (err) {
826 wxString msg;
827 msg.Printf(" OpenGL-> Framebuffer GenRenderbuffers error: %08X", err);
828 wxLogMessage(msg);
829 retVal = false;
830 }
831
832 glBindFramebuffer(GL_FRAMEBUFFER, m_fb0);
833 err = glGetError();
834 if (err) {
835 wxString msg;
836 msg.Printf(" OpenGL-> Framebuffer BindFramebuffers error: %08X", err);
837 wxLogMessage(msg);
838 retVal = false;
839 }
840
841 // initialize color textures
842 glGenTextures(2, m_cache_tex);
843 for (int i = 0; i < 2; i++) {
844 glBindTexture(g_texture_rectangle_format, m_cache_tex[i]);
845 glTexParameterf(g_texture_rectangle_format, GL_TEXTURE_MIN_FILTER,
846 GL_NEAREST);
847 glTexParameteri(g_texture_rectangle_format, GL_TEXTURE_MAG_FILTER,
848 GL_NEAREST);
849 glTexImage2D(g_texture_rectangle_format, 0, GL_RGBA, m_cache_tex_x,
850 m_cache_tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
851 }
852
853 glBindRenderbuffer(GL_RENDERBUFFER, m_renderbuffer);
854
855 // initialize composite depth/stencil renderbuffer
856 glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, m_cache_tex_x,
857 m_cache_tex_y);
858
859 err = glGetError();
860 if (err) {
861 wxString msg;
862 msg.Printf(" OpenGL-> glRenderbufferStorage error: %08X", err);
863 wxLogMessage(msg);
864 }
865
866 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
867 GL_RENDERBUFFER, m_renderbuffer);
868 err = glGetError();
869 if (err) {
870 wxString msg;
871 msg.Printf(" OpenGL-> glFramebufferRenderbuffer depth error: %08X",
872 err);
873 wxLogMessage(msg);
874 }
875
876 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
877 GL_RENDERBUFFER, m_renderbuffer);
878 err = glGetError();
879 if (err) {
880 wxString msg;
881 msg.Printf(" OpenGL-> glFramebufferRenderbuffer stencil error: %08X",
882 err);
883 wxLogMessage(msg);
884 }
885
886 glBindTexture(GL_TEXTURE_2D, 0);
887 glBindFramebuffer(GL_FRAMEBUFFER, 0);
888
889 // Check framebuffer completeness at the end of initialization.
890 glBindFramebuffer(GL_FRAMEBUFFER, m_fb0);
891
892 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
893 g_texture_rectangle_format, m_cache_tex[0], 0);
894
895 GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
896
897 glBindFramebuffer(GL_FRAMEBUFFER, 0);
898
899 if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
900 wxString msg;
901 msg.Printf(" OpenGL-> buildFBOSize->Framebuffer Incomplete: %08X %08X",
902 fb_status);
903 wxLogMessage(msg);
904 retVal = false;
905 }
906
907 return retVal;
908}
909#endif
910
911void glChartCanvas::BuildFBO() {
912 if (g_b_needFinish) glFinish();
913
914 if (m_b_BuiltFBO) {
915 // return;
916 glDeleteTextures(2, m_cache_tex);
917 glDeleteFramebuffers(1, &m_fb0);
918 glDeleteRenderbuffers(1, &m_renderbuffer);
919 m_b_BuiltFBO = false;
920 }
921
922 if (m_b_DisableFBO) return;
923
924 // int initialSize = 2048;
925 int gl_width, gl_height;
926 m_pParentCanvas->GetClientSize(&gl_width, &gl_height);
927 int initialSize = NextPow2(gl_width * m_displayScale);
928
929#ifdef __ANDROID__
930 // Some low mem-spec devices have trouble with 2048 FBO size.
931 // Detect here, and choose 1024 size instead
932 wxString info = androidGetDeviceInfo();
933
934 if (wxNOT_FOUND != info.Find("GT-S6312")) initialSize = 1024;
935#endif
936
937 if (!buildFBOSize(initialSize)) {
938 glDeleteTextures(2, m_cache_tex);
939 glDeleteFramebuffers(1, &m_fb0);
940 glDeleteRenderbuffers(1, &m_renderbuffer);
941
942 if (!buildFBOSize(1024)) {
943 wxLogMessage("BuildFBO C");
944
945 m_b_DisableFBO = true;
946 wxLogMessage("OpenGL-> FBO Framebuffer unavailable");
947 m_b_BuiltFBO = false;
948
949 return;
950 }
951 }
952
953 // All OK
954
955 wxString msg;
956 msg.Printf("OpenGL-> Framebuffer OK, size = %d", m_cache_tex_x);
957 wxLogDebug(msg);
958
959 /* invalidate cache */
960 Invalidate();
961
962 // glClear(GL_COLOR_BUFFER_BIT);
963 m_b_BuiltFBO = true;
964
965 return;
966}
967
968void glChartCanvas::SetupOpenGL() {
969 LoadS57();
970
971 if (IsShown()) SetCurrent(*m_pcontext);
972
973 char *str = (char *)glGetString(GL_RENDERER);
974 if (str == NULL) {
975 // perhaps we should edit the config and turn off opengl now
976 wxLogMessage("Failed to initialize OpenGL");
977 exit(1);
978 }
979
980 char render_string[80];
981 strncpy(render_string, str, 79);
982 m_renderer = wxString(render_string, wxConvUTF8);
983
984 wxString msg;
985 if (g_bSoftwareGL) msg.Printf("OpenGL-> Software OpenGL");
986 msg.Printf("OpenGL-> Renderer String: ");
987 msg += m_renderer;
988 wxLogMessage(msg);
989
990 if (ps52plib) ps52plib->SetGLRendererString(m_renderer);
991
992 char version_string[80];
993 strncpy(version_string, (char *)glGetString(GL_VERSION), 79);
994 msg.Printf("OpenGL-> Version reported: ");
995 m_version = wxString(version_string, wxConvUTF8);
996 msg += m_version;
997 wxLogMessage(msg);
998
999 char GLSL_version_string[80];
1000 strncpy(GLSL_version_string, (char *)glGetString(GL_SHADING_LANGUAGE_VERSION),
1001 79);
1002 msg.Printf("OpenGL-> GLSL Version reported: ");
1003 m_GLSLversion = wxString(GLSL_version_string, wxConvUTF8);
1004 msg += m_GLSLversion;
1005 wxLogMessage(msg);
1006
1007#ifndef __ANDROID__
1008#ifndef __WXOSX__
1009 GLenum err = glewInit();
1010#ifdef GLEW_ERROR_NO_GLX_DISPLAY
1011 if (GLEW_OK != err && GLEW_ERROR_NO_GLX_DISPLAY != err)
1012#else
1013 if (GLEW_OK != err)
1014#endif
1015 {
1016 printf("GLEW init failed: %s\n", glewGetErrorString(err));
1017 exit(1);
1018 } else {
1019 wxLogMessage("GLEW init success!n");
1020 }
1021#endif
1022#endif
1023
1024 const GLubyte *ext_str = glGetString(GL_EXTENSIONS);
1025 m_extensions = wxString((const char *)ext_str, wxConvUTF8);
1026
1027 // Set the minimum line width
1028 GLint parms[2];
1029#ifndef USE_ANDROID_GLES2
1030 glGetIntegerv(GL_SMOOTH_LINE_WIDTH_RANGE, &parms[0]);
1031#else
1032 glGetIntegerv(GL_ALIASED_LINE_WIDTH_RANGE, &parms[0]);
1033#endif
1034 g_GLMinSymbolLineWidth = wxMax(parms[0], 1);
1035 g_GLMinCartographicLineWidth = wxMax(parms[0], 1);
1036
1037 // Some GL renderers do a poor job of Anti-aliasing very narrow line
1038 // widths. This is most evident on rendered symbols which have horizontal
1039 // or vertical line segments Detect this case, and adjust the render
1040 // parameters.
1041
1042 if (m_renderer.Upper().Find("MESA") != wxNOT_FOUND) {
1043 GLfloat parf;
1044 glGetFloatv(GL_SMOOTH_LINE_WIDTH_GRANULARITY, &parf);
1045
1046 g_GLMinSymbolLineWidth = wxMax(((float)parms[0] + parf), 1);
1047 }
1048
1049 s_b_useScissorTest = true;
1050 // the radeon x600 driver has buggy scissor test
1051 if (GetRendererString().Find("RADEON X600") != wxNOT_FOUND)
1052 s_b_useScissorTest = false;
1053
1054 if (GetRendererString().Find("GeForce") != wxNOT_FOUND) // GeForce GTX 1070
1055 s_b_useScissorTest = false;
1056
1057 bool bad_stencil_code = false;
1058
1059 // And for the lousy Unichrome drivers, too
1060 if (GetRendererString().Find("UniChrome") != wxNOT_FOUND)
1061 bad_stencil_code = true;
1062
1063 // And for the lousy Mali drivers, too
1064 if (GetRendererString().Find("Mali") != wxNOT_FOUND) bad_stencil_code = true;
1065
1066 // Stencil buffer test
1067 glEnable(GL_STENCIL_TEST);
1068 GLboolean stencil = glIsEnabled(GL_STENCIL_TEST);
1069 int sb;
1070 glGetIntegerv(GL_STENCIL_BITS, &sb);
1071 // printf("Stencil Buffer Available: %d\nStencil bits: %d\n", stencil,
1072 // sb);
1073 glDisable(GL_STENCIL_TEST);
1074
1075 s_b_useStencil = false;
1076 if (stencil && (sb == 8)) s_b_useStencil = true;
1077
1078 if (QueryExtension("GL_ARB_texture_non_power_of_two"))
1079 g_texture_rectangle_format = GL_TEXTURE_2D;
1080 else if (QueryExtension("GL_OES_texture_npot"))
1081 g_texture_rectangle_format = GL_TEXTURE_2D;
1082 else if (QueryExtension("GL_ARB_texture_rectangle"))
1083 g_texture_rectangle_format = GL_TEXTURE_RECTANGLE_ARB;
1084 wxLogMessage(wxString::Format("OpenGL-> Texture rectangle format: %x",
1085 g_texture_rectangle_format));
1086
1087#ifdef __ANDROID__
1088 g_texture_rectangle_format = GL_TEXTURE_2D;
1089#endif
1090
1091 // VBO??
1092 g_b_EnableVBO = true; // For linestrings
1093
1094 if (g_b_EnableVBO)
1095 wxLogMessage("OpenGL-> Using Vertexbuffer Objects");
1096 else
1097 wxLogMessage("OpenGL-> Vertexbuffer Objects unavailable");
1098
1099 // Inform S52PLIB of Renderer string, for any possible optimizations
1100 // Especially, for using VBO while AREA rendering.
1101 if (ps52plib) ps52plib->SetGLRendererString(GetRendererString());
1102
1103 // Can we use the stencil buffer in a FBO?
1104#ifdef ocpnUSE_GLES
1105 m_b_useFBOStencil = QueryExtension("GL_OES_packed_depth_stencil");
1106#else
1107 m_b_useFBOStencil = QueryExtension("GL_EXT_packed_depth_stencil") == GL_TRUE;
1108#endif
1109
1110#ifndef USE_ANDROID_GLES2
1111 // On Intel Graphics platforms, don't use stencil buffer at all
1112 if (bad_stencil_code) s_b_useStencil = false;
1113#endif
1114
1115 g_GLOptions.m_bUseCanvasPanning = false;
1116
1117 // TODO
1118 // Temporarily disable FBO on Windows, pending implementation of MSAA to
1119 // buffers
1120#ifdef __WXMSW__
1121 // m_b_DisableFBO = true;
1122#endif
1123
1124 // Accelerated pan is not used for MacOS Retina display
1125 // So there is no advantage to using FBO
1126 if (m_displayScale > 1) m_b_DisableFBO = true;
1127
1128 // Maybe build FBO(s)
1129 BuildFBO();
1130
1131#ifndef __ANDROID__
1132
1133 if (m_b_BuiltFBO) {
1134 // Check framebuffer completeness at the end of initialization.
1135 glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fb0);
1136
1137 glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
1138 g_texture_rectangle_format, m_cache_tex[0], 0);
1139
1140 GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
1141 glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
1142
1143 if (fb_status != GL_FRAMEBUFFER_COMPLETE_EXT) {
1144 wxString msg;
1145 msg.Printf(" OpenGL-> Framebuffer Incomplete: %08X", fb_status);
1146 wxLogMessage(msg);
1147 m_b_DisableFBO = true;
1148 BuildFBO();
1149 }
1150 }
1151#endif
1152
1153 if (m_b_BuiltFBO && !m_b_useFBOStencil) s_b_useStencil = false;
1154
1155 // If stencil seems to be a problem, force use of depth buffer clipping for
1156 // Area Patterns
1157 s_b_useStencilAP = s_b_useStencil & !bad_stencil_code;
1158
1159#ifdef USE_ANDROID_GLES2
1160 s_b_useStencilAP = s_b_useStencil; // required for GLES2 platform
1161#endif
1162
1163 // Check and determine if GLSL is to be used
1164 m_bUseGLSL = true;
1165
1166 if (m_b_BuiltFBO) {
1167 wxLogMessage("OpenGL-> Using Framebuffer Objects");
1168
1169 if (m_b_useFBOStencil)
1170 wxLogMessage("OpenGL-> Using FBO Stencil buffer");
1171 else
1172 wxLogMessage("OpenGL-> FBO Stencil buffer unavailable");
1173 } else
1174 wxLogMessage("OpenGL-> Framebuffer Objects unavailable");
1175
1176 if (s_b_useStencil)
1177 wxLogMessage("OpenGL-> Using Stencil buffer clipping");
1178 else
1179 wxLogMessage("OpenGL-> Using Depth buffer clipping");
1180
1181 if (s_b_useScissorTest && s_b_useStencil)
1182 wxLogMessage("OpenGL-> Using Scissor Clipping");
1183
1184 /* we upload non-aligned memory */
1185 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1186
1187 MipMap_ResolveRoutines();
1188 SetupCompression();
1189
1190 wxString lwmsg;
1191 lwmsg.Printf("OpenGL-> Minimum cartographic line width: %4.1f",
1192 g_GLMinCartographicLineWidth);
1193 wxLogMessage(lwmsg);
1194 lwmsg.Printf("OpenGL-> Minimum symbol line width: %4.1f",
1195 g_GLMinSymbolLineWidth);
1196 wxLogMessage(lwmsg);
1197
1198 if (!g_bGLexpert)
1199 g_GLOptions.m_bUseAcceleratedPanning = !m_b_DisableFBO && m_b_BuiltFBO;
1200
1201#ifdef USE_ANDROID_GLES2
1202 g_GLOptions.m_bUseAcceleratedPanning = true;
1203#endif
1204
1205 if (1) // for now upload all levels
1206 {
1207 int max_level = 0;
1208 int tex_dim = g_GLOptions.m_iTextureDimension;
1209 for (int dim = tex_dim; dim > 0; dim /= 2) max_level++;
1210 g_mipmap_max_level = max_level - 1;
1211 }
1212
1213 // Android, even though using GLES, does not require all levels.
1214#ifdef __ANDROID__
1216#endif
1217
1218 s_b_useFBO = m_b_BuiltFBO;
1219
1220 // Inform the S52 PLIB of options determined
1221 if (ps52plib)
1222 ps52plib->SetGLOptions(
1223 s_b_useStencil, s_b_useStencilAP, s_b_useScissorTest, s_b_useFBO,
1224 g_b_EnableVBO, g_texture_rectangle_format, g_GLMinCartographicLineWidth,
1225 g_GLMinSymbolLineWidth);
1226
1227 m_bsetup = true;
1228
1229 SendJSONConfigMessage();
1230}
1231
1232void glChartCanvas::SendJSONConfigMessage() {
1233 if (g_pi_manager) {
1234 nlohmann::json v;
1235 v["setupComplete"] = m_bsetup;
1236 v["useStencil"] = s_b_useStencil;
1237 v["useStencilAP"] = s_b_useStencilAP;
1238 v["useScissorTest"] = s_b_useScissorTest;
1239 v["useFBO"] = s_b_useFBO;
1240 v["useVBO"] = g_b_EnableVBO;
1241 v["TextureRectangleFormat"] = g_texture_rectangle_format;
1242 SendJsonMessageToAllPlugins("OCPN_OPENGL_CONFIG", v);
1243 }
1244}
1245void glChartCanvas::SetupCompression() {
1246 int dim = g_GLOptions.m_iTextureDimension;
1247
1248#ifdef __WXMSW__
1249 if (!::IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE)) {
1250 wxLogMessage("OpenGL-> SSE2 Instruction set not available");
1251 goto no_compression;
1252 }
1253#endif
1254
1255 g_uncompressed_tile_size = dim * dim * 4; // stored as 32bpp in vram
1256 if (!g_GLOptions.m_bTextureCompression) goto no_compression;
1257
1258 g_raster_format = GL_RGB;
1259
1260 // On GLES, we prefer OES_ETC1 compression, if available
1261#ifdef ocpnUSE_GLES
1262 if (QueryExtension("GL_OES_compressed_ETC1_RGB8_texture")) {
1263 g_raster_format = GL_ETC1_RGB8_OES;
1264
1265 wxLogMessage("OpenGL-> Using oes etc1 compression");
1266 }
1267#endif
1268
1269 if (GL_RGB == g_raster_format) {
1270 /* because s3tc is patented, many foss drivers disable
1271 support by default, however the extension dxt1 allows
1272 us to load this texture type which is enough because we
1273 compress in software using libsquish for superior quality anyway */
1274
1275 if ((QueryExtension("GL_EXT_texture_compression_s3tc") ||
1276 QueryExtension("GL_EXT_texture_compression_dxt1"))) {
1277 /* buggy opensource nvidia driver, renders incorrectly,
1278 workaround is to use format with alpha... */
1279 if (GetRendererString().Find("Gallium") != wxNOT_FOUND &&
1280 GetRendererString().Find("NV") != wxNOT_FOUND)
1281 g_raster_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1282 else
1283 g_raster_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
1284
1285 wxLogMessage("OpenGL-> Using s3tc dxt1 compression");
1286 } else if (QueryExtension("GL_3DFX_texture_compression_FXT1")) {
1287 g_raster_format = GL_COMPRESSED_RGB_FXT1_3DFX;
1288
1289 wxLogMessage("OpenGL-> Using 3dfx fxt1 compression");
1290 } else {
1291 wxLogMessage("OpenGL-> No Useable compression format found");
1292 goto no_compression;
1293 }
1294 }
1295
1296#ifdef ocpnUSE_GLES /* gles doesn't have GetTexLevelParameter */
1297 g_tile_size = 512 * 512 / 2; /* 4bpp */
1298#else
1299 /* determine compressed size of a level 0 single tile */
1300 GLuint texture;
1301 glGenTextures(1, &texture);
1302 glBindTexture(GL_TEXTURE_2D, texture);
1303 glTexImage2D(GL_TEXTURE_2D, 0, g_raster_format, dim, dim, 0, GL_RGB,
1304 GL_UNSIGNED_BYTE, NULL);
1305 glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED_IMAGE_SIZE,
1306 &g_tile_size);
1307 glDeleteTextures(1, &texture);
1308#endif
1309
1310 /* disable texture compression if the tile size is 0 */
1311 if (g_tile_size == 0) goto no_compression;
1312
1313 wxLogMessage(wxString::Format("OpenGL-> Compressed tile size: %dkb (%d:1)",
1314 g_tile_size / 1024,
1315 g_uncompressed_tile_size / g_tile_size));
1316 return;
1317
1318no_compression:
1319 g_GLOptions.m_bTextureCompression = false;
1320
1321 g_tile_size = g_uncompressed_tile_size;
1322 wxLogMessage(wxString::Format("OpenGL-> Not Using compression"));
1323}
1324
1325void glChartCanvas::OnPaint(wxPaintEvent &event) {
1326 wxPaintDC dc(this);
1327 if (!m_pcontext) return;
1328 if (ChartData->IsBusy()) return;
1329
1330 Show(g_bopengl);
1331 if (!g_bopengl) {
1332 event.Skip();
1333 return;
1334 }
1335
1336 if (IsShown()) SetCurrent(*m_pcontext);
1337
1338 if (!m_bsetup) {
1339 SetupOpenGL();
1340
1341 if (ps52plib) ps52plib->FlushSymbolCaches(ChartCtxFactory());
1342
1343 m_bsetup = true;
1344 // g_bDebugOGL = true;
1345 }
1346
1347 // Paint updates may have been externally disabled (temporarily, to avoid
1348 // Yield() recursion performance loss)
1349 if (!m_b_paint_enable) return;
1350 // Recursion test, sometimes seen on GTK systems when wxBusyCursor is
1351 // activated
1352 if (m_in_glpaint) return;
1353
1354 // If necessary, reconfigure the S52 PLIB
1355 m_pParentCanvas->UpdateCanvasS52PLIBConfig();
1356
1357 // if( m_pParentCanvas->VPoint.b_quilt ){ // quilted
1358 // if( !m_pParentCanvas->m_pQuilt ||
1359 // !m_pParentCanvas->m_pQuilt->IsComposed() )
1360 // return; // not ready
1361 //
1362 // if(m_pParentCanvas->m_pQuilt->IsQuiltVector()){
1363 // if(ps52plib->GetStateHash() !=
1364 // m_pParentCanvas->m_s52StateHash){
1365 // m_pParentCanvas->UpdateS52State();
1366 // m_pParentCanvas->m_s52StateHash =
1367 // ps52plib->GetStateHash();
1368 // }
1369 // }
1370 // }
1371
1372 m_in_glpaint++;
1373 Render();
1374 m_in_glpaint--;
1375}
1376
1377// These routines allow reusable coordinates
1378bool glChartCanvas::HasNormalizedViewPort(const ViewPort &vp) {
1379 return false;
1380#ifndef USE_ANDROID_GLES2
1381 return vp.m_projection_type == PROJECTION_MERCATOR ||
1382 vp.m_projection_type == PROJECTION_POLAR ||
1383 vp.m_projection_type == PROJECTION_EQUIRECTANGULAR;
1384#else
1385 return false;
1386#endif
1387}
1388
1389/* adjust the opengl transformation matrix so that
1390 points plotted using the identity viewport are correct.
1391 and all rotation translation and scaling is now done in opengl
1392
1393 a central lat and lon of 0, 0 can be used, however objects on the far side of
1394 the world can be up to 3 meters off because limited floating point precision,
1395 and if the points cross 180 longitude then two passes will be required to
1396 render them correctly */
1397#define NORM_FACTOR 4096.0
1398void glChartCanvas::MultMatrixViewPort(ViewPort &vp, float lat, float lon) {
1399#ifndef USE_ANDROID_GLES2
1400
1401 wxPoint2DDouble point;
1402
1403 switch (vp.m_projection_type) {
1404 case PROJECTION_MERCATOR:
1405 case PROJECTION_EQUIRECTANGULAR:
1406 case PROJECTION_WEB_MERCATOR:
1407 // m_pParentCanvas->GetDoubleCanvasPointPixVP(vp, lat, lon, &point);
1408 point = vp.GetDoublePixFromLL(lat, lon);
1409 glTranslated(point.m_x, point.m_y, 0);
1410 glScaled(vp.view_scale_ppm / NORM_FACTOR, vp.view_scale_ppm / NORM_FACTOR,
1411 1);
1412 break;
1413
1414 case PROJECTION_POLAR:
1415 // m_pParentCanvas->GetDoubleCanvasPointPixVP(vp, vp.clat > 0 ? 90 : -90,
1416 // vp.clon, &point);
1417 point = vp.GetDoublePixFromLL(vp.clat > 0 ? 90 : -90, vp.clon);
1418 glTranslated(point.m_x, point.m_y, 0);
1419 glRotatef(vp.clon - lon, 0, 0, vp.clat);
1420 glScalef(vp.view_scale_ppm / NORM_FACTOR, vp.view_scale_ppm / NORM_FACTOR,
1421 1);
1422 glTranslatef(-vp.pix_width / 2, -vp.pix_height / 2, 0);
1423 break;
1424
1425 default:
1426 printf("ERROR: Unhandled projection\n");
1427 }
1428
1429 double rotation = vp.rotation;
1430
1431 if (rotation) glRotatef(rotation * 180 / PI, 0, 0, 1);
1432#endif
1433}
1434
1435ViewPort glChartCanvas::NormalizedViewPort(const ViewPort &vp, float lat,
1436 float lon) {
1437 ViewPort cvp = vp;
1438
1439 switch (vp.m_projection_type) {
1440 case PROJECTION_MERCATOR:
1441 case PROJECTION_EQUIRECTANGULAR:
1442 case PROJECTION_WEB_MERCATOR:
1443 cvp.clat = lat;
1444 break;
1445
1446 case PROJECTION_POLAR:
1447 cvp.clat = vp.clat > 0 ? 90 : -90; // either north or south polar
1448 break;
1449
1450 default:
1451 printf("ERROR: Unhandled projection\n");
1452 }
1453
1454 cvp.clon = lon;
1455 cvp.view_scale_ppm = NORM_FACTOR;
1456 cvp.rotation = cvp.skew = 0;
1457 return cvp;
1458}
1459
1460bool glChartCanvas::CanClipViewport(const ViewPort &vp) {
1461 return vp.m_projection_type == PROJECTION_MERCATOR ||
1462 vp.m_projection_type == PROJECTION_WEB_MERCATOR ||
1463 vp.m_projection_type == PROJECTION_EQUIRECTANGULAR;
1464}
1465
1466ViewPort glChartCanvas::ClippedViewport(const ViewPort &vp,
1467 const LLRegion &region) {
1468 if (!CanClipViewport(vp)) return vp;
1469
1470 ViewPort cvp = vp;
1471 LLBBox bbox = region.GetBox();
1472
1473 if (!bbox.GetValid()) return vp;
1474
1475 /* region.GetBox() will always try to give coordinates from -180 to 180 but in
1476 the case where the viewport crosses the IDL, we actually want the clipped
1477 viewport to use coordinates outside this range to ensure the logic in the
1478 various rendering routines works the same here (with accelerated panning)
1479 as it does without, so we can adjust the coordinates here */
1480
1481 if (bbox.GetMaxLon() < cvp.GetBBox().GetMinLon()) {
1482 bbox.Set(bbox.GetMinLat(), bbox.GetMinLon() + 360, bbox.GetMaxLat(),
1483 bbox.GetMaxLon() + 360);
1484 cvp.SetBBoxDirect(bbox);
1485 } else if (bbox.GetMinLon() > cvp.GetBBox().GetMaxLon()) {
1486 bbox.Set(bbox.GetMinLat(), bbox.GetMinLon() - 360, bbox.GetMaxLat(),
1487 bbox.GetMaxLon() - 360);
1488 cvp.SetBBoxDirect(bbox);
1489 } else
1490 cvp.SetBBoxDirect(bbox);
1491
1492 return cvp;
1493}
1494
1495void glChartCanvas::DrawStaticRoutesTracksAndWaypoints(ViewPort &vp) {
1496 if (!m_pParentCanvas->m_bShowNavobjects) return;
1497 ocpnDC dc(*this);
1498
1499 for (Track *pTrackDraw : g_TrackList) {
1500 /* defer rendering active tracks until later */
1501 ActiveTrack *pActiveTrack = dynamic_cast<ActiveTrack *>(pTrackDraw);
1502 if (pActiveTrack && pActiveTrack->IsRunning()) continue;
1503
1504 TrackGui(*pTrackDraw).Draw(m_pParentCanvas, dc, vp, vp.GetBBox());
1505 }
1506
1507 for (Route *pRouteDraw : *pRouteList) {
1508 if (!pRouteDraw) continue;
1509
1510 /* defer rendering active routes until later */
1511 if (pRouteDraw->IsActive() || pRouteDraw->IsSelected()) continue;
1512
1513 /* defer rendering routes being edited until later */
1514 if (pRouteDraw->m_bIsBeingEdited) continue;
1515
1516 RouteGui(*pRouteDraw).DrawGL(vp, m_pParentCanvas, dc);
1517 // pRouteDraw->DrawGL(vp, m_pParentCanvas, dc);
1518 }
1519
1520 /* Waypoints not drawn as part of routes, and not being edited */
1521 if (vp.GetBBox().GetValid() && pWayPointMan) {
1522 for (RoutePoint *pWP : *pWayPointMan->GetWaypointList()) {
1523 if (pWP && (!pWP->m_bRPIsBeingEdited) && (!pWP->m_bIsInRoute))
1524 if (vp.GetBBox().ContainsMarge(pWP->m_lat, pWP->m_lon, .5))
1525 RoutePointGui(*pWP).DrawGL(vp, m_pParentCanvas, dc);
1526 }
1527 }
1528}
1529
1530void glChartCanvas::DrawDynamicRoutesTracksAndWaypoints(ViewPort &vp) {
1531 ocpnDC dc(*this);
1532
1533 for (Track *pTrackDraw : g_TrackList) {
1534 ActiveTrack *pActiveTrack = dynamic_cast<ActiveTrack *>(pTrackDraw);
1535 if (pActiveTrack && pActiveTrack->IsRunning())
1536 TrackGui(*pTrackDraw).Draw(m_pParentCanvas, dc, vp, vp.GetBBox());
1537 // We need Track::Draw() to dynamically render last (ownship) point.
1538 }
1539
1540 for (Route *pRouteDraw : *pRouteList) {
1541 int drawit = 0;
1542 if (!pRouteDraw) continue;
1543
1544 /* Active routes */
1545 if (pRouteDraw->IsActive() || pRouteDraw->IsSelected()) drawit++;
1546
1547 /* Routes being edited */
1548 if (pRouteDraw->m_bIsBeingEdited) drawit++;
1549
1550 /* Routes Selected */
1551 if (pRouteDraw->IsSelected()) drawit++;
1552
1553 if (drawit) {
1554 const LLBBox &vp_box = vp.GetBBox(), &test_box = pRouteDraw->GetBBox();
1555 if (!vp_box.IntersectOut(test_box))
1556 RouteGui(*pRouteDraw).DrawGL(vp, m_pParentCanvas, dc);
1557 // pRouteDraw->DrawGL(vp, m_pParentCanvas, dc);
1558 }
1559 }
1560
1561 /* Waypoints not drawn as part of routes, which are being edited right now */
1562 if (vp.GetBBox().GetValid() && pWayPointMan) {
1563 for (RoutePoint *pWP : *pWayPointMan->GetWaypointList()) {
1564 if (pWP && pWP->m_bRPIsBeingEdited && !pWP->m_bIsInRoute)
1565 RoutePointGui(*pWP).DrawGL(vp, m_pParentCanvas, dc);
1566 // pWP->DrawGL(vp, m_pParentCanvas, dc);
1567 }
1568 }
1569}
1570
1571static void GetLatLonCurveDist(const ViewPort &vp, float &lat_dist,
1572 float &lon_dist) {
1573 // This really could use some more thought, and possibly split at different
1574 // intervals based on chart skew and other parameters to optimize performance
1575 switch (vp.m_projection_type) {
1576 case PROJECTION_TRANSVERSE_MERCATOR:
1577 lat_dist = 4, lon_dist = 1;
1578 break;
1579 case PROJECTION_POLYCONIC:
1580 lat_dist = 2, lon_dist = 1;
1581 break;
1582 case PROJECTION_ORTHOGRAPHIC:
1583 lat_dist = 2, lon_dist = 2;
1584 break;
1585 case PROJECTION_POLAR:
1586 lat_dist = 180, lon_dist = 1;
1587 break;
1588 case PROJECTION_STEREOGRAPHIC:
1589 case PROJECTION_GNOMONIC:
1590 lat_dist = 2, lon_dist = 1;
1591 break;
1592 case PROJECTION_EQUIRECTANGULAR:
1593 // this is suboptimal because we don't care unless there is
1594 // a change in both lat AND lon (skewed chart)
1595 lat_dist = 2, lon_dist = 360;
1596 break;
1597 default:
1598 lat_dist = 180, lon_dist = 360;
1599 }
1600}
1601
1602void glChartCanvas::RenderChartOutline(ocpnDC &dc, int dbIndex, ViewPort &vp) {
1603 if (ChartData->GetDBChartType(dbIndex) == CHART_TYPE_PLUGIN &&
1604 !ChartData->IsChartAvailable(dbIndex))
1605 return;
1606
1607 /* quick bounds check */
1608 LLBBox box;
1609 ChartData->GetDBBoundingBox(dbIndex, box);
1610 if (!box.GetValid()) return;
1611
1612 // Don't draw an outline in the case where the chart covers the entire world
1613 // */
1614 if (box.GetLonRange() == 360) return;
1615
1616 LLBBox vpbox = vp.GetBBox();
1617
1618 double lon_bias = 0;
1619 // chart is outside of viewport lat/lon bounding box
1620 if (box.IntersectOutGetBias(vp.GetBBox(), lon_bias)) return;
1621
1622 wxColour color;
1623 if (ChartData->GetDBChartType(dbIndex) == CHART_TYPE_CM93)
1624 color = GetGlobalColor("YELO1");
1625 else if (ChartData->GetDBChartFamily(dbIndex) == CHART_FAMILY_VECTOR)
1626 color = GetGlobalColor("GREEN2");
1627 else
1628 color = GetGlobalColor("UINFR");
1629
1630#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
1631 float plylat, plylon;
1632
1633 if (g_GLOptions.m_GLLineSmoothing) glEnable(GL_LINE_SMOOTH);
1634
1635 glColor3ub(color.Red(), color.Green(), color.Blue());
1636 glLineWidth(g_GLMinSymbolLineWidth);
1637
1638 float lat_dist, lon_dist;
1639 GetLatLonCurveDist(vp, lat_dist, lon_dist);
1640
1641 // Are there any aux ply entries?
1642 int nAuxPlyEntries = ChartData->GetnAuxPlyEntries(dbIndex), nPly;
1643 int j = 0;
1644 do {
1645 if (nAuxPlyEntries)
1646 nPly = ChartData->GetDBAuxPlyPoint(dbIndex, 0, j, 0, 0);
1647 else
1648 nPly = ChartData->GetDBPlyPoint(dbIndex, 0, &plylat, &plylon);
1649
1650 bool begin = false, sml_valid = false;
1651 double sml[2];
1652 float lastplylat = 0.0;
1653 float lastplylon = 0.0;
1654 // modulo is undefined for zero (compiler can use a div operation)
1655 int modulo = (nPly == 0) ? 1 : nPly;
1656 for (int i = 0; i < nPly + 1; i++) {
1657 if (nAuxPlyEntries)
1658 ChartData->GetDBAuxPlyPoint(dbIndex, i % modulo, j, &plylat, &plylon);
1659 else
1660 ChartData->GetDBPlyPoint(dbIndex, i % modulo, &plylat, &plylon);
1661
1662 plylon += lon_bias;
1663
1664 if (lastplylon - plylon > 180)
1665 lastplylon -= 360;
1666 else if (lastplylon - plylon < -180)
1667 lastplylon += 360;
1668
1669 int splits;
1670 if (i == 0)
1671 splits = 1;
1672 else {
1673 int lat_splits = floor(fabs(plylat - lastplylat) / lat_dist);
1674 int lon_splits = floor(fabs(plylon - lastplylon) / lon_dist);
1675 splits = wxMax(lat_splits, lon_splits) + 1;
1676 }
1677
1678 double smj[2];
1679 if (splits != 1) {
1680 // must perform border interpolation in mercator space as this is what
1681 // the charts use
1682 toSM(plylat, plylon, 0, 0, smj + 0, smj + 1);
1683 if (!sml_valid) toSM(lastplylat, lastplylon, 0, 0, sml + 0, sml + 1);
1684 }
1685
1686 for (double c = 0; c < splits; c++) {
1687 double lat, lon;
1688 if (c == splits - 1)
1689 lat = plylat, lon = plylon;
1690 else {
1691 double d = (double)(c + 1) / splits;
1692 fromSM(d * smj[0] + (1 - d) * sml[0], d * smj[1] + (1 - d) * sml[1],
1693 0, 0, &lat, &lon);
1694 }
1695
1696 wxPoint2DDouble s;
1697 m_pParentCanvas->GetDoubleCanvasPointPix(lat, lon, &s);
1698 if (!std::isnan(s.m_x)) {
1699 if (!begin) {
1700 begin = true;
1701 glBegin(GL_LINE_STRIP);
1702 }
1703 glVertex2f(s.m_x, s.m_y);
1704 } else if (begin) {
1705 glEnd();
1706 begin = false;
1707 }
1708 }
1709 if ((sml_valid = splits != 1)) memcpy(sml, smj, sizeof smj);
1710 lastplylat = plylat, lastplylon = plylon;
1711 }
1712
1713 if (begin) glEnd();
1714
1715 } while (++j < nAuxPlyEntries); // There are no aux Ply Point entries
1716
1717 glDisable(GL_LINE_SMOOTH);
1718 // glDisable( GL_BLEND );
1719
1720#else
1721 double nominal_line_width_pix =
1722 wxMax(2.0, floor(m_pParentCanvas->GetPixPerMM() / 4));
1723
1724 if (ChartData->GetDBChartType(dbIndex) == CHART_TYPE_CM93)
1725 dc.SetPen(wxPen(GetGlobalColor("YELO1"), nominal_line_width_pix,
1726 wxPENSTYLE_SOLID));
1727
1728 else if (ChartData->GetDBChartFamily(dbIndex) == CHART_FAMILY_VECTOR)
1729 dc.SetPen(wxPen(GetGlobalColor("UINFG"), nominal_line_width_pix,
1730 wxPENSTYLE_SOLID));
1731
1732 else
1733 dc.SetPen(wxPen(GetGlobalColor("UINFR"), nominal_line_width_pix,
1734 wxPENSTYLE_SOLID));
1735
1736 float plylat1, plylon1;
1737 int pixx1, pixy1;
1738
1739 // Are there any aux ply entries?
1740 int nAuxPlyEntries = ChartData->GetnAuxPlyEntries(dbIndex);
1741 if (0 == nAuxPlyEntries) // There are no aux Ply Point entries
1742 {
1743 wxPoint r, r1;
1744 std::vector<int> points_vector;
1745
1746 std::vector<float> vec = ChartData->GetReducedPlyPoints(dbIndex);
1747 int nPly = vec.size() / 2;
1748
1749 if (nPly == 0) return;
1750
1751 for (int i = 0; i < nPly; i++) {
1752 plylon1 = vec[i * 2];
1753 plylat1 = vec[i * 2 + 1];
1754
1755 m_pParentCanvas->GetCanvasPointPix(plylat1, plylon1, &r1);
1756 pixx1 = r1.x;
1757 pixy1 = r1.y;
1758
1759 points_vector.push_back(pixx1);
1760 points_vector.push_back(pixy1);
1761 }
1762
1763 ChartData->GetDBPlyPoint(dbIndex, 0, &plylat1, &plylon1);
1764 plylon1 += lon_bias;
1765
1766 m_pParentCanvas->GetCanvasPointPix(vec[1], vec[0], &r1);
1767 pixx1 = r1.x;
1768 pixy1 = r1.y;
1769
1770 points_vector.push_back(pixx1);
1771 points_vector.push_back(pixy1);
1772
1773 if (points_vector.size()) {
1774 std::vector<int>::iterator it = points_vector.begin();
1775 dc.DrawLines(points_vector.size() / 2, (wxPoint *)&(*it), 0, 0, true);
1776 }
1777 }
1778
1779 else // Use Aux PlyPoints
1780 {
1781 wxPoint r, r1;
1782
1783 for (int j = 0; j < nAuxPlyEntries; j++) {
1784 std::vector<int> points_vector;
1785
1786 std::vector<float> vec = ChartData->GetReducedAuxPlyPoints(dbIndex, j);
1787 int nAuxPly = vec.size() / 2;
1788
1789 if (nAuxPly == 0) continue;
1790
1791 for (int i = 0; i < nAuxPly; i++) {
1792 plylon1 = vec[i * 2];
1793 plylat1 = vec[i * 2 + 1];
1794
1795 m_pParentCanvas->GetCanvasPointPix(plylat1, plylon1, &r1);
1796 pixx1 = r1.x;
1797 pixy1 = r1.y;
1798
1799 points_vector.push_back(pixx1);
1800 points_vector.push_back(pixy1);
1801 }
1802
1803 m_pParentCanvas->GetCanvasPointPix(vec[1], vec[0], &r1);
1804 pixx1 = r1.x;
1805 pixy1 = r1.y;
1806
1807 points_vector.push_back(pixx1);
1808 points_vector.push_back(pixy1);
1809
1810 if (points_vector.size()) {
1811 std::vector<int>::iterator it = points_vector.begin();
1812 dc.DrawLines(points_vector.size() / 2, (wxPoint *)&(*it), 0, 0, true);
1813 }
1814 }
1815 }
1816
1817#endif
1818}
1819
1820extern void CalcGridSpacing(float WindowDegrees, float &MajorSpacing,
1821 float &MinorSpacing);
1822extern wxString CalcGridText(float latlon, float spacing, bool bPostfix);
1823void glChartCanvas::GridDraw() {
1824 if (!m_pParentCanvas->m_bDisplayGrid) return;
1825
1826 ViewPort &vp = m_pParentCanvas->GetVP();
1827
1828 if (!vp.IsValid() || !vp.GetBBox().GetValid()) return;
1829
1830 // TODO: make minor grid work all the time
1831 bool minorgrid =
1832 fabs(vp.rotation) < 0.0001 && vp.m_projection_type == PROJECTION_MERCATOR;
1833
1834 double nlat, elon, slat, wlon;
1835 float lat, lon;
1836 float gridlatMajor, gridlatMinor, gridlonMajor, gridlonMinor;
1837 wxCoord w, h;
1838
1839 wxColour GridColor = GetGlobalColor("SNDG1");
1840
1841 if (!m_gridfont.IsBuilt()) {
1842 double dpi_factor = g_BasePlatform->GetDisplayDIPMult(this);
1843 wxFont *dFont = FontMgr::Get().GetFont(_("GridText"), 0);
1844 wxFont font = *dFont;
1845 // Keep point size unscaled here; TexFont::Build handles DPI and display
1846 // scale.
1847 int font_size = wxMax(10, dFont->GetPointSize());
1848 font.SetPointSize(font_size);
1849 font.SetWeight(wxFONTWEIGHT_NORMAL);
1850
1851 m_gridfont.SetContentScaleFactor(OCPN_GetDisplayContentScaleFactor());
1852 m_gridfont.Build(font, m_displayScale, dpi_factor);
1853 }
1854 m_gridfont.SetColor(GridColor);
1855
1856 w = vp.pix_width;
1857 h = vp.pix_height;
1858
1859 LLBBox llbbox = vp.GetBBox();
1860 nlat = llbbox.GetMaxLat();
1861 slat = llbbox.GetMinLat();
1862 elon = llbbox.GetMaxLon();
1863 wlon = llbbox.GetMinLon();
1864
1865 // calculate distance between latitude grid lines
1866 CalcGridSpacing(vp.view_scale_ppm, gridlatMajor, gridlatMinor);
1867 CalcGridSpacing(vp.view_scale_ppm, gridlonMajor, gridlonMinor);
1868
1869 // if it is known the grid has straight lines it's a bit faster
1870 bool straight_latitudes = vp.m_projection_type == PROJECTION_MERCATOR ||
1871 vp.m_projection_type == PROJECTION_WEB_MERCATOR ||
1872 vp.m_projection_type == PROJECTION_EQUIRECTANGULAR;
1873 bool straight_longitudes = vp.m_projection_type == PROJECTION_MERCATOR ||
1874 vp.m_projection_type == PROJECTION_WEB_MERCATOR ||
1875 vp.m_projection_type == PROJECTION_POLAR ||
1876 vp.m_projection_type == PROJECTION_EQUIRECTANGULAR;
1877
1878 double latmargin;
1879 if (straight_latitudes)
1880 latmargin = 0;
1881 else
1882 latmargin = gridlatMajor / 2; // don't draw on poles
1883
1884 slat = wxMax(slat, -90 + latmargin);
1885 nlat = wxMin(nlat, 90 - latmargin);
1886
1887 float startlat = ceil(slat / gridlatMajor) * gridlatMajor;
1888 float startlon = ceil(wlon / gridlonMajor) * gridlonMajor;
1889 float curved_step = wxMin(sqrt(5e-3 / vp.view_scale_ppm), 3);
1890
1891 ocpnDC gldc(*this);
1892 wxPen *pen = wxThePenList->FindOrCreatePen(GridColor, g_GLMinSymbolLineWidth,
1893 wxPENSTYLE_SOLID);
1894 gldc.SetPen(*pen);
1895
1896 // Draw Major latitude grid lines and text
1897
1898 // calculate position of first major latitude grid line
1899 float lon_step = elon - wlon;
1900 if (!straight_latitudes) lon_step /= ceil(lon_step / curved_step);
1901
1902 for (lat = startlat; lat < nlat; lat += gridlatMajor) {
1903 wxPoint r, s;
1904 s.x = INVALID_COORD;
1905 s.y = INVALID_COORD;
1906 for (lon = wlon; lon < elon + lon_step / 2; lon += lon_step) {
1907 m_pParentCanvas->GetCanvasPointPix(lat, lon, &r);
1908 if (s.x != INVALID_COORD && s.y != INVALID_COORD) {
1909 gldc.DrawLine(s.x, s.y, r.x, r.y, false);
1910 }
1911 s = r;
1912 }
1913 }
1914
1915 if (minorgrid) {
1916 // draw minor latitude grid lines
1917 for (lat = ceil(slat / gridlatMinor) * gridlatMinor; lat < nlat;
1918 lat += gridlatMinor) {
1919 wxPoint r;
1920 m_pParentCanvas->GetCanvasPointPix(lat, (elon + wlon) / 2, &r);
1921 gldc.DrawLine(0, r.y, 10, r.y, true);
1922 gldc.DrawLine(w - 10, r.y, w, r.y, false);
1923 }
1924 }
1925
1926 // draw major longitude grid lines
1927 float lat_step = nlat - slat;
1928 if (!straight_longitudes) lat_step /= ceil(lat_step / curved_step);
1929
1930 for (lon = startlon; lon < elon; lon += gridlonMajor) {
1931 wxPoint r, s;
1932 s.x = INVALID_COORD;
1933 s.y = INVALID_COORD;
1934 for (lat = slat; lat < nlat + lat_step / 2; lat += lat_step) {
1935 m_pParentCanvas->GetCanvasPointPix(lat, lon, &r);
1936 if (s.x != INVALID_COORD && s.y != INVALID_COORD) {
1937 gldc.DrawLine(s.x, s.y, r.x, r.y, false);
1938 }
1939 s = r;
1940 }
1941 }
1942
1943 if (minorgrid) {
1944 // draw minor longitude grid lines
1945 for (lon = ceil(wlon / gridlonMinor) * gridlonMinor; lon < elon;
1946 lon += gridlonMinor) {
1947 wxPoint r;
1948 m_pParentCanvas->GetCanvasPointPix((nlat + slat) / 2, lon, &r);
1949 gldc.DrawLine(r.x, 0, r.x, 10, false);
1950 gldc.DrawLine(r.x, h - 10, r.x, h, false);
1951 }
1952 }
1953
1954 // draw text labels
1955 if (abs(vp.rotation) < .1) {
1956 glEnable(GL_TEXTURE_2D);
1957 glEnable(GL_BLEND);
1958 for (lat = startlat; lat < nlat; lat += gridlatMajor) {
1959 if (fabs(lat - wxRound(lat)) < 1e-5) lat = wxRound(lat);
1960
1961 wxString st =
1962 CalcGridText(lat, gridlatMajor, true); // get text for grid line
1963 int iy;
1964 m_gridfont.GetTextExtent(st, 0, &iy);
1965
1966 if (straight_latitudes) {
1967 wxPoint r, s;
1968 m_pParentCanvas->GetCanvasPointPix(lat, elon, &r);
1969 m_pParentCanvas->GetCanvasPointPix(lat, wlon, &s);
1970
1971 float x = 0, y = -1;
1972 y = (float)(r.y * s.x - s.y * r.x) / (s.x - r.x);
1973 if (y < 0 || y > h) {
1974 y = h - iy;
1975 x = (float)(r.x * s.y - s.x * r.y + (s.x - r.x) * y) / (s.y - r.y);
1976 }
1977
1978 m_gridfont.RenderString(st, x, y);
1979 } else {
1980 // iteratively attempt to find where the latitude line crosses x=0
1981 wxPoint2DDouble r;
1982 double y1, y2, lat1, lon1, lat2, lon2;
1983
1984 y1 = 0, y2 = vp.pix_height;
1985 double error = vp.pix_width, lasterror;
1986 int maxiters = 10;
1987 do {
1988 m_pParentCanvas->GetCanvasPixPoint(0, y1, lat1, lon1);
1989 m_pParentCanvas->GetCanvasPixPoint(0, y2, lat2, lon2);
1990
1991 double y = y1 + (lat1 - lat) * (y2 - y1) / (lat1 - lat2);
1992
1993 m_pParentCanvas->GetDoubleCanvasPointPix(
1994 lat, lon1 + (y1 - y) * (lon2 - lon1) / (y1 - y2), &r);
1995
1996 if (fabs(y - y1) < fabs(y - y2))
1997 y1 = y;
1998 else
1999 y2 = y;
2000
2001 lasterror = error;
2002 error = fabs(r.m_x);
2003 if (--maxiters == 0) break;
2004 } while (error > 1 && error < lasterror);
2005
2006 if (error < 1 && r.m_y >= 0 && r.m_y <= vp.pix_height - iy)
2007 r.m_x = 0;
2008 else
2009 // just draw at center longitude
2010 m_pParentCanvas->GetDoubleCanvasPointPix(lat, vp.clon, &r);
2011
2012 m_gridfont.RenderString(st, r.m_x, r.m_y);
2013 }
2014 }
2015
2016 for (lon = startlon; lon < elon; lon += gridlonMajor) {
2017 if (fabs(lon - wxRound(lon)) < 1e-5) lon = wxRound(lon);
2018
2019 wxPoint r, s;
2020 m_pParentCanvas->GetCanvasPointPix(nlat, lon, &r);
2021 m_pParentCanvas->GetCanvasPointPix(slat, lon, &s);
2022
2023 float xlon = lon;
2024 if (xlon > 180.0)
2025 xlon -= 360.0;
2026 else if (xlon <= -180.0)
2027 xlon += 360.0;
2028
2029 wxString st = CalcGridText(xlon, gridlonMajor, false);
2030 int ix;
2031 m_gridfont.GetTextExtent(st, &ix, 0);
2032
2033 if (straight_longitudes) {
2034 float x = -1, y = 0;
2035 x = (float)(r.x * s.y - s.x * r.y) / (s.y - r.y);
2036 if (x < 0 || x > w) {
2037 x = w - ix;
2038 y = (float)(r.y * s.x - s.y * r.x + (s.y - r.y) * x) / (s.x - r.x);
2039 }
2040
2041 m_gridfont.RenderString(st, x, y);
2042 } else {
2043 // iteratively attempt to find where the latitude line crosses x=0
2044 wxPoint2DDouble r;
2045 double x1, x2, lat1, lon1, lat2, lon2;
2046
2047 x1 = 0, x2 = vp.pix_width;
2048 double error = vp.pix_height, lasterror;
2049 do {
2050 m_pParentCanvas->GetCanvasPixPoint(x1, 0, lat1, lon1);
2051 m_pParentCanvas->GetCanvasPixPoint(x2, 0, lat2, lon2);
2052
2053 double x = x1 + (lon1 - lon) * (x2 - x1) / (lon1 - lon2);
2054
2055 m_pParentCanvas->GetDoubleCanvasPointPix(
2056 lat1 + (x1 - x) * (lat2 - lat1) / (x1 - x2), lon, &r);
2057
2058 if (fabs(x - x1) < fabs(x - x2))
2059 x1 = x;
2060 else
2061 x2 = x;
2062
2063 lasterror = error;
2064 error = fabs(r.m_y);
2065 } while (error > 1 && error < lasterror);
2066
2067 if (error < 1 && r.m_x >= 0 && r.m_x <= vp.pix_width - ix)
2068 r.m_y = 0;
2069 else
2070 // failure, instead just draw the text at center latitude
2071 m_pParentCanvas->GetDoubleCanvasPointPix(
2072 wxMin(wxMax(vp.clat, slat), nlat), lon, &r);
2073
2074 m_gridfont.RenderString(st, r.m_x, r.m_y);
2075 }
2076 }
2077
2078 glDisable(GL_TEXTURE_2D);
2079 glDisable(GL_BLEND);
2080 }
2081}
2082
2083void glChartCanvas::DrawEmboss(ocpnDC &dc, emboss_data *emboss) {
2084 if (!emboss) return;
2085
2086 int w = emboss->width, h = emboss->height;
2087
2088 glEnable(GL_TEXTURE_2D);
2089
2090 // render using opengl and alpha blending
2091 if (!emboss->gltexind) { /* upload to texture */
2092
2093 emboss->glwidth = NextPow2(emboss->width);
2094 emboss->glheight = NextPow2(emboss->height);
2095
2096 /* convert to luminance alpha map */
2097 int size = emboss->glwidth * emboss->glheight;
2098 char *data = new char[2 * size];
2099 for (int i = 0; i < h; i++) {
2100 for (int j = 0; j < emboss->glwidth; j++) {
2101 if (j < w) {
2102 data[2 * ((i * emboss->glwidth) + j)] =
2103 (char)(emboss->pmap[(i * w) + j] > 0 ? 0 : 255);
2104 data[2 * ((i * emboss->glwidth) + j) + 1] =
2105 (char)abs((emboss->pmap[(i * w) + j]));
2106 }
2107 }
2108 }
2109
2110 glGenTextures(1, &emboss->gltexind);
2111 glBindTexture(GL_TEXTURE_2D, emboss->gltexind);
2112 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, emboss->glwidth,
2113 emboss->glheight, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,
2114 data);
2115 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2116 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2117
2118 delete[] data;
2119 }
2120
2121 glBindTexture(GL_TEXTURE_2D, emboss->gltexind);
2122
2123 glEnable(GL_BLEND);
2124
2125 int x = emboss->x, y = emboss->y;
2126
2127 float wp = (float)w / emboss->glwidth;
2128 float hp = (float)h / emboss->glheight;
2129
2130 float coords[8];
2131 float uv[8];
2132
2133 // normal uv
2134 uv[0] = 0;
2135 uv[1] = 0;
2136 uv[2] = wp;
2137 uv[3] = 0;
2138 uv[4] = wp;
2139 uv[5] = hp;
2140 uv[6] = 0;
2141 uv[7] = hp;
2142
2143 // pixels
2144 coords[0] = 0;
2145 coords[1] = 0;
2146 coords[2] = w;
2147 coords[3] = 0;
2148 coords[4] = w;
2149 coords[5] = h;
2150 coords[6] = 0;
2151 coords[7] = h;
2152
2153 // FIXME(dave) Find a way to make this thing a little transparaent
2154 RenderSingleTexture(dc, coords, uv, m_pParentCanvas->GetpVP(), x, y, 0);
2155
2156 glDisable(GL_BLEND);
2157 glDisable(GL_TEXTURE_2D);
2158}
2159
2160void glChartCanvas::ShipDraw(ocpnDC &dc) {
2161 if (!m_pParentCanvas->GetVP().IsValid()) return;
2162 wxPoint GPSOffsetPixels(0, 0);
2163 wxPoint2DDouble lGPSPoint, lShipMidPoint;
2164
2165 // COG/SOG may be undefined in NMEA data stream
2166 float pCog = std::isnan(gCog) ? 0 : gCog;
2167 float pSog = std::isnan(gSog) ? 0 : gSog;
2168
2169 // Here, calculate the ownship location on screen, and make it so.
2170 // Special case: No need for such precision on chart drag operations
2171 double shift_dx = 0;
2172 double shift_dy = 0;
2173 bool dynamic = m_pParentCanvas->m_animationActive ||
2174 m_pParentCanvas->m_MouseDragging ||
2175 m_pParentCanvas->m_chart_drag_inertia_active;
2176 if (m_pParentCanvas->m_bFollow && !dynamic) {
2177 lGPSPoint.m_x = m_pParentCanvas->GetVP().pix_width / 2;
2178 lGPSPoint.m_y = m_pParentCanvas->GetVP().pix_height / 2;
2179 if (m_pParentCanvas->m_bLookAhead) {
2180 // In "b_follow" mode, we have a-priori information about the desired
2181 // screen coordinates of ownship, as a pixel offset from center.
2182 // Use this information as a performance optimization,
2183 // at larger viewing scales.
2184 if (m_pParentCanvas->GetVPChartScale() < 2e6) {
2185 double angle = m_pParentCanvas->dir_to_shift * PI / 180.;
2186 angle += m_pParentCanvas->GetVPRotation();
2187 shift_dx = m_pParentCanvas->meters_to_shift * sin(angle) *
2188 m_pParentCanvas->GetVPScale();
2189 lGPSPoint.m_x -= shift_dx / cos(gLat * PI / 180.);
2190 shift_dy = m_pParentCanvas->meters_to_shift * cos(angle) *
2191 m_pParentCanvas->GetVPScale();
2192 lGPSPoint.m_y += shift_dy / cos(gLat * PI / 180.);
2193 } else {
2194 m_pParentCanvas->GetDoubleCanvasPointPix(gLat, gLon, &lGPSPoint);
2195 }
2196 } else {
2197 lGPSPoint.m_x -= m_pParentCanvas->m_OSoffsetx;
2198 lGPSPoint.m_y += m_pParentCanvas->m_OSoffsety;
2199 }
2200 } else {
2201 m_pParentCanvas->GetDoubleCanvasPointPixVP(m_pParentCanvas->GetVP(), gLat,
2202 gLon, &lGPSPoint);
2203 }
2204
2205 lShipMidPoint = lGPSPoint;
2206
2207 // Draw the icon rotated to the COG
2208 // or to the Hdt if available
2209 float icon_hdt = pCog;
2210 if (!std::isnan(gHdt)) icon_hdt = gHdt;
2211
2212 // COG may be undefined in NMEA data stream
2213 if (std::isnan(icon_hdt)) icon_hdt = 0.0;
2214
2215 // Calculate the ownship drawing angle icon_rad using an assumed 10 minute
2216 // predictor
2217 double osd_head_lat, osd_head_lon;
2218 wxPoint2DDouble osd_head_point;
2219
2220 ll_gc_ll(gLat, gLon, icon_hdt, pSog * 10. / 60., &osd_head_lat,
2221 &osd_head_lon);
2222
2223 m_pParentCanvas->GetDoubleCanvasPointPixVP(
2224 m_pParentCanvas->GetVP(), osd_head_lat, osd_head_lon, &osd_head_point);
2225
2226 double icon_rad = atan2f((float)(osd_head_point.m_y - lShipMidPoint.m_y),
2227 (float)(osd_head_point.m_x - lShipMidPoint.m_x));
2228 icon_rad += (float)PI;
2229
2230 if (pSog < 0.2)
2231 icon_rad =
2232 ((icon_hdt + 90.) * PI / 180.) + m_pParentCanvas->GetVP().rotation;
2233
2234 // Another draw test ,based on pixels, assuming the ship icon is a fixed
2235 // nominal size and is just barely outside the viewport ....
2236 BoundingBox bb_screen(0, 0, m_pParentCanvas->GetVP().pix_width,
2237 m_pParentCanvas->GetVP().pix_height);
2238
2239 // TODO: fix to include actual size of boat that will be rendered
2240 int img_height = 0;
2241
2242 if (bb_screen.PointInBox(lShipMidPoint, 20)) {
2243 if (g_GLOptions.m_GLLineSmoothing) glEnable(GL_LINE_SMOOTH);
2244 if (g_GLOptions.m_GLPolygonSmoothing) glEnable(GL_POLYGON_SMOOTH);
2245
2246 if (m_pParentCanvas->GetVP().chart_scale >
2247 300000) // According to S52, this should be 50,000
2248 {
2249 float scale_factor = 1.0;
2250 // Scale the generic icon to ChartScaleFactor, slightly softened....
2251 if ((g_ChartScaleFactorExp > 1.0) && (g_OwnShipIconType == 0))
2252 scale_factor = (log(g_ChartScaleFactorExp) + 1.0) * 1.1;
2253
2254 float nominal_ownship_size_mm = m_pParentCanvas->m_display_size_mm / 44.0;
2255 nominal_ownship_size_mm = wxMin(nominal_ownship_size_mm, 15.0);
2256 nominal_ownship_size_mm = wxMax(nominal_ownship_size_mm, 7.0);
2257
2258 scale_factor *= m_pParentCanvas->GetContentScaleFactor();
2259
2260 float nominal_ownship_size_pixels =
2261 wxMax(20.0, m_pParentCanvas->GetPixPerMM() *
2262 nominal_ownship_size_mm); // nominal length, but not
2263 // less than 20 pixel
2264 float v = (nominal_ownship_size_pixels * scale_factor) / 3;
2265
2266 wxPen ppSmallScaleShip;
2267 if (SHIP_NORMAL == m_pParentCanvas->m_ownship_state)
2268 ppSmallScaleShip =
2269 wxPen(GetGlobalColor("URED"), v / 5, wxPENSTYLE_SOLID);
2270 else
2271 ppSmallScaleShip =
2272 wxPen(GetGlobalColor("YELO1"), v / 5, wxPENSTYLE_SOLID);
2273 dc.SetPen(ppSmallScaleShip);
2274
2275 dc.SetBrush(wxBrush(GetGlobalColor("URED"), wxBRUSHSTYLE_TRANSPARENT));
2276
2277 // start with cross
2278 dc.DrawLine((-v * 1.2) + lShipMidPoint.m_x, lShipMidPoint.m_y,
2279 (v * 1.2) + lShipMidPoint.m_x, lShipMidPoint.m_y);
2280 dc.DrawLine(lShipMidPoint.m_x, (-v * 1.2) + lShipMidPoint.m_y,
2281 lShipMidPoint.m_x, (v * 1.2) + lShipMidPoint.m_y);
2282
2283 // Two circles
2284 dc.StrokeCircle(lShipMidPoint.m_x, lShipMidPoint.m_y, v);
2285 dc.StrokeCircle(lShipMidPoint.m_x, lShipMidPoint.m_y, 0.6 * v);
2286 img_height = 20;
2287 } else {
2288 int draw_color = SHIP_INVALID;
2289 if (SHIP_NORMAL == m_pParentCanvas->m_ownship_state)
2290 draw_color = SHIP_NORMAL;
2291 else if (SHIP_LOWACCURACY == m_pParentCanvas->m_ownship_state)
2292 draw_color = SHIP_LOWACCURACY;
2293
2294 if (!ownship_tex ||
2295 (draw_color !=
2296 ownship_color)) { /* initial run, create texture for ownship,
2297 also needed at colorscheme changes (not
2298 implemented) */
2299
2300 ownship_color = draw_color;
2301
2302 if (ownship_tex) glDeleteTextures(1, &ownship_tex);
2303
2304 glGenTextures(1, &ownship_tex);
2305 glBindTexture(GL_TEXTURE_2D, ownship_tex);
2306
2307 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2308 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2309
2310 wxImage image;
2311 if (m_pParentCanvas->m_pos_image_user) {
2312 switch (draw_color) {
2313 case SHIP_INVALID:
2314 image = *m_pParentCanvas->m_pos_image_user_grey;
2315 break;
2316 case SHIP_NORMAL:
2317 image = *m_pParentCanvas->m_pos_image_user;
2318 break;
2319 case SHIP_LOWACCURACY:
2320 image = *m_pParentCanvas->m_pos_image_user_yellow;
2321 break;
2322 }
2323 } else {
2324 switch (draw_color) {
2325 case SHIP_INVALID:
2326 image = *m_pParentCanvas->m_pos_image_grey;
2327 break;
2328 case SHIP_NORMAL:
2329 image = *m_pParentCanvas->m_pos_image_red;
2330 break;
2331 case SHIP_LOWACCURACY:
2332 image = *m_pParentCanvas->m_pos_image_yellow;
2333 break;
2334 }
2335 }
2336
2337 int w = image.GetWidth(), h = image.GetHeight();
2338 int glw = NextPow2(w), glh = NextPow2(h);
2339 ownship_size = wxSize(w, h);
2340 ownship_tex_size = wxSize(glw, glh);
2341
2342 unsigned char *d = image.GetData();
2343 unsigned char *a = image.GetAlpha();
2344 unsigned char *e = new unsigned char[4 * w * h];
2345
2346 if (d && e && a) {
2347 for (int p = 0; p < w * h; p++) {
2348 e[4 * p + 0] = d[3 * p + 0];
2349 e[4 * p + 1] = d[3 * p + 1];
2350 e[4 * p + 2] = d[3 * p + 2];
2351 e[4 * p + 3] = a[p];
2352 }
2353 }
2354 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, glw, glh, 0, GL_RGBA,
2355 GL_UNSIGNED_BYTE, 0);
2356
2357 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
2358 e);
2359 delete[] e;
2360 }
2361
2362 /* establish ship color */
2363#ifndef USE_ANDROID_GLES2
2364 if (m_pParentCanvas->m_pos_image_user)
2365 glColor4ub(255, 255, 255, 255);
2366 else if (SHIP_NORMAL == m_pParentCanvas->m_ownship_state)
2367 glColor4ub(255, 0, 0, 255);
2368 else if (SHIP_LOWACCURACY == m_pParentCanvas->m_ownship_state)
2369 glColor4ub(255, 255, 0, 255);
2370 else
2371 glColor4ub(128, 128, 128, 255);
2372#endif
2373 float scale_factor_y = 1.0;
2374 float scale_factor_x = 1.0;
2375
2376 int ownShipWidth = 22; // Default values from s_ownship_icon
2377 int ownShipLength = 84;
2378 lShipMidPoint = lGPSPoint;
2379
2380 /* scaled ship? */
2381 if (g_OwnShipIconType != 0)
2382 m_pParentCanvas->ComputeShipScaleFactor(
2383 icon_hdt, ownShipWidth, ownShipLength, lShipMidPoint,
2384 GPSOffsetPixels, lGPSPoint, scale_factor_x, scale_factor_y);
2385
2386 glEnable(GL_BLEND);
2387
2388 // Scale the generic icon to ChartScaleFactor, slightly softened....
2389 if ((g_ShipScaleFactorExp > 1.0) && (g_OwnShipIconType == 0)) {
2390 scale_factor_x = (log(g_ShipScaleFactorExp) + 1.0) * 1.1;
2391 scale_factor_y = (log(g_ShipScaleFactorExp) + 1.0) * 1.1;
2392 }
2393
2394 // Correct for scaled displays, e.g. Retina
2395 scale_factor_x *= m_pParentCanvas->GetContentScaleFactor();
2396 scale_factor_y *= m_pParentCanvas->GetContentScaleFactor();
2397
2398 // Set the size of the little circle showing the GPS reference position
2399 // Set a default early, adjust later based on render type
2400 float gps_circle_radius = 3.0;
2401
2402 if (g_OwnShipIconType == 0) { // Default Bitmap
2403
2404 glEnable(GL_TEXTURE_2D);
2405 glBindTexture(GL_TEXTURE_2D, ownship_tex);
2406
2407 // We choose to render the ownship bitmap at roughly the same size( in
2408 // pixels ) as the DC mode renderer.
2409 // For ultra-high definition displays, we clamp the actual on-screen
2410 // size to be no smaller than 7.0 mm Similarly, for lo-res displays, we
2411 // limit the actual size to be no larger than 15 mm maximum.
2412
2413 // Get bitmap height in pixels
2414 int image_height_bitmap = m_pParentCanvas->m_pos_image_red->GetHeight();
2415 if (m_pParentCanvas->m_pos_image_user)
2416 image_height_bitmap = m_pParentCanvas->m_pos_image_user->GetHeight();
2417
2418 float nominal_ownship_size_mm =
2419 image_height_bitmap / m_pParentCanvas->GetPixPerMM();
2420
2421 nominal_ownship_size_mm = wxMin(nominal_ownship_size_mm, 15.0);
2422 nominal_ownship_size_mm = wxMax(nominal_ownship_size_mm, 7.0);
2423
2424 float nominal_ownship_size_pixels =
2425 m_pParentCanvas->GetPixPerMM() * nominal_ownship_size_mm;
2426
2427 if (m_pParentCanvas->GetContentScaleFactor() == 1.0) {
2428 nominal_ownship_size_pixels = wxMax(
2429 20.0, nominal_ownship_size_pixels); // not less than 20 pixel
2430 }
2431
2432 float h = nominal_ownship_size_pixels * scale_factor_y;
2433 float w = nominal_ownship_size_pixels * scale_factor_x *
2434 ownship_size.x / ownship_size.y;
2435 float glw = ownship_tex_size.x, glh = ownship_tex_size.y;
2436 float u = ownship_size.x / glw, v = ownship_size.y / glh;
2437
2438 // printf("%g %g %g %g %g %g %g\n",
2439 // nominal_ownship_size_mm, nominal_ownship_size_pixels,
2440 // h, w, u, v, m_pParentCanvas->m_display_size_mm);
2441 // tweak GPS reference point indicator size
2442 gps_circle_radius = w / 5;
2443
2444 float uv[8], coords[8];
2445 uv[0] = 0;
2446 uv[1] = 0;
2447 uv[2] = u;
2448 uv[3] = 0;
2449 uv[4] = u;
2450 uv[5] = v;
2451 uv[6] = 0;
2452 uv[7] = v;
2453
2454 coords[0] = -w / 2;
2455 coords[1] = -h / 2;
2456 coords[2] = w / 2;
2457 coords[3] = -h / 2;
2458 coords[4] = w / 2;
2459 coords[5] = h / 2;
2460 coords[6] = -w / 2;
2461 coords[7] = h / 2;
2462
2463 RenderSingleTexture(dc, coords, uv, m_pParentCanvas->GetpVP(),
2464 lShipMidPoint.m_x, lShipMidPoint.m_y,
2465 icon_rad - PI / 2);
2466 glDisable(GL_TEXTURE_2D);
2467 } else if (g_OwnShipIconType == 1) { // Scaled Bitmap
2468
2469 glEnable(GL_TEXTURE_2D);
2470 glBindTexture(GL_TEXTURE_2D, ownship_tex);
2471
2472 float nominal_ownship_size_pixels_y = 84;
2473 float nominal_ownship_size_pixels_x = 22;
2474
2475 float h = nominal_ownship_size_pixels_y * scale_factor_y;
2476 float w = nominal_ownship_size_pixels_x * scale_factor_x;
2477
2478 float u = (float)ownship_size.x / ownship_tex_size.x,
2479 v = (float)ownship_size.y / ownship_tex_size.y;
2480
2481 // tweak GPS reference point indicator size
2482 gps_circle_radius = w / 5;
2483
2484 float uv[8], coords[8];
2485 uv[0] = 0;
2486 uv[1] = 0;
2487 uv[2] = u;
2488 uv[3] = 0;
2489 uv[4] = u;
2490 uv[5] = v;
2491 uv[6] = 0;
2492 uv[7] = v;
2493
2494 coords[0] = -w / 2;
2495 coords[1] = -h / 2;
2496 coords[2] = w / 2;
2497 coords[3] = -h / 2;
2498 coords[4] = w / 2;
2499 coords[5] = h / 2;
2500 coords[6] = -w / 2;
2501 coords[7] = h / 2;
2502
2503 RenderSingleTexture(dc, coords, uv, m_pParentCanvas->GetpVP(),
2504 lShipMidPoint.m_x, lShipMidPoint.m_y,
2505 icon_rad - PI / 2);
2506
2507 glDisable(GL_TEXTURE_2D);
2508 } else if (g_OwnShipIconType == 2) { // Scaled Vector
2509 // static const GLint s_ownship_icon[] = { 5, -42, 11,
2510 // -28, 11, 42, -11, 42,
2511 // -11, -28, -5,
2512 // -42, -11, 0,
2513 // 11, 0, 0, 42,
2514 // 0, -42 };
2515
2516 wxPoint shipPoints[6];
2517
2518 wxColour colour = m_pParentCanvas->ShipColor();
2519 wxPen ppPen(*wxBLACK, 1);
2520 wxBrush ppBrush(colour);
2521 dc.SetPen(ppPen);
2522 dc.SetBrush(ppBrush);
2523
2524 shipPoints[0].x = 0 * scale_factor_x;
2525 shipPoints[0].y = -28 * scale_factor_y;
2526 shipPoints[1].x = 11 * scale_factor_x;
2527 shipPoints[1].y = -28 * scale_factor_y;
2528 shipPoints[2].x = 11 * scale_factor_x;
2529 shipPoints[2].y = 42 * scale_factor_y;
2530 shipPoints[3].x = 0 * scale_factor_x;
2531 shipPoints[3].y = 42 * scale_factor_y;
2532 dc.DrawPolygon(4, shipPoints, lShipMidPoint.m_x, lShipMidPoint.m_y, 1,
2533 icon_rad - PI / 2);
2534
2535 shipPoints[0].x = 0 * scale_factor_x;
2536 shipPoints[0].y = -42 * scale_factor_y;
2537 shipPoints[1].x = 5 * scale_factor_x;
2538 shipPoints[1].y = -42 * scale_factor_y;
2539 shipPoints[2].x = 11 * scale_factor_x;
2540 shipPoints[2].y = -28 * scale_factor_y;
2541 shipPoints[3].x = 0 * scale_factor_x;
2542 shipPoints[3].y = -28 * scale_factor_y;
2543 dc.DrawPolygon(4, shipPoints, lShipMidPoint.m_x, lShipMidPoint.m_y, 1,
2544 icon_rad - PI / 2);
2545
2546 shipPoints[0].x = 0 * scale_factor_x;
2547 shipPoints[0].y = -28 * scale_factor_y;
2548 shipPoints[1].x = -11 * scale_factor_x;
2549 shipPoints[1].y = -28 * scale_factor_y;
2550 shipPoints[2].x = -11 * scale_factor_x;
2551 shipPoints[2].y = 42 * scale_factor_y;
2552 shipPoints[3].x = 0 * scale_factor_x;
2553 shipPoints[3].y = 42 * scale_factor_y;
2554 dc.DrawPolygon(4, shipPoints, lShipMidPoint.m_x, lShipMidPoint.m_y, 1,
2555 icon_rad - PI / 2);
2556
2557 shipPoints[0].x = 0 * scale_factor_x;
2558 shipPoints[0].y = -42 * scale_factor_y;
2559 shipPoints[1].x = -5 * scale_factor_x;
2560 shipPoints[1].y = -42 * scale_factor_y;
2561 shipPoints[2].x = -11 * scale_factor_x;
2562 shipPoints[2].y = -28 * scale_factor_y;
2563 shipPoints[3].x = 0 * scale_factor_x;
2564 shipPoints[3].y = -28 * scale_factor_y;
2565 dc.DrawPolygon(4, shipPoints, lShipMidPoint.m_x, lShipMidPoint.m_y, 1,
2566 icon_rad - PI / 2);
2567
2568 // draw with cross
2569 double p1x = -11 * scale_factor_x;
2570 double p2x = 11 * scale_factor_x;
2571 double p1y = 0;
2572 double p2y = 0;
2573 double p1xr =
2574 ((p1x)*cos(icon_rad - PI / 2)) - ((p1y)*sin(icon_rad - PI / 2));
2575 double p2xr =
2576 ((p2x)*cos(icon_rad - PI / 2)) - ((p2y)*sin(icon_rad - PI / 2));
2577 double p1yr =
2578 ((p1y)*cos(icon_rad - PI / 2)) + ((p1x)*sin(icon_rad - PI / 2));
2579 double p2yr =
2580 ((p2y)*cos(icon_rad - PI / 2)) + ((p2x)*sin(icon_rad - PI / 2));
2581 dc.DrawLine(p1xr + lShipMidPoint.m_x, p1yr + lShipMidPoint.m_y,
2582 p2xr + lShipMidPoint.m_x, p2yr + lShipMidPoint.m_y);
2583
2584 p1x = 0;
2585 p2x = 0;
2586 p1y = -42 * scale_factor_y;
2587 p2y = 42 * scale_factor_y;
2588 p1xr = ((p1x)*cos(icon_rad - PI / 2)) - ((p1y)*sin(icon_rad - PI / 2));
2589 p2xr = ((p2x)*cos(icon_rad - PI / 2)) - ((p2y)*sin(icon_rad - PI / 2));
2590 p1yr = ((p1y)*cos(icon_rad - PI / 2)) + ((p1x)*sin(icon_rad - PI / 2));
2591 p2yr = ((p2y)*cos(icon_rad - PI / 2)) + ((p2x)*sin(icon_rad - PI / 2));
2592 dc.DrawLine(p1xr + lShipMidPoint.m_x, p1yr + lShipMidPoint.m_y,
2593 p2xr + lShipMidPoint.m_x, p2yr + lShipMidPoint.m_y);
2594 }
2595
2596 img_height = ownShipLength * scale_factor_y;
2597
2598 // Reference point, where the GPS antenna is
2599 if (m_pParentCanvas->m_pos_image_user) gps_circle_radius = 1;
2600
2601 wxPen ppPen1(GetGlobalColor("UBLCK"), 1, wxPENSTYLE_SOLID);
2602 dc.SetPen(ppPen1);
2603 dc.SetBrush(wxBrush(GetGlobalColor("CHWHT")));
2604
2605 dc.StrokeCircle(lGPSPoint.m_x, lGPSPoint.m_y, gps_circle_radius);
2606 }
2607
2608 // glDisableClientState(GL_VERTEX_ARRAY);
2609 glDisable(GL_LINE_SMOOTH);
2610 glDisable(GL_POLYGON_SMOOTH);
2611 glDisable(GL_BLEND);
2612 }
2613
2614 m_pParentCanvas->ShipIndicatorsDraw(dc, img_height, GPSOffsetPixels,
2615 lGPSPoint);
2616}
2617
2618void glChartCanvas::DrawFloatingOverlayObjects(ocpnDC &dc) {
2619 ViewPort &vp = m_pParentCanvas->GetVP();
2620
2621 // Draw any active or selected routes now
2622 extern Routeman *g_pRouteMan;
2623 // extern Track *g_pActiveTrack;
2624 Route *active_route = g_pRouteMan->GetpActiveRoute();
2625
2626 // if( active_route ) active_route->DrawGL( vp, region );
2627 // if( g_pActiveTrack ) g_pActiveTrack->Draw( dc, vp );
2628 // if( m_pParentCanvas->m_pSelectedRoute )
2629 // m_pParentCanvas->m_pSelectedRoute->DrawGL( vp, region );
2630
2631 GridDraw();
2632
2633 g_overlayCanvas = m_pParentCanvas;
2634 if (g_pi_manager) {
2635 g_pi_manager->SendViewPortToRequestingPlugIns(vp);
2636 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
2637 m_pcontext, vp, m_pParentCanvas->m_canvasIndex, OVERLAY_LEGACY);
2638 }
2639
2640 // all functions called with m_pParentCanvas-> are still slow because they go
2641 // through ocpndc
2642 AISDrawAreaNotices(dc, m_pParentCanvas->GetVP(), m_pParentCanvas);
2643
2644 m_pParentCanvas->DrawAnchorWatchPoints(dc);
2645 AISDraw(dc, m_pParentCanvas->GetVP(), m_pParentCanvas);
2646 ShipDraw(dc);
2647 m_pParentCanvas->AlertDraw(dc);
2648
2649 m_pParentCanvas->RenderVisibleSectorLights(dc);
2650
2651 m_pParentCanvas->RenderRouteLegs(dc);
2652 m_pParentCanvas->RenderShipToActive(dc, true);
2653 m_pParentCanvas->ScaleBarDraw(dc);
2654 s57_DrawExtendedLightSectorsGL(dc, m_pParentCanvas->VPoint,
2655 m_pParentCanvas->extendedSectorLegs);
2656 if (g_pi_manager) {
2657 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
2658 m_pcontext, vp, m_pParentCanvas->m_canvasIndex, OVERLAY_OVER_SHIPS);
2659 }
2660}
2661
2662void glChartCanvas::DrawChartBar(ocpnDC &dc) {
2663 if (m_pParentCanvas->GetPiano()) {
2664 int canvas_height = GetClientSize().y;
2665 canvas_height *= m_displayScale;
2666
2667 m_pParentCanvas->GetPiano()->DrawGL(
2668 canvas_height - m_pParentCanvas->GetPiano()->GetHeight());
2669 }
2670}
2671
2672void glChartCanvas::DrawQuiting() {
2673#ifndef USE_ANDROID_GLES2
2674 GLubyte pattern[8][8];
2675 for (int y = 0; y < 8; y++)
2676 for (int x = 0; x < 8; x++) pattern[y][x] = (y == x) * 255;
2677
2678 glEnable(GL_BLEND);
2679 glEnable(GL_TEXTURE_2D);
2680 glBindTexture(GL_TEXTURE_2D, 0);
2681
2682 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2683 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2684 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2685
2686 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 8, 8, 0, GL_ALPHA, GL_UNSIGNED_BYTE,
2687 pattern);
2688 glColor3f(0, 0, 0);
2689
2690 float x = GetSize().x, y = GetSize().y;
2691 float u = x / 8, v = y / 8;
2692
2693 glBegin(GL_QUADS);
2694 glTexCoord2f(0, 0);
2695 glVertex2f(0, 0);
2696 glTexCoord2f(0, v);
2697 glVertex2f(0, y);
2698 glTexCoord2f(u, v);
2699 glVertex2f(x, y);
2700 glTexCoord2f(u, 0);
2701 glVertex2f(x, 0);
2702 glEnd();
2703
2704 glDisable(GL_TEXTURE_2D);
2705 glDisable(GL_BLEND);
2706#endif
2707}
2708
2709void glChartCanvas::DrawCloseMessage(wxString msg) {
2710#ifndef USE_ANDROID_GLES2
2711
2712 if (1) {
2713 wxFont *pfont = FontMgr::Get().FindOrCreateFont(
2714 12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
2715
2716 TexFont texfont;
2717
2718 texfont.Build(*pfont, 1, 1);
2719 int w, h;
2720 texfont.GetTextExtent(msg, &w, &h);
2721 h += 2;
2722 int yp = m_pParentCanvas->GetVP().pix_height / 2;
2723 int xp = (m_pParentCanvas->GetVP().pix_width - w) / 2;
2724
2725 glColor3ub(243, 229, 47);
2726
2727 glBegin(GL_QUADS);
2728 glVertex2i(xp, yp);
2729 glVertex2i(xp + w, yp);
2730 glVertex2i(xp + w, yp + h);
2731 glVertex2i(xp, yp + h);
2732 glEnd();
2733
2734 glEnable(GL_BLEND);
2735
2736 glColor3ub(0, 0, 0);
2737 glEnable(GL_TEXTURE_2D);
2738 texfont.RenderString(msg, xp, yp);
2739 glDisable(GL_TEXTURE_2D);
2740 glDisable(GL_BLEND);
2741 }
2742#endif
2743}
2744
2745GLShaderProgram *pStaticShader;
2746
2747static std::list<double *> combine_work_data;
2748static void combineCallbackD(GLdouble coords[3], GLdouble *vertex_data[4],
2749 GLfloat weight[4], GLdouble **dataOut) {
2750 double *vertex = new double[3];
2751 combine_work_data.push_back(vertex);
2752 memcpy(vertex, coords, 3 * (sizeof *coords));
2753 *dataOut = vertex;
2754}
2755
2756#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
2757void vertexCallbackD_GLSL(GLvoid *vertex) {
2758 GLdouble *pointer = (GLdouble *)vertex;
2759 s_tess_vertex_work.push_back(pointer[0]);
2760 s_tess_vertex_work.push_back(pointer[1]);
2761}
2762
2763void beginCallbackD_GLSL(GLenum mode) {
2764 s_tess_mode = mode;
2765 s_tess_vertex_work.clear();
2766}
2767
2768void endCallbackD_GLSL() {
2769 if (!s_tess_vertex_work.empty() && (s_tess_vertex_work.size() % 2 == 0)) {
2770 GLShaderProgram *shader = pStaticShader;
2771 shader->Bind();
2772
2773 shader->SetUniformMatrix4fv("MVMatrix",
2774 (GLfloat *)s_tessVP.vp_matrix_transform);
2775
2776 mat4x4 identityMatrix;
2777 mat4x4_identity(identityMatrix);
2778 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)identityMatrix);
2779
2780 // Use color stored in static variable.
2781 float colorv[4];
2782 colorv[0] = s_regionColor.Red() / float(256);
2783 colorv[1] = s_regionColor.Green() / float(256);
2784 colorv[2] = s_regionColor.Blue() / float(256);
2785 colorv[3] = s_regionColor.Alpha() / float(256);
2786 shader->SetUniform4fv("color", colorv);
2787 shader->SetAttributePointerf("position", s_tess_vertex_work.data());
2788
2789 glDrawArrays(s_tess_mode, 0, s_tess_vertex_work.size() / 2);
2790
2791 shader->UnBind();
2792 } else
2793 wxLogError(
2794 "::endCallbackD_GLSL() called with wrong tess vertex vector length "
2795 "(%d).",
2796 s_tess_vertex_work.size());
2797}
2798#else
2799void vertexCallbackD(GLvoid *vertex) { glVertex3dv((GLdouble *)vertex); }
2800
2801void beginCallbackD(GLenum mode) { glBegin(mode); }
2802
2803void endCallbackD() { glEnd(); }
2804
2805#endif
2806
2807void glChartCanvas::DrawRegion(ViewPort &vp, const LLRegion &region) {
2808 float lat_dist, lon_dist;
2809 GetLatLonCurveDist(vp, lat_dist, lon_dist);
2810
2811 GLUtesselator *tobj = gluNewTess();
2812 if (!pStaticShader) pStaticShader = GetStaticTriShader();
2813
2814#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
2815 gluTessCallback(tobj, GLU_TESS_VERTEX, (_GLUfuncptr)&vertexCallbackD_GLSL);
2816 gluTessCallback(tobj, GLU_TESS_BEGIN, (_GLUfuncptr)&beginCallbackD_GLSL);
2817 gluTessCallback(tobj, GLU_TESS_END, (_GLUfuncptr)&endCallbackD_GLSL);
2818 gluTessCallback(tobj, GLU_TESS_COMBINE, (_GLUfuncptr)&combineCallbackD);
2819 s_tessVP = vp;
2820
2821#else
2822 gluTessCallback(tobj, GLU_TESS_VERTEX, (_GLUfuncptr)&vertexCallbackD);
2823 gluTessCallback(tobj, GLU_TESS_BEGIN, (_GLUfuncptr)&beginCallbackD);
2824 gluTessCallback(tobj, GLU_TESS_END, (_GLUfuncptr)&endCallbackD);
2825 gluTessCallback(tobj, GLU_TESS_COMBINE, (_GLUfuncptr)&combineCallbackD);
2826#endif
2827
2828 gluTessNormal(tobj, 0, 0, 1);
2829
2830 gluTessBeginPolygon(tobj, NULL);
2831 for (auto i = region.contours.begin(); i != region.contours.end(); i++) {
2832 gluTessBeginContour(tobj);
2833 contour_pt l = *i->rbegin();
2834 double sml[2];
2835 bool sml_valid = false;
2836 for (poly_contour::const_iterator j = i->begin(); j != i->end(); j++) {
2837 int lat_splits = floor(fabs(j->y - l.y) / lat_dist);
2838 int lon_splits = floor(fabs(j->x - l.x) / lon_dist);
2839 int splits = wxMax(lat_splits, lon_splits) + 1;
2840
2841 double smj[2];
2842 if (splits != 1) {
2843 // must perform border interpolation in mercator space as this is what
2844 // the charts use
2845 toSM(j->y, j->x, 0, 0, smj + 0, smj + 1);
2846 if (!sml_valid) toSM(l.y, l.x, 0, 0, sml + 0, sml + 1);
2847 }
2848
2849 for (int i = 0; i < splits; i++) {
2850 double lat, lon;
2851 if (i == splits - 1)
2852 lat = j->y, lon = j->x;
2853 else {
2854 double d = (double)(i + 1) / splits;
2855 fromSM(d * smj[0] + (1 - d) * sml[0], d * smj[1] + (1 - d) * sml[1],
2856 0, 0, &lat, &lon);
2857 }
2858 wxPoint2DDouble q = vp.GetDoublePixFromLL(lat, lon);
2859 if (std::isnan(q.m_x)) continue;
2860
2861 double *p = new double[6];
2862
2863 // p[0] = q.m_x, p[1] = q.m_y, p[2] = 0;
2864 // It is reasonable to use wxRound() here,
2865 // since we are working with pixel coordinates at this point
2866 p[0] = wxRound(q.m_x), p[1] = wxRound(q.m_y), p[2] = 0;
2867
2868 // wxPoint pt = vp.GetPixFromLL(lat, lon);
2869 // p[0] = pt.x, p[1] = pt.y, p[2] = 0;
2870
2871 gluTessVertex(tobj, p, p);
2872 combine_work_data.push_back(p);
2873 }
2874 l = *j;
2875
2876 if ((sml_valid = splits != 1)) memcpy(sml, smj, sizeof smj);
2877 }
2878 gluTessEndContour(tobj);
2879 }
2880 gluTessEndPolygon(tobj);
2881
2882 gluDeleteTess(tobj);
2883
2884 for (std::list<double *>::iterator i = combine_work_data.begin();
2885 i != combine_work_data.end(); i++)
2886 delete[] *i;
2887 combine_work_data.clear();
2888}
2889
2890/* set stencil buffer to clip in this region, and optionally clear using the
2891 * current color */
2892void glChartCanvas::SetClipRegion(ViewPort &vp, const LLRegion &region) {
2893 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // disable color buffer
2894
2895 if (s_b_useStencil) {
2896 // Create a stencil buffer for clipping to the region
2897 glEnable(GL_STENCIL_TEST);
2898 glStencilMask(0x1); // write only into bit 0 of the stencil buffer
2899 glClear(GL_STENCIL_BUFFER_BIT);
2900
2901 // We are going to write "1" into the stencil buffer wherever the region
2902 // is valid
2903 glStencilFunc(GL_ALWAYS, 1, 1);
2904 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
2905 }
2906// #ifndef USE_ANDROID_GLES2
2907#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
2908
2909 else // Use depth buffer for clipping
2910 {
2911 glEnable(GL_DEPTH_TEST); // to enable writing to the depth buffer
2912 glDepthFunc(GL_ALWAYS); // to ensure everything you draw passes
2913 glDepthMask(GL_TRUE); // to allow writes to the depth buffer
2914
2915 glClear(GL_DEPTH_BUFFER_BIT); // for a fresh start
2916
2917 // Decompose the region into rectangles, and draw as quads
2918 // With z = 1
2919 // dep buffer clear = 1
2920 // 1 makes 0 in dep buffer, works
2921 // 0 make .5 in depth buffer
2922 // -1 makes 1 in dep buffer
2923
2924 // Depth buffer runs from 0 at z = 1 to 1 at z = -1
2925 // Draw the clip geometry at z = 0.5, giving a depth buffer value of 0.25
2926 // Subsequent drawing at z=0 (depth = 0.5) will pass if using
2927 // glDepthFunc(GL_GREATER);
2928 glTranslatef(0, 0, .5);
2929 }
2930#endif
2931
2932 s_regionColor = wxColor(0, 0, 0, 255);
2933 DrawRegion(vp, region);
2934
2935 if (s_b_useStencil) {
2936 // Now set the stencil ops to subsequently render only where the stencil
2937 // bit is "1"
2938 glStencilFunc(GL_EQUAL, 1, 1);
2939 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2940 }
2941// #ifndef USE_ANDROID_GLES2
2942#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
2943 else {
2944 glDepthFunc(GL_GREATER); // Set the test value
2945 glDepthMask(GL_FALSE); // disable depth buffer
2946 glTranslatef(0, 0, -.5); // reset translation
2947 }
2948#endif
2949 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // re-enable color buffer
2950}
2951
2952void glChartCanvas::SetClipRect(const ViewPort &vp, const wxRect &rect,
2953 bool b_clear) {
2954 /* for some reason this causes an occasional bug in depth mode, I cannot
2955 seem to solve it yet, so for now: */
2956 if (s_b_useStencil && s_b_useScissorTest) {
2957 wxRect vp_rect(0, 0, vp.pix_width, vp.pix_height);
2958 if (rect != vp_rect) {
2959 glEnable(GL_SCISSOR_TEST);
2960 glScissor(rect.x, vp.pix_height - rect.height - rect.y, rect.width,
2961 rect.height);
2962 }
2963#ifndef USE_ANDROID_GLES2
2964#endif
2965 return;
2966 }
2967}
2968
2969void glChartCanvas::DisableClipRegion() {
2970 glDisable(GL_SCISSOR_TEST);
2971 glDisable(GL_STENCIL_TEST);
2972 glDisable(GL_DEPTH_TEST);
2973}
2974
2975void glChartCanvas::Invalidate() {
2976 /* should probably use a different flag for this */
2977 m_cache_vp.Invalidate();
2978}
2979
2980void glChartCanvas::RenderRasterChartRegionGL(ChartBase *chart, ViewPort &vp,
2981 LLRegion &region) {
2982 ChartBaseBSB *pBSBChart = dynamic_cast<ChartBaseBSB *>(chart);
2983 if (!pBSBChart) return;
2984
2986 return; // don't want multiple texfactories to exist
2987
2988 // Look for the texture factory for this chart
2989 wxString key = chart->GetHashKey();
2990
2991 glTexFactory *pTexFact;
2992 ChartPathHashTexfactType &hash = g_glTextureManager->m_chart_texfactory_hash;
2993 ChartPathHashTexfactType::iterator ittf = hash.find(key);
2994
2995 // Not Found ?
2996 if (ittf == hash.end()) {
2997 hash[key] = new glTexFactory(chart, g_raster_format);
2998 hash[key]->SetHashKey(key);
2999 }
3000
3001 pTexFact = hash[key];
3002 pTexFact->SetLRUTime(++m_LRUtime);
3003
3004 // for small scales, don't use normalized coordinates for accuracy (difference
3005 // is up to 3 meters error)
3006 bool use_norm_vp =
3007 glChartCanvas::HasNormalizedViewPort(vp) && pBSBChart->GetPPM() < 1;
3008 pTexFact->PrepareTiles(vp, use_norm_vp, pBSBChart);
3009
3010 // For underzoom cases, we will define the textures as having their base
3011 // levels equivalent to a level "n" mipmap, where n is calculated, and is
3012 // always binary This way we can avoid loading much texture memory
3013
3014 int base_level;
3015 if (vp.m_projection_type == PROJECTION_MERCATOR &&
3016 chart->GetChartProjectionType() == PROJECTION_MERCATOR) {
3017 double scalefactor = pBSBChart->GetRasterScaleFactor(vp);
3018 base_level = log(scalefactor) / log(2.0);
3019
3020 if (base_level < 0) /* for overzoom */
3021 base_level = 0;
3022 if (base_level > g_mipmap_max_level) base_level = g_mipmap_max_level;
3023 } else
3024 base_level = 0; // base level should be computed per tile, for now load all
3025
3026 /* setup opengl parameters */
3027 glEnable(GL_TEXTURE_2D);
3028#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3029 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3030
3031 glEnableClientState(GL_VERTEX_ARRAY);
3032 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3033
3034 if (use_norm_vp) {
3035 glPushMatrix();
3036 double lat, lon;
3037 pTexFact->GetCenter(lat, lon);
3038 MultMatrixViewPort(vp, lat, lon);
3039 }
3040#endif
3041
3042 LLBBox box = region.GetBox();
3043 int numtiles;
3044 int mem_used = 0;
3045 if (g_memCacheLimit > 0) {
3046 // GetMemoryStatus is slow on linux
3047 platform::GetMemoryStatus(0, &mem_used);
3048 }
3049
3050 glTexTile **tiles = pTexFact->GetTiles(numtiles);
3051 for (int i = 0; i < numtiles; i++) {
3052 glTexTile *tile = tiles[i];
3053 if (region.IntersectOut(tile->box)) {
3054 /* user setting is in MB while we count exact bytes */
3055 bool bGLMemCrunch =
3056 g_tex_mem_used > g_GLOptions.m_iTextureMemorySize * 1024 * 1024;
3057 if (bGLMemCrunch) pTexFact->DeleteTexture(tile->rect);
3058 } else {
3059 bool texture = pTexFact->PrepareTexture(base_level, tile->rect,
3060 global_color_scheme, mem_used);
3061
3062 float *coords;
3063 if (use_norm_vp)
3064 coords = tile->m_coords;
3065 else {
3066 coords = new float[2 * tile->m_ncoords];
3067 for (int i = 0; i < tile->m_ncoords; i++) {
3068 wxPoint2DDouble p = vp.GetDoublePixFromLL(tile->m_coords[2 * i + 0],
3069 tile->m_coords[2 * i + 1]);
3070 coords[2 * i + 0] = p.m_x;
3071 coords[2 * i + 1] = p.m_y;
3072 }
3073 }
3074
3075#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
3076 RenderTextures(m_gldc, coords, tile->m_texcoords, 4,
3077 m_pParentCanvas->GetpVP());
3078#else
3079 if (!texture) { // failed to load, draw red
3080 glDisable(GL_TEXTURE_2D);
3081 glColor3f(1, 0, 0);
3082 }
3083
3084 glTexCoordPointer(2, GL_FLOAT, 2 * sizeof(GLfloat), tile->m_texcoords);
3085 glVertexPointer(2, GL_FLOAT, 2 * sizeof(GLfloat), coords);
3086 glDrawArrays(GL_QUADS, 0, tile->m_ncoords);
3087#endif
3088 if (!texture) glEnable(GL_TEXTURE_2D);
3089
3090 if (!use_norm_vp) delete[] coords;
3091 }
3092 }
3093
3094 glDisable(GL_TEXTURE_2D);
3095
3096#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3097 if (use_norm_vp) glPopMatrix();
3098
3099 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3100 glDisableClientState(GL_VERTEX_ARRAY);
3101#endif
3102}
3103
3104void glChartCanvas::RenderQuiltViewGL(ViewPort &vp,
3105 const OCPNRegion &rect_region) {
3106 if (!m_pParentCanvas->m_pQuilt->GetnCharts() ||
3107 m_pParentCanvas->m_pQuilt->IsBusy())
3108 return;
3109
3110 // render the quilt
3111 ChartBase *chart = m_pParentCanvas->m_pQuilt->GetFirstChart();
3112 if (!chart) {
3113 printf(" Chart NULL\n");
3114 chart = m_pParentCanvas->m_pQuilt->GetFirstChart();
3115 }
3116
3117 // Check the first, smallest scale chart
3118 if (chart) {
3119 // if( ! m_pParentCanvas->IsChartLargeEnoughToRender( chart, vp )
3120 // )
3121 // chart = NULL;
3122 }
3123
3124 LLRegion region = vp.GetLLRegion(rect_region);
3125
3126 LLRegion rendered_region;
3127 while (chart) {
3128 // This test does not need to be done for raster charts, since
3129 // we can assume that texture binding is acceptably fast regardless of the
3130 // render region, and that the quilt zoom methods choose a reasonable
3131 // reference chart.
3132 if (chart->GetChartFamily() != CHART_FAMILY_RASTER) {
3133 // if( ! m_pParentCanvas->IsChartLargeEnoughToRender(
3134 // chart, vp ) ) {
3135 // chart = m_pParentCanvas->m_pQuilt->GetNextChart();
3136 // continue;
3137 // }
3138 }
3139
3140 QuiltPatch *pqp = m_pParentCanvas->m_pQuilt->GetCurrentPatch();
3141 if (pqp->b_Valid) {
3142 LLRegion get_region = pqp->ActiveRegion;
3143 bool b_rendered = false;
3144
3145 if (!pqp->b_overlay) {
3146 get_region.Intersect(region);
3147 if (!get_region.Empty()) {
3148 if (chart->GetChartFamily() == CHART_FAMILY_RASTER) {
3149 ChartBaseBSB *Patch_Ch_BSB = dynamic_cast<ChartBaseBSB *>(chart);
3150 if (Patch_Ch_BSB) {
3151 SetClipRegion(vp, get_region /*pqp->quilt_region*/);
3152 RenderRasterChartRegionGL(chart, vp, pqp->ActiveRegion);
3153 DisableClipRegion();
3154
3155 b_rendered = true;
3156 } else if (chart->GetChartType() == CHART_TYPE_MBTILES) {
3157 SetClipRegion(vp, pqp->ActiveRegion /*pqp->quilt_region*/);
3158 chart->RenderRegionViewOnGL(*m_pcontext, vp, rect_region,
3159 get_region);
3160 DisableClipRegion();
3161 }
3162
3163 } else if (chart->GetChartFamily() == CHART_FAMILY_VECTOR) {
3164 if (chart->GetChartType() == CHART_TYPE_CM93COMP) {
3165 RenderNoDTA(vp, get_region);
3166 chart->RenderRegionViewOnGL(*m_pcontext, vp, rect_region,
3167 get_region);
3168 } else {
3169 s57chart *Chs57 = dynamic_cast<s57chart *>(chart);
3170 if (Chs57) {
3171 if (Chs57->m_RAZBuilt) {
3172 RenderNoDTA(vp, get_region);
3173 Chs57->RenderRegionViewOnGLNoText(*m_pcontext, vp,
3174 rect_region, get_region);
3175 DisableClipRegion();
3176 } else {
3177 // The SENC is quesed for building, so..
3178 // Show GSHHS with compatible color scheme in the meantime.
3179 ocpnDC gldc(*this);
3180 const LLRegion &oregion = get_region;
3181 LLBBox box = oregion.GetBox();
3182
3183 wxPoint p1 =
3184 vp.GetPixFromLL(box.GetMaxLat(), box.GetMinLon());
3185 wxPoint p2 =
3186 vp.GetPixFromLL(box.GetMaxLat(), box.GetMaxLon());
3187 wxPoint p3 =
3188 vp.GetPixFromLL(box.GetMinLat(), box.GetMaxLon());
3189 wxPoint p4 =
3190 vp.GetPixFromLL(box.GetMinLat(), box.GetMinLon());
3191
3192 wxRect srect(p1.x, p1.y, p3.x - p1.x, p4.y - p2.y);
3193
3194 bool world = false;
3195 ViewPort cvp = ClippedViewport(vp, get_region);
3196 if (m_pParentCanvas->GetWorldBackgroundChart()) {
3197 SetClipRegion(cvp, get_region);
3198 m_pParentCanvas->GetWorldBackgroundChart()->SetColorsDirect(
3199 GetGlobalColor("LANDA"), GetGlobalColor("DEPMS"));
3200 RenderWorldChart(gldc, cvp, srect, world);
3201 m_pParentCanvas->GetWorldBackgroundChart()->SetColorScheme(
3202 global_color_scheme);
3203 DisableClipRegion();
3204 }
3205 }
3206 } else {
3207 ChartPlugInWrapper *ChPI =
3208 dynamic_cast<ChartPlugInWrapper *>(chart);
3209 if (ChPI) {
3210 SetClipRegion(vp, get_region);
3211 RenderNoDTA(vp, get_region);
3212 ChPI->RenderRegionViewOnGLNoText(*m_pcontext, vp, rect_region,
3213 get_region);
3214 DisableClipRegion();
3215
3216 } else {
3217 SetClipRegion(vp, get_region);
3218 RenderNoDTA(vp, get_region);
3219 chart->RenderRegionViewOnGL(*m_pcontext, vp, rect_region,
3220 get_region);
3221 DisableClipRegion();
3222 }
3223 }
3224 }
3225 }
3226 }
3227 }
3228
3229 if (b_rendered) {
3230 // LLRegion get_region = pqp->ActiveRegion;
3231 // get_region.Intersect( Region ); not technically
3232 // required?
3233 // rendered_region.Union(get_region);
3234 }
3235 }
3236
3237 chart = m_pParentCanvas->m_pQuilt->GetNextChart();
3238 }
3239
3240 // Render any Overlay patches for s57 charts(cells)
3241 if (m_pParentCanvas->m_pQuilt->HasOverlays()) {
3242 ChartBase *pch = m_pParentCanvas->m_pQuilt->GetFirstChart();
3243 while (pch) {
3244 QuiltPatch *pqp = m_pParentCanvas->m_pQuilt->GetCurrentPatch();
3245 if (pqp->b_Valid && pqp->b_overlay &&
3246 pch->GetChartFamily() == CHART_FAMILY_VECTOR) {
3247 LLRegion get_region = pqp->ActiveRegion;
3248
3249 get_region.Intersect(region);
3250 if (!get_region.Empty()) {
3251 s57chart *Chs57 = dynamic_cast<s57chart *>(pch);
3252 if (Chs57)
3253 Chs57->RenderOverlayRegionViewOnGL(*m_pcontext, vp, rect_region,
3254 get_region);
3255 else {
3256 ChartPlugInWrapper *ChPI = dynamic_cast<ChartPlugInWrapper *>(pch);
3257 if (ChPI) {
3258 ChPI->RenderRegionViewOnGL(*m_pcontext, vp, rect_region,
3259 get_region);
3260 }
3261 }
3262 }
3263 }
3264
3265 pch = m_pParentCanvas->m_pQuilt->GetNextChart();
3266 }
3267 }
3268
3269 // Hilite rollover of standard chart key
3270 ViewPort vph = m_pParentCanvas->GetVP();
3271 for (auto &index : m_pParentCanvas->m_pQuilt->GetHiLiteIndexArray()) {
3272 const ChartTableEntry &cte = ChartData->GetChartTableEntry(index);
3273 LLRegion hiregion =
3274 m_pParentCanvas->m_pQuilt->GetChartQuiltRegion(cte, vph);
3275
3276 if (!hiregion.Empty()) {
3277 glEnable(GL_BLEND);
3278
3279 double hitrans;
3280 switch (global_color_scheme) {
3281 case GLOBAL_COLOR_SCHEME_DAY:
3282 hitrans = .4;
3283 break;
3284 case GLOBAL_COLOR_SCHEME_DUSK:
3285 hitrans = .2;
3286 break;
3287 case GLOBAL_COLOR_SCHEME_NIGHT:
3288 hitrans = .1;
3289 break;
3290 default:
3291 hitrans = .4;
3292 break;
3293 }
3294
3295#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3296
3297 glColor4f((float).8, (float).4, (float).4, (float)hitrans);
3298#else
3299 s_regionColor = wxColor(204, 102, 102, hitrans * 256);
3300#endif
3301
3302 DrawRegion(vp, hiregion);
3303
3304 glDisable(GL_BLEND);
3305 }
3306 }
3307
3308#if 0
3309 LLRegion hiregion = m_pParentCanvas->m_pQuilt->GetHiliteRegion();
3310
3311 if (!hiregion.Empty()) {
3312 glEnable(GL_BLEND);
3313
3314 double hitrans;
3315 switch (global_color_scheme) {
3316 case GLOBAL_COLOR_SCHEME_DAY:
3317 hitrans = .4;
3318 break;
3319 case GLOBAL_COLOR_SCHEME_DUSK:
3320 hitrans = .2;
3321 break;
3322 case GLOBAL_COLOR_SCHEME_NIGHT:
3323 hitrans = .1;
3324 break;
3325 default:
3326 hitrans = .4;
3327 break;
3328 }
3329
3330//#ifndef USE_ANDROID_GLES2
3331#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3332
3333 glColor4f((float).8, (float).4, (float).4, (float)hitrans);
3334#else
3335 s_regionColor = wxColor(204, 102, 102, hitrans * 256);
3336#endif
3337
3338 DrawRegion(vp, hiregion);
3339
3340 glDisable(GL_BLEND);
3341 }
3342#endif
3343
3344 m_pParentCanvas->m_pQuilt->SetRenderedVP(vp);
3345}
3346
3347void glChartCanvas::RenderQuiltViewGLText(ViewPort &vp,
3348 const OCPNRegion &rect_region) {
3349 if (!m_pParentCanvas->m_pQuilt->GetnCharts() ||
3350 m_pParentCanvas->m_pQuilt->IsBusy())
3351 return;
3352
3353 // render the quilt
3354 ChartBase *chart = m_pParentCanvas->m_pQuilt->GetLargestScaleChart();
3355
3356 LLRegion region = vp.GetLLRegion(rect_region);
3357
3358 LLRegion rendered_region;
3359 while (chart) {
3360 QuiltPatch *pqp = m_pParentCanvas->m_pQuilt->GetCurrentPatch();
3361 if (pqp->b_Valid) {
3362 LLRegion get_region = pqp->ActiveRegion;
3363
3364 if (!pqp->b_overlay) {
3365 if (chart->GetChartFamily() == CHART_FAMILY_VECTOR) {
3366 s57chart *Chs57 = dynamic_cast<s57chart *>(chart);
3367 if (Chs57) {
3368 Chs57->RenderViewOnGLTextOnly(*m_pcontext, vp);
3369 } else {
3370 ChartPlugInWrapper *ChPI =
3371 dynamic_cast<ChartPlugInWrapper *>(chart);
3372 if (ChPI) {
3373 ChPI->RenderRegionViewOnGLTextOnly(*m_pcontext, vp, rect_region);
3374 }
3375 }
3376 }
3377 }
3378 }
3379
3380 chart = m_pParentCanvas->m_pQuilt->GetNextSmallerScaleChart();
3381 }
3382
3383 /*
3384 // Render any Overlay patches for s57 charts(cells)
3385 if( m_pParentCanvas->m_pQuilt->HasOverlays() ) {
3386 ChartBase *pch = m_pParentCanvas->m_pQuilt->GetFirstChart();
3387 while( pch ) {
3388 QuiltPatch *pqp =
3389 m_pParentCanvas->m_pQuilt->GetCurrentPatch(); if( pqp->b_Valid &&
3390 pqp->b_overlay && pch->GetChartFamily() == CHART_FAMILY_VECTOR ) { LLRegion
3391 get_region = pqp->ActiveRegion;
3392
3393 get_region.Intersect( region );
3394 if( !get_region.Empty() ) {
3395 s57chart *Chs57 = dynamic_cast<s57chart*>( pch );
3396 if( Chs57 )
3397 Chs57->RenderOverlayRegionViewOnGL( *m_pcontext,
3398 vp, rect_region, get_region );
3399 }
3400 }
3401
3402 pch = m_pParentCanvas->m_pQuilt->GetNextChart();
3403 }
3404 }
3405 */
3406}
3407
3408void glChartCanvas::RenderCharts(ocpnDC &dc, const OCPNRegion &rect_region) {
3409 ViewPort &vp = m_pParentCanvas->VPoint;
3410
3411 // Only for cm93 (not quilted), SetVPParms can change the valid region of the
3412 // chart we need to know this before rendering the chart so we can compute the
3413 // background region and nodta regions correctly. I would prefer to just
3414 // perform this here (or in SetViewPoint) for all vector charts instead of in
3415 // their render routine, but how to handle quilted cases?
3416 if (!vp.b_quilt &&
3417 m_pParentCanvas->m_singleChart->GetChartType() == CHART_TYPE_CM93COMP)
3418 static_cast<cm93compchart *>(m_pParentCanvas->m_singleChart)
3419 ->SetVPParms(vp);
3420
3421 LLRegion chart_region;
3422 if (!vp.b_quilt &&
3423 (m_pParentCanvas->m_singleChart->GetChartType() == CHART_TYPE_PLUGIN)) {
3424 if (m_pParentCanvas->m_singleChart->GetChartFamily() ==
3425 CHART_FAMILY_RASTER) {
3426 // We do this the hard way, since PlugIn Raster charts do not understand
3427 // LLRegion yet...
3428 double ll[8];
3429 ChartPlugInWrapper *cpw =
3430 dynamic_cast<ChartPlugInWrapper *>(m_pParentCanvas->m_singleChart);
3431 if (!cpw) return;
3432
3433 cpw->chartpix_to_latlong(0, 0, ll + 0, ll + 1);
3434 cpw->chartpix_to_latlong(0, cpw->GetSize_Y(), ll + 2, ll + 3);
3435 cpw->chartpix_to_latlong(cpw->GetSize_X(), cpw->GetSize_Y(), ll + 4,
3436 ll + 5);
3437 cpw->chartpix_to_latlong(cpw->GetSize_X(), 0, ll + 6, ll + 7);
3438
3439 // for now don't allow raster charts to cross both 0 meridian and IDL
3440 // (complicated to deal with)
3441 for (int i = 1; i < 6; i += 2)
3442 if (fabs(ll[i] - ll[i + 2]) > 180) {
3443 // we detect crossing idl here, make all longitudes positive
3444 for (int i = 1; i < 8; i += 2)
3445 if (ll[i] < 0) ll[i] += 360;
3446 break;
3447 }
3448
3449 chart_region = LLRegion(4, ll);
3450 } else {
3451 Extent ext;
3452 m_pParentCanvas->m_singleChart->GetChartExtent(&ext);
3453
3454 double ll[8] = {ext.SLAT, ext.WLON, ext.SLAT, ext.ELON,
3455 ext.NLAT, ext.ELON, ext.NLAT, ext.WLON};
3456 chart_region = LLRegion(4, ll);
3457 }
3458 } else
3459 chart_region = vp.b_quilt
3460 ? m_pParentCanvas->m_pQuilt->GetFullQuiltRegion()
3461 : m_pParentCanvas->m_singleChart->GetValidRegion();
3462
3463 bool world_view = false;
3464 for (OCPNRegionIterator upd(rect_region); upd.HaveRects(); upd.NextRect()) {
3465 wxRect rect = upd.GetRect();
3466 LLRegion background_region = vp.GetLLRegion(rect);
3467 // Remove the valid chart area to find the region NOT covered by the
3468 // charts
3469 background_region.Subtract(chart_region);
3470
3471 if (!background_region.Empty()) {
3472 ViewPort cvp = ClippedViewport(vp, background_region);
3473 SetClipRect(cvp, rect, false);
3474 RenderWorldChart(dc, cvp, rect, world_view);
3475 DisableClipRegion();
3476 }
3477 }
3478
3479 if (vp.b_quilt) {
3480 RenderQuiltViewGL(vp, rect_region);
3481 int yyp = 4;
3482 } else {
3483 LLRegion region = vp.GetLLRegion(rect_region);
3484 if (m_pParentCanvas->m_singleChart->GetChartFamily() ==
3485 CHART_FAMILY_RASTER) {
3486 if (m_pParentCanvas->m_singleChart->GetChartType() == CHART_TYPE_MBTILES)
3487 m_pParentCanvas->m_singleChart->RenderRegionViewOnGL(
3488 *m_pcontext, vp, rect_region, region);
3489 else
3490 RenderRasterChartRegionGL(m_pParentCanvas->m_singleChart, vp, region);
3491 } else if (m_pParentCanvas->m_singleChart->GetChartFamily() ==
3492 CHART_FAMILY_VECTOR) {
3493 chart_region.Intersect(region);
3494 RenderNoDTA(vp, chart_region);
3495 m_pParentCanvas->m_singleChart->RenderRegionViewOnGL(*m_pcontext, vp,
3496 rect_region, region);
3497 }
3498 }
3499 glUseProgram(0);
3500}
3501
3502void glChartCanvas::RenderNoDTA(ViewPort &vp, const LLRegion &region,
3503 int transparency) {
3504 wxColour color = GetGlobalColor("NODTA");
3505#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3506 if (color.IsOk())
3507 glColor4ub(color.Red(), color.Green(), color.Blue(), transparency);
3508 else
3509 glColor4ub(163, 180, 183, transparency);
3510
3511 glEnable(GL_BLEND);
3512 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3513
3514#else
3515 // Store the color for tesselator callback pickup.
3516 s_regionColor = color;
3517#endif
3518
3519 DrawRegion(vp, region);
3520}
3521
3522/* render world chart, but only in this rectangle */
3523void glChartCanvas::RenderWorldChart(ocpnDC &dc, ViewPort &vp, wxRect &rect,
3524 bool &world_view) {
3525 // set gl color to water
3526 wxColour water = m_pParentCanvas->pWorldBackgroundChart->water;
3527
3528 glEnable(GL_SCISSOR_TEST);
3529 glScissor(rect.x, vp.pix_height - rect.height - rect.y, rect.width,
3530 rect.height);
3531
3532 // clear background
3533 if (!world_view) {
3534 if (!world_view) {
3535 int x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height;
3536#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
3537
3538 GLShaderProgram *shader = pcolor_tri_shader_program[GetCanvasIndex()];
3539 shader->Bind();
3540
3541 float colorv[4];
3542 colorv[0] = water.Red() / float(256);
3543 colorv[1] = water.Green() / float(256);
3544 colorv[2] = water.Blue() / float(256);
3545 colorv[3] = 1.0;
3546 shader->SetUniform4fv("color", colorv);
3547
3548 float pf[8];
3549 pf[0] = x2;
3550 pf[1] = y1;
3551 pf[2] = x2;
3552 pf[3] = y2;
3553 pf[4] = x1;
3554 pf[5] = y1;
3555 pf[6] = x1;
3556 pf[7] = y2;
3557 shader->SetAttributePointerf("position", pf);
3558
3559 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
3560
3561 shader->UnBind();
3562
3563#else
3564#endif
3565 }
3566 }
3567
3568 // m_pParentCanvas->pWorldBackgroundChart->RenderViewOnDC(dc, vp);
3569 gShapeBasemap.RenderViewOnDC(dc, vp);
3570
3571 glDisable(GL_SCISSOR_TEST);
3572}
3573
3574/* these are the overlay objects which move with the charts and
3575 are not frequently updated (not ships etc..)
3576
3577 many overlay objects are fixed to a geographical location or
3578 grounded as opposed to the floating overlay objects. */
3579void glChartCanvas::DrawGroundedOverlayObjects(ocpnDC &dc, ViewPort &vp) {
3580 m_pParentCanvas->RenderAllChartOutlines(dc, vp);
3581
3582 DrawStaticRoutesTracksAndWaypoints(vp);
3583
3584 DisableClipRegion();
3585}
3586
3587void glChartCanvas::DrawGLTidesInBBox(ocpnDC &dc, LLBBox &BBox) {
3588 // At small scale, we render the Tide icon as a texture for best performance
3589 if (m_pParentCanvas->GetVP().chart_scale > 500000) {
3590 // Prepare the texture if necessary
3591
3592 if (!m_tideTex) {
3593 wxBitmap bmp = m_pParentCanvas->GetTideBitmap();
3594 if (!bmp.Ok()) return;
3595
3596 wxImage image = bmp.ConvertToImage();
3597 int w = image.GetWidth(), h = image.GetHeight();
3598
3599 int tex_w, tex_h;
3600 if (g_texture_rectangle_format == GL_TEXTURE_2D)
3601 tex_w = w, tex_h = h;
3602 else
3603 tex_w = NextPow2(w), tex_h = NextPow2(h);
3604
3605 m_tideTexWidth = tex_w;
3606 m_tideTexHeight = tex_h;
3607
3608 unsigned char *d = image.GetData();
3609 unsigned char *a = image.GetAlpha();
3610
3611 unsigned char mr, mg, mb;
3612 if (!a) image.GetOrFindMaskColour(&mr, &mg, &mb);
3613
3614 unsigned char *e = new unsigned char[4 * w * h];
3615 if (e && d) {
3616 for (int y = 0; y < h; y++)
3617 for (int x = 0; x < w; x++) {
3618 unsigned char r, g, b;
3619 int off = (y * w + x);
3620 r = d[off * 3 + 0];
3621 g = d[off * 3 + 1];
3622 b = d[off * 3 + 2];
3623
3624 e[off * 4 + 0] = r;
3625 e[off * 4 + 1] = g;
3626 e[off * 4 + 2] = b;
3627
3628 e[off * 4 + 3] =
3629 a ? a[off] : ((r == mr) && (g == mg) && (b == mb) ? 0 : 255);
3630 }
3631 }
3632
3633 glGenTextures(1, &m_tideTex);
3634
3635 glBindTexture(GL_TEXTURE_2D, m_tideTex);
3636 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3637 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3638
3639 if (g_texture_rectangle_format == GL_TEXTURE_2D)
3640 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
3641 GL_UNSIGNED_BYTE, e);
3642 else {
3643 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_w, tex_h, 0, GL_RGBA,
3644 GL_UNSIGNED_BYTE, 0);
3645 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
3646 e);
3647 }
3648
3649 delete[] e;
3650 }
3651
3652 // Texture is ready
3653
3654 glBindTexture(GL_TEXTURE_2D, m_tideTex);
3655 glEnable(GL_TEXTURE_2D);
3656 glEnable(GL_BLEND);
3657
3658#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
3659#else
3660 for (int i = 1; i < ptcmgr->Get_max_IDX() + 1; i++) {
3661 const IDX_entry *pIDX = ptcmgr->GetIDX_entry(i);
3662
3663 char type = pIDX->IDX_type; // Entry "TCtcIUu" identifier
3664 if ((type == 't') || (type == 'T')) // only Tides
3665 {
3666 double lon = pIDX->IDX_lon;
3667 double lat = pIDX->IDX_lat;
3668
3669 if (BBox.Contains(lat, lon)) {
3670 wxPoint r;
3671 m_pParentCanvas->GetCanvasPointPix(lat, lon, &r);
3672
3673 float xp = r.x;
3674 float yp = r.y;
3675
3676 double scale = 1.0;
3677#ifdef __ANDROID__
3678 scale *= getAndroidDisplayDensity();
3679#endif
3680 double width2 = scale * m_tideTexWidth / 2;
3681 double height2 = scale * m_tideTexHeight / 2;
3682
3683 float coords[8];
3684 float uv[8];
3685
3686 // normal uv
3687 uv[0] = 0;
3688 uv[1] = 0;
3689 uv[2] = 0;
3690 uv[3] = 1;
3691 uv[4] = 1;
3692 uv[5] = 1;
3693 uv[6] = 1;
3694 uv[7] = 0;
3695
3696 coords[0] = xp - width2;
3697 coords[1] = yp - height2;
3698 coords[2] = xp - width2;
3699 coords[3] = yp + height2;
3700 coords[4] = xp + width2;
3701 coords[5] = yp + height2;
3702 coords[6] = xp + width2;
3703 coords[7] = yp - height2;
3704
3705 RenderTextures(dc, coords, uv, 4, m_pParentCanvas->GetpVP());
3706 }
3707 } // type 'T"
3708 } // loop
3709
3710#endif
3711
3712 glDisable(GL_TEXTURE_2D);
3713 glDisable(GL_BLEND);
3714 glBindTexture(GL_TEXTURE_2D, 0);
3715 } else
3716 m_pParentCanvas->DrawAllTidesInBBox(dc, BBox);
3717}
3718
3719void glChartCanvas::DrawGLCurrentsInBBox(ocpnDC &dc, LLBBox &BBox) {
3720 m_pParentCanvas->DrawAllCurrentsInBBox(dc, BBox);
3721}
3722
3723void glChartCanvas::SetColorScheme(ColorScheme cs) {
3724 if (!m_bsetup) return;
3725
3726 glDeleteTextures(1, &m_tideTex);
3727 glDeleteTextures(1, &m_currentTex);
3728 m_tideTex = 0;
3729 m_currentTex = 0;
3730 ownship_color = -1;
3731}
3732
3733void glChartCanvas::RenderGLAlertMessage() {
3734 if (!m_pParentCanvas->GetAlertString().IsEmpty()) {
3735 wxString msg = m_pParentCanvas->GetAlertString();
3736
3737 wxFont *pfont = GetOCPNScaledFont(_("Dialog"));
3738 m_gldc.SetFont(*pfont);
3739
3740 int w, h;
3741 wxScreenDC sdc;
3742 sdc.GetTextExtent(msg, &w, &h, NULL, NULL, pfont);
3743
3744 h += 2;
3745 w += 4;
3746 int yp =
3747 m_pParentCanvas->VPoint.pix_height - GetChartbarHeight() - h - (h / 4);
3748
3749 wxRect sbr = m_pParentCanvas->GetScaleBarRect();
3750 int xp = sbr.x + sbr.width + 5;
3751
3752 wxPen ppPen1(GetGlobalColor("UBLCK"), 1, wxPENSTYLE_SOLID);
3753 m_gldc.SetPen(ppPen1);
3754 m_gldc.SetBrush(wxBrush(GetGlobalColor("YELO1")));
3755
3756 m_gldc.DrawRectangle(xp, yp, w, h);
3757
3758 m_gldc.DrawText(msg, xp, yp);
3759 }
3760}
3761
3762unsigned long quiltHash;
3763int refChartIndex;
3764extern wxLongLong s_t0;
3765
3766int n_render;
3767void glChartCanvas::Render() {
3768 if (!m_bsetup || !m_pParentCanvas->m_pQuilt ||
3769 (m_pParentCanvas->VPoint.b_quilt && !m_pParentCanvas->m_pQuilt) ||
3770 (!m_pParentCanvas->VPoint.b_quilt && !m_pParentCanvas->m_singleChart)) {
3771#ifdef __WXGTK__ // for some reason in gtk, a swap is needed here to get an
3772 // initial screen update
3773 SwapBuffers();
3774#endif
3775 if (!g_PrintingInProgress) return;
3776 }
3777
3778 if (!g_true_zoom && m_binPinch) return;
3779
3780 // if (m_binPinch) printf(" %ld Render Start\n", m_glstopwatch.Time());
3781 long render_start_time = m_glstopwatch.Time();
3782
3783#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
3784 loadShaders(GetCanvasIndex());
3785 configureShaders(m_pParentCanvas->VPoint);
3786#endif
3787
3788#ifdef USE_ANDROID_GLES2
3789
3790 OCPNStopWatch sw;
3791
3792 if (m_binPinch) return;
3793
3794 // qDebug() << "Render" << m_pParentCanvas->m_canvasIndex << GetPosition().x
3795 // << GetSize().x << m_pParentCanvas->GetPosition().x << m_pcontext;
3796
3797 // if(m_pParentCanvas->m_canvasIndex == 0) return;
3798
3799 // Do any setup required...
3800
3801 bool recompose = false;
3802 if (m_pParentCanvas->VPoint.b_quilt && m_pParentCanvas->m_pQuilt &&
3803 !m_pParentCanvas->m_pQuilt->IsComposed()) {
3804 if (m_pParentCanvas->VPoint.IsValid()) {
3805 m_pParentCanvas->m_pQuilt->Compose(m_pParentCanvas->VPoint);
3806 m_pParentCanvas->UpdateCanvasControlBar();
3807 recompose = true;
3808 } else
3809 return;
3810 }
3811
3812 // Check to see if the Compose() call forced a SENC build.
3813 // If so, zoom the canvas just slightly to force a deferred redraw of the
3814 // full screen.
3815 if (sw.GetTime() > 2000) { // long enough to detect SENC build.
3816 m_pParentCanvas->ZoomCanvas(1.0001, false);
3817 }
3818
3819 // qDebug() << "RenderTime1" << sw.GetTime();
3820
3821 quiltHash = m_pParentCanvas->m_pQuilt->GetXStackHash();
3822 refChartIndex = m_pParentCanvas->m_pQuilt->GetRefChartdbIndex();
3823
3824#endif
3825
3826#ifdef __WXOSX__
3827 // Support scaled HDPI displays.
3828 m_displayScale = GetContentScaleFactor();
3829#endif
3830 m_pParentCanvas->VPoint.SetPixelScale(m_displayScale);
3831
3832 m_last_render_time = wxDateTime::Now().GetTicks();
3833
3834 // we don't care about jobs that are now off screen
3835 // clear out and it will be repopulated during render
3836 if (g_GLOptions.m_bTextureCompression &&
3837 !g_GLOptions.m_bTextureCompressionCaching)
3838 g_glTextureManager->ClearJobList();
3839
3840 ocpnDC gldc(*this);
3841
3842 int gl_width, gl_height;
3843 gl_width = m_pParentCanvas->VPoint.pix_width;
3844 gl_height = m_pParentCanvas->VPoint.pix_height;
3845
3846 // Take a copy for use later by DC
3847 m_glcanvas_width = gl_width;
3848 m_glcanvas_height = gl_height;
3849
3850 // @todo: If the intention was to work with the same ViewPort object, use a
3851 // reference instead. Making a copy of VPoint here means that any changes to
3852 // VPoint will not affect m_pParentCanvas->VPoint. It's not clear if this is
3853 // the intended behavior.
3854 ViewPort VPoint = m_pParentCanvas->VPoint;
3855
3856 OCPNRegion screen_region(wxRect(0, 0, gl_width, gl_height));
3857 glViewport(0, 0, (GLint)gl_width, (GLint)gl_height);
3858
3859// #ifndef USE_ANDROID_GLES2
3860#if !defined(USE_ANDROID_GLES2)
3861 glMatrixMode(GL_PROJECTION);
3862 glLoadIdentity();
3863
3864 glOrtho(0, (GLint)gl_width, (GLint)gl_height, 0, -1, 1);
3865 glMatrixMode(GL_MODELVIEW);
3866 glLoadIdentity();
3867#endif
3868
3869 if (s_b_useStencil) {
3870 glEnable(GL_STENCIL_TEST);
3871 glStencilMask(0xff);
3872 glClear(GL_STENCIL_BUFFER_BIT);
3873 glDisable(GL_STENCIL_TEST);
3874 }
3875
3876 // set opengl settings that don't normally change
3877 // this should be able to go in SetupOpenGL, but it's
3878 // safer here incase a plugin mangles these
3879 if (g_GLOptions.m_GLLineSmoothing) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
3880 if (g_GLOptions.m_GLPolygonSmoothing)
3881 glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
3882 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3883
3884 // Delete any textures known to the GPU that
3885 // belong to charts which will not be used in this render
3886 // This is done chart-by-chart...later we will scrub for unused textures
3887 // that belong to charts which ARE used in this render, if we need to....
3888
3889 g_glTextureManager->TextureCrunch(0.8);
3890
3891 // If we plan to post process the display, don't use accelerated panning
3892 double scale_factor = VPoint.ref_scale / VPoint.chart_scale;
3893
3894 bool bpost_hilite = !m_pParentCanvas->m_pQuilt->GetHiliteRegion().Empty();
3895 bool useFBO = false;
3896 int sx = gl_width;
3897 int sy = gl_height;
3898
3899 // Try to use the framebuffer object's cache of the last frame
3900 // to accelerate drawing this frame (if overlapping)
3901 if (m_b_BuiltFBO && !bpost_hilite
3902 //&& VPoint.tilt == 0 // disabling fbo in tilt mode gives better quality
3903 // but slower
3904 ) {
3905 // Is this viewpoint the same as the previously painted one?
3906 bool b_newview = true;
3907 bool b_full = false;
3908
3909 // If the view is the same we do no updates,
3910 // Just render cached texture to the framebuffer
3911 if (m_cache_vp.view_scale_ppm == VPoint.view_scale_ppm &&
3912 m_cache_vp.rotation == VPoint.rotation &&
3913 m_cache_vp.clat == VPoint.clat && m_cache_vp.clon == VPoint.clon &&
3914 m_cache_vp.IsValid() && m_cache_vp.pix_height == VPoint.pix_height &&
3915 m_cache_current_ch == m_pParentCanvas->m_singleChart) {
3916 b_newview = false;
3917 }
3918
3919#ifdef USE_ANDROID_GLES2
3920 if (recompose) b_newview = true;
3921
3922 if (m_bforcefull) {
3923 b_newview = true;
3924 b_full = true;
3925 }
3926
3927 // If no charts are to be rendered, we need to refresh the entire display
3928 // This fixes a problem with routes/tracks/marks rendering on pans at very
3929 // small scale. It is a workaround, so finding root cause should be
3930 // considered a TODO
3931
3932 if (VPoint.b_quilt) {
3933 ChartBase *chart = m_pParentCanvas->m_pQuilt->GetFirstChart();
3934 if (!chart) b_full = true;
3935 }
3936
3937#endif
3938
3939 if (b_newview) {
3940 float dx = 0;
3941 float dy = 0;
3942
3943 bool accelerated_pan = false;
3944 // if (g_in_inertia)
3945 // printf("--- accpan condition %d %d\n",
3946 // g_GLOptions.m_bUseAcceleratedPanning,
3947 // m_cache_vp.IsValid());
3948 // else
3949 // printf("||| accpan condition %d %d\n",
3950 // g_GLOptions.m_bUseAcceleratedPanning,
3951 // m_cache_vp.IsValid());
3952
3953 if (g_GLOptions.m_bUseAcceleratedPanning && m_cache_vp.IsValid() &&
3954 (VPoint.m_projection_type == PROJECTION_MERCATOR ||
3955 VPoint.m_projection_type == PROJECTION_EQUIRECTANGULAR) &&
3956 m_cache_vp.pix_height == VPoint.pix_height) {
3957 wxPoint2DDouble c_old =
3958 VPoint.GetDoublePixFromLL(VPoint.clat, VPoint.clon) *
3959 m_displayScale;
3960 wxPoint2DDouble c_new =
3961 m_cache_vp.GetDoublePixFromLL(VPoint.clat, VPoint.clon) *
3962 m_displayScale;
3963
3964 dy = wxRound(c_new.m_y - c_old.m_y);
3965 dx = wxRound(c_new.m_x - c_old.m_x);
3966
3967 // The math below using the previous frame's texture does not really
3968 // work for sub-pixel pans.
3969 // TODO is to rethink this.
3970 // Meanwhile, require the accelerated pans to be whole pixel multiples
3971 // only. This is not as bad as it sounds. Keyboard and mouse pans are
3972 // whole_pixel moves. However, autofollow at large scale is certainly
3973 // not.
3974
3975 double deltax = c_new.m_x - c_old.m_x;
3976 double deltay = c_new.m_y - c_old.m_y;
3977
3978 bool b_whole_pixel = true;
3979 if ((fabs(deltax - dx) > 1e-2) || (fabs(deltay - dy) > 1e-2))
3980 b_whole_pixel = false;
3981
3982 accelerated_pan = b_whole_pixel && abs(dx) < m_cache_tex_x &&
3983 abs(dy) < m_cache_tex_y &&
3984 (abs(dx) > 0 || (abs(dy) > 0));
3985
3986 // if (g_in_inertia && !accelerated_pan)
3987 // printf("--- accpan %d %d %g %g\n", accelerated_pan,
3988 // b_whole_pixel, dx, dy);
3989 }
3990
3991 // FBO swapping has trouble with Retina display on MacOS Monterey.
3992 // So, disable accelerated pan ops on this case.
3993 if (m_displayScale > 1) accelerated_pan = false;
3994
3995 // FIXME (dave) There are some display artifact troubles using accPan on
3996 // rotation.
3997 // Especially seen on sparse RNC rendering
3998 if (fabs(VPoint.rotation) > 0) accelerated_pan = false;
3999
4000 // do we allow accelerated panning? can we perform it here?
4001#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
4002#else // GLES2
4003 // enable rendering to texture in framebuffer object
4004 glBindFramebuffer(GL_FRAMEBUFFER, m_fb0);
4005
4006 if (VPoint.chart_scale < 5000) b_full = true;
4007
4008 if (VPoint.chart_scale > 5e7) b_full = true;
4009
4010 if (b_full) accelerated_pan = false;
4011
4012 if (accelerated_pan) {
4013 if ((dx != 0) || (dy != 0)) { // Anything to do?
4014
4015 // calculate the new regions to render
4016 // add extra pixels to avoid coordindate rounding issues at large
4017 // scale
4018 OCPNRegion update_region;
4019
4020 int fluff = 2;
4021
4022 // Avoid rendering artifacts caused by Multi Sampling (MSAA)
4023 if (VPoint.chart_scale < 10000) fluff = 8;
4024
4025 if (dy > 0 && dy < gl_height)
4026 update_region.Union(
4027 wxRect(0, gl_height - (dy + fluff), gl_width, dy + fluff));
4028 else if (dy < 0)
4029 update_region.Union(wxRect(0, 0, gl_width, -dy + fluff));
4030
4031 if (dx > 0 && dx < gl_width)
4032 update_region.Union(
4033 wxRect(gl_width - (dx + fluff), 0, dx + fluff, gl_height));
4034 else if (dx < 0)
4035 update_region.Union(wxRect(0, 0, -dx + fluff, gl_height));
4036
4037 m_cache_page = !m_cache_page; /* page flip */
4038
4039 // Bind the destination (target frame) texture to the frame buffer
4040 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4041 GL_TEXTURE_2D, m_cache_tex[m_cache_page], 0);
4042
4043 // Before rendering anything, clear the color buffers
4044 // wxColour color = GetGlobalColor("NODTA");
4045 // glClearColor(color.Red() / 256., color.Green() / 256.,
4046 // color.Blue() / 256., 1.0);
4047 // glClear(GL_COLOR_BUFFER_BIT);
4048
4049 // First render the new content into the update region
4050 // if (g_in_inertia)
4051 // printf("--- R2a %g\n",
4052 // (wxGetLocalTimeMillis() - s_t0).ToDouble());
4053 RenderCharts(m_gldc, update_region);
4054 // if (g_in_inertia)
4055 // printf("--- R2b %g\n",
4056 // (wxGetLocalTimeMillis() - s_t0).ToDouble());
4057 glDisable(g_texture_rectangle_format);
4058 glUseProgram(0);
4059
4060 // Next, render the cached texture as quad to FBO(m_blit_tex) with
4061 // offsets
4062 glBindTexture(GL_TEXTURE_2D, m_cache_tex[!m_cache_page]);
4063 glEnable(GL_TEXTURE_2D);
4064
4065 // Blit the existing content onto the alternate FBO, at the correct
4066 // location
4067 float x1, x2, y1, y2;
4068
4069 if (dx > 0)
4070 x1 = dx, x2 = 0;
4071 else
4072 x1 = 0, x2 = -dx;
4073
4074 if (dy > 0)
4075 y1 = dy, y2 = 0;
4076 else
4077 y1 = 0, y2 = -dy;
4078
4079 // normalize to texture coordinates range from 0 to 1
4080 float tx1, tx2, ty1, ty2;
4081
4082 float xcor = 0;
4083 float ycor = 0;
4084
4085 tx1 = 0;
4086 tx2 = sx / (float)m_cache_tex_x;
4087 ty1 = 0;
4088 ty2 = sy / (float)m_cache_tex_y;
4089
4090 float coords[8];
4091 float uv[8];
4092
4093 // normal uv
4094 uv[0] = tx1;
4095 uv[1] = ty1;
4096 uv[2] = tx2;
4097 uv[3] = ty1;
4098 uv[4] = tx2;
4099 uv[5] = ty2;
4100 uv[6] = tx1;
4101 uv[7] = ty2;
4102
4103 coords[0] = -dx;
4104 coords[1] = dy;
4105 coords[2] = -dx + sx;
4106 coords[3] = dy;
4107 coords[4] = -dx + sx;
4108 coords[5] = dy + sy;
4109 coords[6] = -dx;
4110 coords[7] = dy + sy;
4111
4112 GLShaderProgram *shader =
4113 ptexture_2D_shader_program[GetCanvasIndex()];
4114 shader->Bind();
4115
4116 // Set up the texture sampler to texture unit 0
4117 shader->SetUniform1i("uTex", 0);
4118
4119 mat4x4 m, mvp, I;
4120 mat4x4_identity(m);
4121 mat4x4_scale_aniso(mvp, m, 2.0 / (float)sx, 2.0 / (float)sy, 1.0);
4122 mat4x4_translate_in_place(mvp, -(float)sx / 2, -(float)sy / 2, 0);
4123 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)mvp);
4124 mat4x4_identity(I);
4125 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
4126
4127 float co1[8];
4128 co1[0] = coords[0];
4129 co1[1] = coords[1];
4130 co1[2] = coords[2];
4131 co1[3] = coords[3];
4132 co1[4] = coords[6];
4133 co1[5] = coords[7];
4134 co1[6] = coords[4];
4135 co1[7] = coords[5];
4136
4137 float tco1[8];
4138 tco1[0] = uv[0];
4139 tco1[1] = uv[1];
4140 tco1[2] = uv[2];
4141 tco1[3] = uv[3];
4142 tco1[4] = uv[6];
4143 tco1[5] = uv[7];
4144 tco1[6] = uv[4];
4145 tco1[7] = uv[5];
4146
4147 shader->SetAttributePointerf("aPos", co1);
4148 shader->SetAttributePointerf("aUV", tco1);
4149
4150 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
4151
4152 // restore the shader matrix
4153 shader->SetUniformMatrix4fv("MVMatrix",
4154 (GLfloat *)VPoint.vp_matrix_transform);
4155
4156 shader->UnBind();
4157 glBindTexture(g_texture_rectangle_format, 0);
4158
4159 glDisable(g_texture_rectangle_format);
4160 glUseProgram(0);
4161 }
4162
4163 } // accelerated pan
4164
4165 else { // must redraw the entire screen
4166 // qDebug() << "Fullpage";
4167 glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0,
4168 g_texture_rectangle_format,
4169 m_cache_tex[!m_cache_page], 0);
4170
4171 m_fbo_offsetx = 0;
4172 m_fbo_offsety = 0;
4173 m_fbo_swidth = sx;
4174 m_fbo_sheight = sy;
4175
4176 // FIXME (dave) test on Android
4177 // This can be annoying on Android pinch zoom
4178
4179 // Clear the screen to NODTA color
4180 wxColour color = GetGlobalColor("NODTA");
4181 glClearColor(color.Red() / 256., color.Green() / 256.,
4182 color.Blue() / 256., 1.0);
4183 glClear(GL_COLOR_BUFFER_BIT);
4184
4185 OCPNRegion rscreen_region(VPoint.rv_rect);
4186 // if (g_in_inertia)
4187 // printf("--- R2c %g\n",
4188 // (wxGetLocalTimeMillis() - s_t0).ToDouble());
4189 RenderCharts(m_gldc, rscreen_region);
4190 // if (g_in_inertia)
4191 // printf("--- R2d %g\n",
4192 // (wxGetLocalTimeMillis() - s_t0).ToDouble());
4193
4194 m_cache_page = !m_cache_page; /* page flip */
4195
4196 } // full page render
4197
4198 // Disable Render to FBO
4199 glBindFramebuffer(GL_FRAMEBUFFER, 0);
4200
4201#endif // gles2 for accpan
4202
4203 } // newview
4204
4205 useFBO = true;
4206 }
4207
4208#ifndef __ANDROID__
4209 if (VPoint.tilt) {
4210 glMatrixMode(GL_PROJECTION);
4211 glLoadIdentity();
4212
4213 gluPerspective(2 * 180 / PI * atan2((double)gl_height, (double)gl_width),
4214 (GLfloat)gl_width / (GLfloat)gl_height, 1, gl_width);
4215
4216 glMatrixMode(GL_MODELVIEW);
4217 glLoadIdentity();
4218
4219 glScalef(1, -1, 1);
4220 glTranslatef(-gl_width / 2, -gl_height / 2, -gl_width / 2);
4221 glRotated(VPoint.tilt * 180 / PI, 1, 0, 0);
4222
4223 glGetIntegerv(GL_VIEWPORT, viewport);
4224 glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
4225 glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
4226 }
4227#endif
4228
4229 // if (g_in_inertia)
4230 // printf("--- R3 %g\n", (wxGetLocalTimeMillis() - s_t0).ToDouble());
4231
4232 if (useFBO) {
4233#if 0 // #ifndef USE_ANDROID_GLES2
4234 glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fb0);
4235 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
4236 glBlitFramebuffer(0, 0, sx, sy, 0, 0, sx*2, sy*2, GL_COLOR_BUFFER_BIT, GL_LINEAR);
4237
4238 glBindFramebuffer(GL_FRAMEBUFFER, 0);
4239
4240#else
4241 // Render the cached texture as quad to screen
4242 glBindTexture(g_texture_rectangle_format, m_cache_tex[m_cache_page]);
4243 glEnable(g_texture_rectangle_format);
4244
4245 float tx, ty, tx0, ty0, divx, divy;
4246
4247 // Normalize, or not?
4248 if (GL_TEXTURE_RECTANGLE_ARB == g_texture_rectangle_format) {
4249 divx = divy = 1.0f;
4250 } else {
4251 divx = m_cache_tex_x;
4252 divy = m_cache_tex_y;
4253 }
4254
4255 tx0 = m_fbo_offsetx / divx;
4256 ty0 = m_fbo_offsety / divy;
4257 tx = (m_fbo_offsetx + m_fbo_swidth) / divx;
4258 ty = (m_fbo_offsety + m_fbo_sheight) / divy;
4259
4260 float coords[8];
4261 float uv[8];
4262
4263 // normal uv
4264 uv[0] = tx0;
4265 uv[1] = ty;
4266 uv[2] = tx;
4267 uv[3] = ty;
4268 uv[4] = tx;
4269 uv[5] = ty0;
4270 uv[6] = tx0;
4271 uv[7] = ty0;
4272
4273 // pixels
4274 coords[0] = 0;
4275 coords[1] = 0;
4276 coords[2] = sx;
4277 coords[3] = 0;
4278 coords[4] = sx;
4279 coords[5] = sy;
4280 coords[6] = 0;
4281 coords[7] = sy;
4282
4283 wxColour color = GetGlobalColor("NODTA");
4284 glClearColor(color.Red() / 256., color.Green() / 256., color.Blue() / 256.,
4285 1.0);
4286 glClear(GL_COLOR_BUFFER_BIT);
4287
4288 RenderTextures(gldc, coords, uv, 4, m_pParentCanvas->GetpVP());
4289#endif
4290
4291 glDisable(g_texture_rectangle_format);
4292
4293 m_cache_vp = VPoint;
4294 m_cache_vp.Validate();
4295
4296 m_cache_current_ch = m_pParentCanvas->m_singleChart;
4297
4298 if (VPoint.b_quilt) m_pParentCanvas->m_pQuilt->SetRenderedVP(VPoint);
4299
4300 } else // useFBO
4301 {
4302 RenderCharts(m_gldc, screen_region);
4303 }
4304
4305 // if (m_binPinch)
4306 // printf(" Render Charts Done %ld\n",
4307 // m_glstopwatch.Time() - render_start_time);
4308
4309 // Done with base charts.
4310 // Now the overlays
4311 RenderS57TextOverlay(VPoint);
4312 RenderMBTilesOverlay(VPoint);
4313
4314 g_overlayCanvas = m_pParentCanvas;
4315 if (g_pi_manager) {
4316 g_pi_manager->SendViewPortToRequestingPlugIns(VPoint);
4317 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
4318 m_pcontext, VPoint, m_pParentCanvas->m_canvasIndex, OVERLAY_CHARTS);
4319 }
4320
4321 // Render static overlay objects
4322 for (OCPNRegionIterator upd(screen_region); upd.HaveRects(); upd.NextRect()) {
4323 wxRect rt = upd.GetRect();
4324 LLRegion region = VPoint.GetLLRegion(rt);
4325 ViewPort cvp = ClippedViewport(VPoint, region);
4326 DrawGroundedOverlayObjects(gldc, cvp);
4327 }
4328
4329 if (m_pParentCanvas->m_bShowTide || m_pParentCanvas->m_bShowCurrent) {
4330 LLRegion screenLLRegion = VPoint.GetLLRegion(screen_region);
4331 LLBBox screenBox = screenLLRegion.GetBox();
4332 // Enlarge the box a bit
4333 screenBox.EnLarge(screenBox.GetLonRange() * 0.05);
4334
4335 // update the tide/current select points, if necessary
4336 if (m_pParentCanvas->m_bShowTide) {
4337 m_pParentCanvas->RebuildTideSelectList(screenBox); // full screen
4338 DrawGLTidesInBBox(gldc, VPoint.GetBBox());
4339 }
4340
4341 if (m_pParentCanvas->m_bShowCurrent) {
4342 m_pParentCanvas->RebuildCurrentSelectList(screenBox);
4343 DrawGLCurrentsInBBox(gldc, VPoint.GetBBox());
4344 }
4345 }
4346
4347 // If multi-canvas, indicate which canvas has keyboard focus
4348 // by drawing a simple blue bar at the top.
4349 if (m_pParentCanvas->m_show_focus_bar &&
4350 (g_canvasConfig != 0)) { // multi-canvas?
4351 if (m_pParentCanvas == wxWindow::FindFocus()) {
4352 g_focusCanvas = m_pParentCanvas;
4353
4354 wxColour colour = GetGlobalColor("BLUE4");
4355 wxPen ppBlue(colour, 1);
4356 wxBrush ppBrush(colour);
4357 gldc.SetPen(ppBlue);
4358 gldc.SetBrush(ppBrush);
4359 int xw = m_pParentCanvas->GetClientSize().x * m_displayScale;
4360 float rect_pix = m_pParentCanvas->m_focus_indicator_pix * m_displayScale;
4361 wxPoint barPoints[4];
4362 barPoints[0].x = 0;
4363 barPoints[0].y = 0;
4364 barPoints[1].x = xw;
4365 barPoints[1].y = 0;
4366 barPoints[2].x = xw;
4367 barPoints[2].y = rect_pix;
4368 barPoints[3].x = 0;
4369 barPoints[3].y = rect_pix;
4370
4371 gldc.DrawPolygon(4, barPoints, 0, 0, 1, 0);
4372 }
4373 }
4374
4375 DrawDynamicRoutesTracksAndWaypoints(VPoint);
4376
4377 // Now draw all the objects which normally move around and are not
4378 // cached from the previous frame
4379 DrawFloatingOverlayObjects(m_gldc);
4380
4381#ifndef USE_ANDROID_GLES2
4382 // from this point on don't use perspective
4383 if (VPoint.tilt) {
4384 glMatrixMode(GL_PROJECTION);
4385 glLoadIdentity();
4386
4387 glOrtho(0, (GLint)gl_width, (GLint)gl_height, 0, -1, 1);
4388 glMatrixMode(GL_MODELVIEW);
4389 glLoadIdentity();
4390 }
4391#endif
4392
4393 if (!g_bhide_depth_units)
4394 DrawEmboss(m_gldc, m_pParentCanvas->EmbossDepthScale());
4395 if (!g_bhide_overzoom_flag)
4396 DrawEmboss(m_gldc, m_pParentCanvas->EmbossOverzoomIndicator(gldc));
4397
4398 if (g_pi_manager) {
4399 ViewPort &vp = m_pParentCanvas->GetVP();
4400 g_pi_manager->SendViewPortToRequestingPlugIns(vp);
4401 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
4402 m_pcontext, vp, m_pParentCanvas->m_canvasIndex, OVERLAY_OVER_EMBOSS);
4403 }
4404 if (!g_PrintingInProgress) {
4405 if (m_pParentCanvas->m_pTrackRolloverWin)
4406 m_pParentCanvas->m_pTrackRolloverWin->Draw(gldc);
4407
4408 if (m_pParentCanvas->m_pRouteRolloverWin)
4409 m_pParentCanvas->m_pRouteRolloverWin->Draw(gldc);
4410
4411 if (m_pParentCanvas->m_pAISRolloverWin)
4412 m_pParentCanvas->m_pAISRolloverWin->Draw(gldc);
4413
4414 if (m_pParentCanvas->GetMUIBar())
4415 m_pParentCanvas->GetMUIBar()->DrawGL(gldc, m_displayScale);
4416
4417 if (g_MainToolbar && m_pParentCanvas->IsPrimaryCanvas())
4418 g_MainToolbar->DrawGL(gldc, m_displayScale);
4419
4420 if (g_iENCToolbar && m_pParentCanvas->IsPrimaryCanvas())
4421 g_iENCToolbar->DrawGL(gldc, m_displayScale);
4422 }
4423
4424 // On some platforms, the opengl context window is always on top of any
4425 // standard DC windows, so we need to draw the Chart Info Window
4426 // as overlayed bmps.
4427
4428#ifdef __WXOSX__
4429 if (m_pParentCanvas->m_pCIWin && m_pParentCanvas->m_pCIWin->IsShown()) {
4430 int x, y, width, height;
4431 m_pParentCanvas->m_pCIWin->GetClientSize(&width, &height);
4432 m_pParentCanvas->m_pCIWin->GetPosition(&x, &y);
4433 wxBitmap bmp(width, height, -1);
4434 wxMemoryDC dc(bmp);
4435 if (bmp.IsOk()) {
4436 dc.SetBackground(wxBrush(GetGlobalColor("UIBCK")));
4437 dc.Clear();
4438
4439 dc.SetTextBackground(GetGlobalColor("UIBCK"));
4440 dc.SetTextForeground(GetGlobalColor("UITX1"));
4441
4442 int yt = 0;
4443 int xt = 0;
4444 wxString s = m_pParentCanvas->m_pCIWin->GetString();
4445 int h = m_pParentCanvas->m_pCIWin->GetCharHeight();
4446
4447 wxStringTokenizer tkz(s, "\n");
4448 wxString token;
4449
4450 while (tkz.HasMoreTokens()) {
4451 token = tkz.GetNextToken();
4452 dc.DrawText(token, xt, yt);
4453 yt += h;
4454 }
4455 dc.SelectObject(wxNullBitmap);
4456
4457 m_gldc.DrawBitmap(bmp, x, y, false);
4458 }
4459 }
4460
4461#endif
4462 // render the chart bar
4463 if (g_bShowChartBar) DrawChartBar(m_gldc);
4464
4465 if (m_pParentCanvas->m_Compass && m_pParentCanvas->m_bShowCompassWin &&
4466 g_bShowCompassWin)
4467 m_pParentCanvas->m_Compass->Paint(gldc);
4468
4469 if (m_pParentCanvas->IsPrimaryCanvas() &&
4470 m_pParentCanvas->m_notification_button) {
4471 auto &noteman = NotificationManager::GetInstance();
4472 if (noteman.GetNotificationCount()) {
4473 m_pParentCanvas->m_notification_button->SetIconSeverity(
4474 noteman.GetMaxSeverity());
4475 if (m_pParentCanvas->m_notification_button->UpdateStatus()) Refresh();
4476 m_pParentCanvas->m_notification_button->Show(true);
4477 m_pParentCanvas->m_notification_button->Paint(gldc);
4478 } else {
4479 m_pParentCanvas->m_notification_button->Show(false);
4480 }
4481 }
4482 RenderGLAlertMessage();
4483
4484 if (g_pi_manager) {
4485 ViewPort &vp = m_pParentCanvas->GetVP();
4486 g_pi_manager->SendViewPortToRequestingPlugIns(vp);
4487 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
4488 m_pcontext, vp, m_pParentCanvas->m_canvasIndex, OVERLAY_OVER_UI);
4489 glActiveTexture(GL_TEXTURE0);
4490 }
4491
4492 // quiting?
4493 if (g_bquiting) DrawQuiting();
4494 if (g_bcompression_wait)
4495 DrawCloseMessage(_("Waiting for raster chart compression thread exit."));
4496
4497 // Some older MSW OpenGL drivers are generally very unstable.
4498 // This helps...
4499
4500 SwapBuffers();
4501
4502 g_glTextureManager->TextureCrunch(0.8);
4503 g_glTextureManager->FactoryCrunch(0.6);
4504
4505 m_pParentCanvas->PaintCleanup();
4506 m_bforcefull = false;
4507
4508 // if (m_binPinch)
4509 // printf(" Render Finished: %ld\n",
4510 // m_glstopwatch.Time() - render_start_time);
4511
4512 n_render++;
4513}
4514
4515void glChartCanvas::RenderS57TextOverlay(ViewPort &VPoint) {
4516 // Render the decluttered Text overlay for quilted vector charts, except for
4517 // CM93 Composite
4518 if (VPoint.b_quilt) {
4519 if (m_pParentCanvas->m_pQuilt->IsQuiltVector() && ps52plib &&
4520 ps52plib->GetShowS57Text()) {
4521 ChartBase *chart = m_pParentCanvas->m_pQuilt->GetRefChart();
4522 if (chart && (chart->GetChartType() != CHART_TYPE_CM93COMP)) {
4523 // Clear the text Global declutter list
4524 if (chart) {
4525 ChartPlugInWrapper *ChPI = dynamic_cast<ChartPlugInWrapper *>(chart);
4526 if (ChPI)
4527 ChPI->ClearPLIBTextList();
4528 else
4529 ps52plib->ClearTextList();
4530 }
4531
4532 // Grow the ViewPort a bit laterally, to minimize "jumping" of text
4533 // elements at right side of screen
4534 ViewPort vpx = VPoint;
4535 vpx.BuildExpandedVP(VPoint.pix_width * 12 / 10, VPoint.pix_height);
4536
4537 OCPNRegion screen_region(
4538 wxRect(0, 0, VPoint.pix_width, VPoint.pix_height));
4539 RenderQuiltViewGLText(vpx, screen_region);
4540 }
4541 }
4542 }
4543}
4544void glChartCanvas::RenderSingleMBTileOverlay(const int dbIndex, bool bOverlay,
4545 ViewPort &vp,
4546 OCPNRegion &screen_region,
4547 LLRegion &screenLLRegion) {
4548 ChartBase *chart = ChartData->OpenChartFromDBAndLock(dbIndex, FULL_INIT);
4549
4550 // Chart may have been prevented from initial loading due to size, or some
4551 // other reason...
4552 if (chart == NULL) return;
4553
4554 ChartMbTiles *pcmbt = dynamic_cast<ChartMbTiles *>(chart);
4555 if (!pcmbt) return;
4556
4557 // Is tile an OVERLAY type?
4558 // Render, or not, depending on passed flag.
4559 if (bOverlay && pcmbt->GetTileType() != MbTilesType::OVERLAY) return;
4560
4561 wxFileName tileFile(chart->GetFullPath());
4562 // Size test for 5 GByte
4563 wxULongLong tileSizeMB = tileFile.GetSize() >> 20;
4564
4565 // Auto-show MBTiles in basemap directories
4566 bool isBasemap = tileFile.GetPath().Lower().Contains("basemap");
4567
4568 // For basemap MBTiles, stop rendering when zoomed in past their max detail
4569 // to allow S57 vector charts to show through
4570 if (isBasemap) {
4571 double chart_native_ppm = m_pParentCanvas->GetCanvasScaleFactor() /
4572 (double)chart->GetNativeScale();
4573 double zoom_ratio = vp.view_scale_ppm / chart_native_ppm;
4574 if (zoom_ratio > g_tile_basemap_zoom_factor) return;
4575 }
4576
4577 if (!isBasemap && (!ChartData->CheckAnyCanvasExclusiveTileGroup() ||
4578 (tileSizeMB.GetLo() > 5000))) {
4579 // Check to see if the tile has been "clicked".
4580 // If so, do not add to no-show array again.
4581 if (!m_pParentCanvas->IsTileOverlayIndexInYesShow(dbIndex)) {
4582 if (!m_pParentCanvas->IsTileOverlayIndexInNoShow(dbIndex)) {
4583 m_pParentCanvas->m_tile_noshow_index_array.push_back(dbIndex);
4584 }
4585 }
4586 }
4587
4588 // This test catches the case where the chart is added to no_show list
4589 // when first loaded by OpenChartFromDBAndLock
4590 if (m_pParentCanvas->IsTileOverlayIndexInNoShow(dbIndex)) {
4591 return;
4592 }
4593
4594 pcmbt->RenderRegionViewOnGL(*m_pcontext, vp, screen_region, screenLLRegion);
4595
4596 // Light up the piano key if the chart was rendered
4597 std::vector<int> piano_active_array_tiles =
4598 m_pParentCanvas->m_Piano->GetActiveKeyArray();
4599 bool bfound = false;
4600
4601 if (std::find(piano_active_array_tiles.begin(),
4602 piano_active_array_tiles.end(),
4603 dbIndex) != piano_active_array_tiles.end()) {
4604 bfound = true;
4605 }
4606
4607 if (!bfound) {
4608 piano_active_array_tiles.push_back(dbIndex);
4609 m_pParentCanvas->m_Piano->SetActiveKeyArray(piano_active_array_tiles);
4610 }
4611}
4612
4613void glChartCanvas::RenderMBTilesOverlay(ViewPort &VPoint) {
4614 // Render MBTiles as overlay
4615 std::vector<int> stackIndexArray =
4616 m_pParentCanvas->m_pQuilt->GetExtendedStackIndexArray();
4617 unsigned int im = stackIndexArray.size();
4618 // XXX should
4619 // assert(!VPoint.b_quilt && im == 0)
4620 if (VPoint.b_quilt && im > 0) {
4621 bool regionVPBuilt = false;
4622 OCPNRegion screen_region;
4623 LLRegion screenLLRegion;
4624 LLBBox screenBox;
4625 ViewPort vp;
4626
4627 std::vector<int> tiles_to_show;
4628 for (unsigned int is = 0; is < im; is++) {
4629 const ChartTableEntry &cte =
4630 ChartData->GetChartTableEntry(stackIndexArray[is]);
4631 if (cte.GetChartType() == CHART_TYPE_MBTILES) {
4632 if (m_pParentCanvas->IsTileOverlayIndexInNoShow(stackIndexArray[is])) {
4633 // Turn off the piano highlite
4634 std::vector<int> piano_active_array_tiles =
4635 m_pParentCanvas->m_Piano->GetActiveKeyArray();
4636 bool bfound = false;
4637
4638 for (unsigned int i = 0; i < piano_active_array_tiles.size(); i++) {
4639 if (piano_active_array_tiles[i] == stackIndexArray[is]) {
4640 piano_active_array_tiles.erase(piano_active_array_tiles.begin() +
4641 i); // erase it
4642 bfound = true;
4643 break;
4644 }
4645 }
4646
4647 if (bfound)
4648 m_pParentCanvas->m_Piano->SetActiveKeyArray(
4649 piano_active_array_tiles);
4650
4651 continue;
4652 }
4653
4654 tiles_to_show.push_back(stackIndexArray[is]);
4655 if (!regionVPBuilt) {
4656 screen_region =
4657 OCPNRegion(wxRect(0, 0, VPoint.pix_width, VPoint.pix_height));
4658 screenLLRegion = VPoint.GetLLRegion(screen_region);
4659 screenBox = screenLLRegion.GetBox();
4660
4661 vp = VPoint;
4662 wxPoint p;
4663 p.x = VPoint.pix_width / 2;
4664 p.y = VPoint.pix_height / 2;
4665 VPoint.GetLLFromPix(p, &vp.clat, &vp.clon);
4666
4667 regionVPBuilt = true;
4668 }
4669 }
4670 }
4671
4672 // Render in two passes, to render the OVERLAY types last
4673
4674 // Show the tilesets in reverse order to have the largest scale
4675 // on top
4676
4677 for (std::vector<int>::reverse_iterator rit = tiles_to_show.rbegin();
4678 rit != tiles_to_show.rend(); ++rit) {
4679 RenderSingleMBTileOverlay(*rit, FALSE, vp, screen_region, screenLLRegion);
4680 }
4681 for (std::vector<int>::reverse_iterator rit = tiles_to_show.rbegin();
4682 rit != tiles_to_show.rend(); ++rit) {
4683 RenderSingleMBTileOverlay(*rit, TRUE, vp, screen_region, screenLLRegion);
4684 }
4685
4686 // Render the HiLite on piano rollover of mbTile key
4687 LLRegion hiregion = m_pParentCanvas->m_pQuilt->GetHiliteRegion();
4688
4689 if (!hiregion.Empty()) {
4690 glEnable(GL_BLEND);
4691
4692 double hitrans;
4693 switch (global_color_scheme) {
4694 case GLOBAL_COLOR_SCHEME_DAY:
4695 hitrans = .4;
4696 break;
4697 case GLOBAL_COLOR_SCHEME_DUSK:
4698 hitrans = .2;
4699 break;
4700 case GLOBAL_COLOR_SCHEME_NIGHT:
4701 hitrans = .1;
4702 break;
4703 default:
4704 hitrans = .4;
4705 break;
4706 }
4707
4708#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
4709 glColor4f((float).8, (float).4, (float).4, (float)hitrans);
4710#else
4711 s_regionColor = wxColor(204, 102, 102, hitrans * 256);
4712#endif
4713
4714 DrawRegion(VPoint, hiregion);
4715
4716 glDisable(GL_BLEND);
4717 }
4718 }
4719}
4720
4721#if 0
4722void glChartCanvas::RenderCanvasBackingChart(ocpnDC &dc,
4723 OCPNRegion valid_region) {
4724 // Fill the FBO with the current gshhs world chart
4725 int w, h;
4726 GetClientSize(&w, &h);
4727
4728 glViewport(0, 0, (GLint)m_cache_tex_x, (GLint)m_cache_tex_y);
4729#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
4730 glMatrixMode(GL_PROJECTION);
4731 glLoadIdentity();
4732
4733 glOrtho(0, m_cache_tex_x, m_cache_tex_y, 0, -1, 1);
4734 glMatrixMode(GL_MODELVIEW);
4735 glLoadIdentity();
4736#endif
4737
4738 wxRect rtex(0, 0, m_cache_tex_x, m_cache_tex_y);
4739 ViewPort cvp =
4740 m_pParentCanvas->GetVP().BuildExpandedVP(m_cache_tex_x, m_cache_tex_y);
4741
4742 bool world_view = false;
4743 RenderWorldChart(dc, cvp, rtex, world_view);
4744 gShapeBasemap.RenderViewOnDC(dc, cvp);
4745
4746 // dc.SetPen(wxPen(wxColour(254,254,0), 3));
4747 // dc.DrawLine( 0, 0, m_cache_tex_x, m_cache_tex_y);
4748
4749 // Reset matrices
4750 glViewport(0, 0, (GLint)w, (GLint)h);
4751#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
4752 glMatrixMode(GL_PROJECTION);
4753 glLoadIdentity();
4754
4755 glOrtho(0, (GLint)w, (GLint)h, 0, -1, 1);
4756 glMatrixMode(GL_MODELVIEW);
4757 glLoadIdentity();
4758#endif
4759}
4760#endif
4761
4762void glChartCanvas::FastPan(int dx, int dy) {
4763#if !defined(USE_ANDROID_GLES2) && !defined(ocpnUSE_GLSL)
4764#endif
4765}
4766
4767void glChartCanvas::ZoomProject(float offset_x, float offset_y, float swidth,
4768 float sheight) {
4769 if (IsShown()) SetCurrent(*m_pcontext);
4770 float sx = GetSize().x;
4771 float sy = GetSize().y;
4772 glClear(GL_COLOR_BUFFER_BIT);
4773
4774 int w, h;
4775 GetClientSize(&w, &h);
4776
4777 if (s_b_useStencil) {
4778 glEnable(GL_STENCIL_TEST);
4779 glStencilMask(0xff);
4780 glClear(GL_STENCIL_BUFFER_BIT);
4781 glDisable(GL_STENCIL_TEST);
4782 }
4783
4784#ifndef __ANDROID__
4785 // Render backing texture
4786 if (1) {
4787 float tx0 = 0;
4788 float ty0 = 0;
4789 float tx = sx;
4790 float ty = sy;
4791
4792 float vx0 = 0;
4793 float vy0 = 0;
4794 float vx = sx;
4795 float vy = sy;
4796
4797 float sxfactor = sx / swidth;
4798 float syfactor = sy / sheight;
4799
4800 glViewport(-offset_x * sx / swidth - (sx * sxfactor / 2),
4801 -offset_y * (sy / sheight) - (sy * syfactor / 2),
4802 sx * sx / swidth * 2, sy * sy / sheight * 2);
4803 glBindTexture(g_texture_rectangle_format, m_TouchBackingTexture);
4804 glEnable(g_texture_rectangle_format);
4805
4806 float uv[8];
4807 float coords[8];
4808
4809 // normal uv Texture coordinates
4810 uv[0] = 0;
4811 uv[1] = 0;
4812 uv[2] = 1;
4813 uv[3] = 0;
4814 uv[4] = 1;
4815 uv[5] = 1;
4816 uv[6] = 0;
4817 uv[7] = 1;
4818
4819 // pixels
4820 coords[0] = vx0;
4821 coords[1] = vy0;
4822 coords[2] = vx;
4823 coords[3] = vy0;
4824 coords[4] = vx;
4825 coords[5] = vy;
4826 coords[6] = vx0;
4827 coords[7] = vy;
4828
4829 RenderTextures(m_gldc, coords, uv, 4, &m_texVP);
4830 glBindTexture(g_texture_rectangle_format, 0);
4831 }
4832#endif
4833
4834 // render zoomed canvas section
4835 if (1) {
4836 float tx, ty, tx0, ty0;
4837 tx = sx, ty = sy;
4838
4839 tx0 = ty0 = 0.;
4840
4841 float vx0 = 0;
4842 float vy0 = 0;
4843 float vy = sy;
4844 float vx = sx;
4845
4846 glBindTexture(g_texture_rectangle_format, 0);
4847
4848 // Render the cached texture as quad to screen
4849 glBindTexture(g_texture_rectangle_format, m_cache_tex[m_cache_page]);
4850 glEnable(g_texture_rectangle_format);
4851
4852 float uv[8];
4853 float coords[8];
4854
4855 // normal uv Texture coordinates
4856 uv[0] = tx0 / m_cache_tex_x;
4857 uv[1] = ty / m_cache_tex_y;
4858 uv[2] = tx / m_cache_tex_x;
4859 uv[3] = ty / m_cache_tex_y;
4860 uv[4] = tx / m_cache_tex_x;
4861 uv[5] = ty0 / m_cache_tex_y;
4862 uv[6] = tx0 / m_cache_tex_x;
4863 uv[7] = ty0 / m_cache_tex_y;
4864
4865 // pixels
4866 coords[0] = vx0;
4867 coords[1] = vy0;
4868 coords[2] = vx;
4869 coords[3] = vy0;
4870 coords[4] = vx;
4871 coords[5] = vy;
4872 coords[6] = vx0;
4873 coords[7] = vy;
4874
4875 glViewport(-offset_x * sx / swidth, -offset_y * (sy / sheight),
4876 sx * sx / swidth, sy * sy / sheight);
4877
4878 RenderTextures(m_gldc, coords, uv, 4, m_pParentCanvas->GetpVP());
4879
4880 glDisable(g_texture_rectangle_format);
4881 glBindTexture(g_texture_rectangle_format, 0);
4882 }
4883
4884#if 0
4885 // For fun, we prove the coordinates of the blank area outside the chart when
4886 // zooming out. Bottom stripe
4887 // wxColour color = GetGlobalColor("YELO1"); //GREY1
4888 wxColour color = GetGlobalColor("GREY1"); //
4889 float ht = -offset_y * (sy / sheight);
4890 wxRect r(0, sy - ht, w, ht);
4891 RenderColorRect(r, color);
4892
4893 // top stripe
4894 wxRect rt(0, 0, w, sy - (ht + (sy * sy / sheight)));
4895 RenderColorRect(rt, color);
4896
4897 // left
4898 float w1 = -offset_x * sx / swidth;
4899 wxRect rl(0, 0, w1, sy);
4900 RenderColorRect(rl, color);
4901
4902 // right
4903 float px = w1 + sx * sx / swidth;
4904 wxRect rr(px, 0, sx - px, sy);
4905 RenderColorRect(rr, color);
4906#endif
4907 // When zooming out, if we go too far, then the frame buffer is repeated
4908 // on-screen due to address wrapping in the frame buffer. Detect this case,
4909 // and render some simple solid covering quads to avoid a confusing display.
4910
4911 SwapBuffers();
4912}
4913
4914void glChartCanvas::onZoomTimerEvent(wxTimerEvent &event) {
4915 // If m_zoomFinal is set, stop the timer.
4916 if (!m_zoomFinal) {
4917 if (m_nRun < m_nTotal) {
4918 m_runoffsetx += m_offsetxStep;
4919 if (m_offsetxStep > 0)
4920 m_runoffsetx = wxMin(m_runoffsetx, m_fbo_offsetx);
4921 else
4922 m_runoffsetx = wxMax(m_runoffsetx, m_fbo_offsetx);
4923
4924 m_runoffsety += m_offsetyStep;
4925 if (m_offsetyStep > 0)
4926 m_runoffsety = wxMin(m_runoffsety, m_fbo_offsety);
4927 else
4928 m_runoffsety = wxMax(m_runoffsety, m_fbo_offsety);
4929
4930 m_runswidth += m_swidthStep;
4931 if (m_swidthStep > 0)
4932 m_runswidth = wxMin(m_runswidth, m_fbo_swidth);
4933 else
4934 m_runswidth = wxMax(m_runswidth, m_fbo_swidth);
4935
4936 m_runsheight += m_sheightStep;
4937 if (m_sheightStep > 0)
4938 m_runsheight = wxMin(m_runsheight, m_fbo_sheight);
4939 else
4940 m_runsheight = wxMax(m_runsheight, m_fbo_sheight);
4941
4942 m_nRun += m_nStep;
4943 }
4944
4945 ZoomProject(m_runoffsetx, m_runoffsety, m_runswidth, m_runsheight);
4946
4947 } else {
4948 zoomTimer.Stop();
4949 if (m_zoomFinal) {
4950 m_pParentCanvas->ZoomCanvasSimple(m_zoomFinalZoom);
4951 if (m_zoomFinaldx || m_zoomFinaldy) {
4952 m_pParentCanvas->PanCanvas(m_zoomFinaldx, m_zoomFinaldy);
4953 }
4954 }
4955 m_zoomFinal = false;
4956 }
4957}
4958
4959void glChartCanvas::FastZoom(float factor, float cp_x, float cp_y, float post_x,
4960 float post_y) {
4961 int sx = GetSize().x;
4962 int sy = GetSize().y;
4963
4964 m_lastfbo_offsetx = m_fbo_offsetx;
4965 m_lastfbo_offsety = m_fbo_offsety;
4966 m_lastfbo_swidth = m_fbo_swidth;
4967 m_lastfbo_sheight = m_fbo_sheight;
4968
4969 float curr_fbo_offset_x = m_fbo_offsetx;
4970 float curr_fbo_offset_y = m_fbo_offsety;
4971 float curr_fbo_swidth = m_fbo_swidth;
4972 float curr_fbo_sheight = m_fbo_sheight;
4973
4974 float fx = (float)cp_x / sx;
4975 float fy = 1.0 - (float)cp_y / sy;
4976
4977 float fbo_ctr_x = curr_fbo_offset_x + (curr_fbo_swidth * fx);
4978 float fbo_ctr_y = curr_fbo_offset_y + (curr_fbo_sheight * fy);
4979
4980 m_fbo_swidth = curr_fbo_swidth / factor;
4981 m_fbo_sheight = curr_fbo_sheight / factor;
4982
4983 m_fbo_offsetx = fbo_ctr_x - (m_fbo_swidth * fx);
4984 m_fbo_offsety = fbo_ctr_y - (m_fbo_sheight * fy);
4985
4986 m_fbo_offsetx += post_x;
4987 m_fbo_offsety += post_y;
4988
4989 {
4990 m_nStep = 20;
4991 m_nTotal = 100;
4992
4993 // m_nStep = 10; // Android?
4994 // m_nTotal = 40;
4995
4996 m_nRun = 0;
4997
4998 float perStep = m_nStep / m_nTotal;
4999
5000 if (zoomTimer.IsRunning()) {
5001 m_offsetxStep = (m_fbo_offsetx - m_runoffsetx) * perStep;
5002 m_offsetyStep = (m_fbo_offsety - m_runoffsety) * perStep;
5003 m_swidthStep = (m_fbo_swidth - m_runswidth) * perStep;
5004 m_sheightStep = (m_fbo_sheight - m_runsheight) * perStep;
5005
5006 } else {
5007 m_offsetxStep = (m_fbo_offsetx - m_lastfbo_offsetx) * perStep;
5008 m_offsetyStep = (m_fbo_offsety - m_lastfbo_offsety) * perStep;
5009 m_swidthStep = (m_fbo_swidth - m_lastfbo_swidth) * perStep;
5010 m_sheightStep = (m_fbo_sheight - m_lastfbo_sheight) * perStep;
5011
5012 m_runoffsetx = m_lastfbo_offsetx;
5013 m_runoffsety = m_lastfbo_offsety;
5014 m_runswidth = m_lastfbo_swidth;
5015 m_runsheight = m_lastfbo_sheight;
5016 }
5017
5018 if (!zoomTimer.IsRunning()) zoomTimer.Start(m_nStep);
5019 m_zoomFinal = false;
5020 }
5021}
5022
5023#ifdef __ANDROID__
5024
5025void glChartCanvas::OnEvtPanGesture(wxQT_PanGestureEvent &event) {
5026 // qDebug() << "OnEvtPanGesture" << m_pParentCanvas->m_canvasIndex <<
5027 // event.cursor_pos.x;
5028
5029 if (m_pParentCanvas->isRouteEditing() || m_pParentCanvas->isMarkEditing())
5030 return;
5031
5032 if (m_binPinch) return;
5033 if (m_bpinchGuard) return;
5034
5035 int x = event.GetOffset().x;
5036 int y = event.GetOffset().y;
5037
5038 int lx = event.GetLastOffset().x;
5039 int ly = event.GetLastOffset().y;
5040
5041 int dx = lx - x;
5042 int dy = y - ly;
5043
5044 switch (event.GetState()) {
5045 case GestureStarted:
5046 if (m_binPan) break;
5047
5048 panx = pany = 0;
5049 m_binPan = true;
5050 m_binGesture = true;
5051 // qDebug() << "pg1";
5052 break;
5053
5054 case GestureUpdated:
5055 if (m_binPan) {
5056 if (!g_GLOptions.m_bUseCanvasPanning) {
5057 // qDebug() << "slowpan" << dx << dy;
5058
5059 m_pParentCanvas->FreezePiano();
5060 m_pParentCanvas->PanCanvas(dx, -dy);
5061 m_pParentCanvas->ThawPiano();
5062
5063 } else {
5064 FastPan(dx, dy);
5065 }
5066
5067 panx -= dx;
5068 pany -= dy;
5069 }
5070 break;
5071
5072 case GestureFinished:
5073 // qDebug() << "panGestureFinished";
5074
5075 m_pParentCanvas->UpdateCanvasControlBar();
5076
5077 m_binPan = false;
5078 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5079
5080 break;
5081
5082 case GestureCanceled:
5083 m_binPan = false;
5084 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5085 break;
5086
5087 default:
5088 break;
5089 }
5090
5091 m_bgestureGuard = true;
5092 m_gestureEeventTimer.Start(500, wxTIMER_ONE_SHOT);
5093 m_bforcefull = false;
5094
5095 // qDebug() << "panGestureDone";
5096}
5097
5098float zoom_inc = 1.0;
5099
5100void glChartCanvas::OnEvtPinchGesture(wxQT_PinchGestureEvent &event) {
5101 float zoom_gain = 1.0;
5102 float zout_gain = 1.0;
5103
5104 float zoom_val;
5105 float total_zoom_val;
5106
5107 float max_zoom_scale = 1000.;
5108 float min_zoom_scale = 2e8;
5109
5110 if (event.GetScaleFactor() > 1)
5111 zoom_val = ((event.GetScaleFactor() - 1.0) * zoom_gain) + 1.0;
5112 else
5113 zoom_val = 1.0 - ((1.0 - event.GetScaleFactor()) * zout_gain);
5114
5115 if (event.GetTotalScaleFactor() > 1)
5116 total_zoom_val = ((event.GetTotalScaleFactor() - 1.0) * zoom_gain) + 1.0;
5117 else
5118#if 0
5119 total_zoom_val = 1.0 - ((1.0 - event.GetTotalScaleFactor()) * zout_gain);
5120
5121 double projected_scale = cc1->GetVP().chart_scale / total_zoom_val;
5122
5123 // Max zoom in is set by scale of quilt reference chart, consistent with chart render limits set elsewhere.
5124 float max_zoom_scale = 1000.;
5125 if( cc1->GetVP().b_quilt) {
5126 int ref_index = cc1->GetQuiltRefChartdbIndex();
5127// if((ref_index >= 0) && ChartData){
5128// max_zoom_scale = ChartData->GetDBChartScale(ref_index) / 8.0;
5129// }
5130 }
5131
5132
5133 float min_zoom_scale = 2e8;
5134
5135#endif
5136
5137 total_zoom_val = 1.0 - ((1.0 - event.GetTotalScaleFactor()) * zoom_gain);
5138
5139 double projected_scale =
5140 m_pParentCanvas->GetVP().chart_scale / total_zoom_val;
5141
5142 switch (event.GetState()) {
5143 case GestureStarted:
5144 m_first_zout = false;
5145 m_binPinch = true;
5146 m_binPan = false; // cancel any tentative pan gesture, in case the "pan
5147 // cancel" event was lost
5148 m_binGesture = true;
5149 // qDebug() << "pg2";
5150 m_pinchStart = event.GetCenterPoint();
5151 m_lpinchPoint = m_pinchStart;
5152
5153 m_pParentCanvas->GetCanvasPixPoint(event.GetCenterPoint().x,
5154 event.GetCenterPoint().y, m_pinchlat,
5155 m_pinchlon);
5156 // qDebug() << "center" << event.GetCenterPoint().x <<
5157 // event.GetCenterPoint().y;
5158
5159 m_cc_x = m_fbo_offsetx + (m_fbo_swidth / 2);
5160 m_cc_y = m_fbo_offsety + (m_fbo_sheight / 2);
5161
5162 // Render the full charts with overlay objects onto the frame buffer.
5163 if (IsShown()) SetCurrent(*m_pcontext);
5164 RenderScene();
5165
5166 zoom_inc = 1.0;
5167 break;
5168
5169 case GestureUpdated:
5170 if (g_GLOptions.m_bUseCanvasPanning) {
5171 if (projected_scale < min_zoom_scale) {
5172 wxPoint pinchPoint = event.GetCenterPoint();
5173
5174 float dx = pinchPoint.x - m_lpinchPoint.x;
5175 float dy = pinchPoint.y - m_lpinchPoint.y;
5176
5177 FastZoom(zoom_val, m_pinchStart.x, m_pinchStart.y,
5178 -dx / total_zoom_val, dy / total_zoom_val);
5179
5180 m_lpinchPoint = pinchPoint;
5181 }
5182 } else {
5183 // qDebug() << "update totalzoom" << total_zoom_val << projected_scale;
5184 if (1 || ((total_zoom_val > 1) && !m_first_zout)) { // Zoom in
5185 wxPoint pinchPoint = event.GetCenterPoint();
5186
5187 float dx = pinchPoint.x - m_lpinchPoint.x;
5188 float dy = pinchPoint.y - m_lpinchPoint.y;
5189
5190 if ((projected_scale > max_zoom_scale) &&
5191 (projected_scale < min_zoom_scale))
5192 FastZoom(zoom_val, m_pinchStart.x, m_pinchStart.y,
5193 -dx / total_zoom_val, dy / total_zoom_val);
5194
5195 m_lpinchPoint = pinchPoint;
5196
5197 } else {
5198 m_first_zout = true;
5199 zoom_inc *= zoom_val;
5200 if ((zoom_inc < 0.9) || (zoom_inc > 1.1)) {
5201 m_pParentCanvas->ZoomCanvas(zoom_inc, false);
5202 zoom_inc = 1.0;
5203 }
5204
5205 wxPoint pinchPoint = event.GetCenterPoint();
5206 float dx = pinchPoint.x - m_lpinchPoint.x;
5207 float dy = pinchPoint.y - m_lpinchPoint.y;
5208 m_pParentCanvas->PanCanvas(-dx, -dy);
5209 m_lpinchPoint = pinchPoint;
5210
5211 // SetCurrent(*m_pcontext);
5212 // RenderScene();
5213 // g_Piano->DrawGL(cc1->m_canvas_height -
5214 // g_Piano->GetHeight()); SwapBuffers();
5215 }
5216 }
5217
5218 break;
5219
5220 case GestureFinished: {
5221 // qDebug() << "finish totalzoom" << total_zoom_val <<
5222 // projected_scale;
5223
5224 float cc_x = m_fbo_offsetx + (m_fbo_swidth / 2);
5225 float cc_y = m_fbo_offsety + (m_fbo_sheight / 2);
5226 float dy = 0;
5227 float dx = 0;
5228
5229 float tzoom = total_zoom_val;
5230
5231 if (projected_scale >= min_zoom_scale)
5232 tzoom = m_pParentCanvas->GetVP().chart_scale / min_zoom_scale;
5233
5234 if (projected_scale < max_zoom_scale)
5235 tzoom = m_pParentCanvas->GetVP().chart_scale / max_zoom_scale;
5236
5237 dx = (cc_x - m_cc_x) * tzoom;
5238 dy = -(cc_y - m_cc_y) * tzoom;
5239
5240 if (zoomTimer.IsRunning()) {
5241 // qDebug() << "Final zoom";
5242 m_zoomFinal = true;
5243 m_zoomFinalZoom = tzoom;
5244 m_zoomFinaldx = dx;
5245 m_zoomFinaldy = dy;
5246 }
5247
5248 else {
5249 double final_projected_scale =
5250 m_pParentCanvas->GetVP().chart_scale / tzoom;
5251 // qDebug() << "Final pinchB" << tzoom << final_projected_scale;
5252
5253 if (final_projected_scale < min_zoom_scale) {
5254 // qDebug() << "zoomit";
5255 m_pParentCanvas->ZoomCanvas(tzoom, false);
5256 m_pParentCanvas->PanCanvas(dx, dy);
5257 m_pParentCanvas->m_pQuilt->Invalidate();
5258 m_bforcefull = true;
5259
5260 } else {
5261 double new_scale =
5262 m_pParentCanvas->GetCanvasScaleFactor() / min_zoom_scale;
5263 // qDebug() << "clampit";
5264 m_pParentCanvas->SetVPScale(new_scale);
5265 m_pParentCanvas->m_pQuilt->Invalidate();
5266 m_bforcefull = true;
5267 }
5268 }
5269
5270 // if( projected_scale < 3e8)
5271 // m_pParentCanvas->ZoomCanvas( total_zoom_val, false
5272 // );
5273 // else
5274 // m_pParentCanvas->ZoomCanvas(m_pParentCanvas->GetVP().chart_scale
5275 // / 3e8, false);
5276
5277 m_binPinch = false;
5278 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5279 break;
5280 }
5281
5282 case GestureCanceled:
5283 m_binPinch = false;
5284 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5285 break;
5286
5287 default:
5288 break;
5289 }
5290
5291 m_bgestureGuard = true;
5292 // m_bpinchGuard = true;
5293 m_gestureEeventTimer.Start(500, wxTIMER_ONE_SHOT);
5294}
5295
5296void glChartCanvas::onGestureTimerEvent(wxTimerEvent &event) {
5297 // On some devices, the pan GestureFinished event fails to show up
5298 // Watch for this case, and fix it.....
5299 // qDebug() << "onGestureTimerEvent";
5300
5301 if (m_binPan) {
5302 m_binPan = false;
5303 Invalidate();
5304 Update();
5305 }
5306 m_bgestureGuard = false;
5307 m_bpinchGuard = false;
5308 m_binGesture = false;
5309 m_bforcefull = false;
5310}
5311
5312void glChartCanvas::onGestureFinishTimerEvent(wxTimerEvent &event) {
5313 // qDebug() << "onGestureFinishTimerEvent";
5314
5315 // signal gesture is finished after a delay
5316 m_binGesture = false;
5317 m_bforcefull = false;
5318}
5319
5320#else
5321#ifdef HAVE_WX_GESTURE_EVENTS
5322
5323void glChartCanvas::OnEvtPanGesture(wxPanGestureEvent &event) {
5324 // qDebug() << "OnEvtPanGesture" << m_pParentCanvas->m_canvasIndex <<
5325 // event.cursor_pos.x;
5326 if (m_pParentCanvas->isRouteEditing() || m_pParentCanvas->isMarkEditing())
5327 return;
5328
5329 if (m_binPinch) return;
5330 if (m_bpinchGuard) return;
5331
5332 int dx = event.GetDelta().x;
5333 int dy = event.GetDelta().y;
5334
5335 if (event.IsGestureStart()) {
5336 if (m_binPan) return;
5337
5338 panx = pany = 0;
5339 m_binPan = true;
5340 m_binGesture = true;
5341 // qDebug() << "pg1";
5342 }
5343
5344 else if (event.IsGestureEnd()) {
5345 // qDebug() << "panGestureFinished";
5346 m_pParentCanvas->UpdateCanvasControlBar();
5347 m_binPan = false;
5348 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5349 }
5350
5351 else {
5352 if (m_binPan) {
5353 if (!g_GLOptions.m_bUseCanvasPanning) {
5354 // qDebug() << "slowpan" << dx << dy;
5355
5356 m_pParentCanvas->FreezePiano();
5357 m_pParentCanvas->PanCanvas(dx, -dy);
5358 m_pParentCanvas->ThawPiano();
5359
5360 } else {
5361 FastPan(dx, dy);
5362 }
5363
5364 panx -= dx;
5365 pany -= dy;
5366 }
5367 }
5368
5369 m_bgestureGuard = true;
5370 m_gestureEeventTimer.Start(500, wxTIMER_ONE_SHOT);
5371 m_bforcefull = false;
5372}
5373
5374// Generic wxWidgets gesture event processor
5375void glChartCanvas::OnEvtZoomGesture(wxZoomGestureEvent &event) {
5376 if (g_true_zoom) {
5377 float zoom_gain = 1.0;
5378 float zout_gain = 1.0;
5379
5380 float last_zoom_val = m_step_zoom_val; // m_total_zoom_val;
5381
5382 float max_zoom_scale = 1000.;
5383 float min_zoom_scale = 2e8;
5384
5385 if (event.GetZoomFactor() > 1)
5386 m_total_zoom_val = ((event.GetZoomFactor() - 1.0) * zoom_gain) + 1.0;
5387 else
5388 m_total_zoom_val = 1.0 - ((1.0 - event.GetZoomFactor()) * zout_gain);
5389
5390 float inc_zoom_val =
5391 m_total_zoom_val / last_zoom_val; // the incremental zoom
5392
5393 double projected_scale = m_cache_vp.chart_scale;
5394
5395 if (event.IsGestureStart()) {
5396 m_glstopwatch.Start();
5397 printf("\nStart--------------\n");
5398 m_binPinch = true;
5399 m_pParentCanvas->m_inPinch = true;
5400 m_binPan = false; // cancel any tentative pan gesture, in case the "pan
5401 // cancel" event was lost
5402 m_binGesture = true;
5403 m_pinchStart = event.GetPosition();
5404 m_lpinchPoint = m_pinchStart;
5405 m_total_zoom_val = 1.0;
5406 m_final_zoom_val = 1.0;
5407 m_step_zoom_val = 1.0;
5408
5409 // Capture the lat/lon of the "pinch-point"
5410 m_pParentCanvas->GetCanvasPixPoint(
5411 event.GetPosition().x, event.GetPosition().y, m_pinchlat, m_pinchlon);
5412 m_zoom_inc = 1.0;
5413 }
5414
5415 if (event.IsGestureEnd()) {
5416 // Some platforms generate spurious gestureEnd events. Guard for this.
5417 if (!m_binGesture) return;
5418 printf("EndZoom--------------\n");
5419
5420 Refresh();
5421
5422 // Let the gesture finish timer (500 msec) signal the pinch is done.
5423 // this will allow any lingering drag operation to avoid starting the
5424 // inertial drag process
5425 m_final_zoom_val = 1.0;
5426 m_total_zoom_val = 1.0;
5427 m_step_zoom_val = 1.0;
5428
5429 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5430 }
5431
5432 else {
5433 // printf("%ld %6g %6g %6g \n", g_glstopwatch.Time(),
5434 // event.GetZoomFactor(),
5435 // inc_zoom_val, projected_scale);
5436 float zoom_step = 5;
5437 float zoom_trigger = 0.05;
5438 if (projected_scale > 1e5)
5439 zoom_trigger = .1;
5440 else if (projected_scale < 3e4)
5441 zoom_trigger = .02;
5442
5443 if (inc_zoom_val != 1.0) {
5444 if (inc_zoom_val > 1 + zoom_step) {
5445 m_step_zoom_val = m_step_zoom_val * (1 + zoom_step);
5446 printf(" Partial zoom: %6g\n", 1 + zoom_step);
5447 m_pParentCanvas->ZoomCanvasSimple(1 + zoom_step);
5448 if (IsShown()) SetCurrent(*m_pcontext);
5449 Render();
5450 } else {
5451 if (fabs(inc_zoom_val - 1.) > zoom_trigger) {
5452 m_step_zoom_val = m_total_zoom_val;
5453 printf(" Zoom: %6g\n", inc_zoom_val);
5454 m_pParentCanvas->ZoomCanvasSimple(inc_zoom_val);
5455
5456 // Consider "zoom to pinch-point"
5457 // Disable ZTC if lookahead is ON, and currently b_follow is active
5458 bool b_allow_ztp = true;
5459 if (m_pParentCanvas->m_bFollow && m_pParentCanvas->m_bLookAhead)
5460 b_allow_ztp = false;
5461
5462 if (g_bEnableZoomToCursor && b_allow_ztp) {
5463 // get the new (after zoom) pixel position of the original
5464 // pinch-point
5465 wxPoint r;
5466 m_pParentCanvas->GetCanvasPointPix(m_pinchlat, m_pinchlon, &r);
5467 // Shift the canvas to follow the pinch-lat/lon
5468 int dx = r.x - event.GetPosition().x;
5469 int dy = r.y - event.GetPosition().y;
5470 m_pParentCanvas->PanCanvas(dx, dy);
5471 }
5472
5473 if (IsShown()) SetCurrent(*m_pcontext);
5474 Render();
5475 }
5476 }
5477 }
5478 }
5479 } // true-zoom
5480 else {
5481 // Legacy zoom behavior
5482 float zoom_gain = 1.0;
5483 float zout_gain = 1.0;
5484
5485 float last_zoom_val = m_total_zoom_val;
5486
5487 float max_zoom_scale = 1000.;
5488 float min_zoom_scale = 2e8;
5489
5490 if (event.GetZoomFactor() > 1)
5491 m_total_zoom_val = ((event.GetZoomFactor() - 1.0) * zoom_gain) + 1.0;
5492 else
5493 m_total_zoom_val = 1.0 - ((1.0 - event.GetZoomFactor()) * zout_gain);
5494
5495 float inc_zoom_val =
5496 m_total_zoom_val / last_zoom_val; // the incremental zoom
5497
5498 double projected_scale =
5499 m_pParentCanvas->GetVP().chart_scale / m_total_zoom_val;
5500
5501 if (event.IsGestureStart()) {
5502 // printf("\nStart--------------\n");
5503 m_first_zout = false;
5504 m_binPinch = true;
5505 m_binPan = false; // cancel any tentative pan gesture, in case the "pan
5506 // cancel" event was lost
5507 m_binGesture = true;
5508 m_pinchStart = event.GetPosition();
5509 m_lpinchPoint = m_pinchStart;
5510 m_total_zoom_val = 1.0;
5511 m_final_zoom_val = 1.0;
5512
5513 m_pParentCanvas->GetCanvasPixPoint(
5514 event.GetPosition().x, event.GetPosition().y, m_pinchlat, m_pinchlon);
5515 // qDebug() << "center" << event.GetCenterPoint().x <<
5516 // event.GetCenterPoint().y;
5517
5518 m_cc_x = m_fbo_offsetx + (m_fbo_swidth / 2);
5519 m_cc_y = m_fbo_offsety + (m_fbo_sheight / 2);
5520
5521 // Render the full charts with overlay objects onto the frame buffer.
5522 if (IsShown()) SetCurrent(*m_pcontext);
5523 RenderScene();
5524#ifndef __ANDROID__
5525 ViewPort vpr = m_pParentCanvas->VPoint;
5526 m_texVP = vpr;
5527 GetTouchBackingBitmap(vpr);
5528#endif
5529 m_zoom_inc = 1.0;
5530 }
5531
5532 if (event.IsGestureEnd()) {
5533 // printf("End--------------\n");
5534 // qDebug() << "finish totalzoom" << total_zoom_val <<
5535 // projected_scale;
5536
5537 // Some ptaforms generate spurious gestureEnd events. Guard for this.
5538 if (!m_binGesture) return;
5539
5540 float cc_x = m_fbo_offsetx + (m_fbo_swidth / 2);
5541 float cc_y = m_fbo_offsety + (m_fbo_sheight / 2);
5542 float dy = 0;
5543 float dx = 0;
5544
5545 float tzoom = m_final_zoom_val;
5546
5547 dx = (cc_x - m_cc_x) * tzoom;
5548 dy = -(cc_y - m_cc_y) * tzoom;
5549
5550 if (zoomTimer.IsRunning()) {
5551 // qDebug() << "Final zoom";
5552 m_zoomFinal = true;
5553 m_zoomFinalZoom = tzoom;
5554 m_zoomFinaldx = dx;
5555 m_zoomFinaldy = dy;
5556 }
5557
5558 else {
5559 double final_projected_scale =
5560 m_pParentCanvas->GetVP().chart_scale / tzoom;
5561 // qDebug() << "Final pinchB" << tzoom << final_projected_scale;
5562
5563 if (final_projected_scale < min_zoom_scale) {
5564 // qDebug() << "zoomit";
5565 m_pParentCanvas->ZoomCanvas(tzoom, false);
5566 m_pParentCanvas->PanCanvas(dx, dy);
5567 m_pParentCanvas->m_pQuilt->Invalidate();
5568 m_bforcefull = true;
5569
5570 } else {
5571 double new_scale =
5572 m_pParentCanvas->GetCanvasScaleFactor() / min_zoom_scale;
5573 // qDebug() << "clampit";
5574 m_pParentCanvas->SetVPScale(new_scale);
5575 m_pParentCanvas->m_pQuilt->Invalidate();
5576 m_bforcefull = true;
5577 }
5578 }
5579
5580 m_binPinch = false;
5581 m_final_zoom_val = 1.0;
5582 m_total_zoom_val = 1.0;
5583 m_gestureFinishTimer.Start(500, wxTIMER_ONE_SHOT);
5584 }
5585
5586 else {
5587 if (1 /* g_GLOptions.m_bUseCanvasPanning*/) {
5588 if (projected_scale < min_zoom_scale) {
5589 wxPoint pinchPoint = event.GetPosition();
5590
5591 float dx = pinchPoint.x - m_lpinchPoint.x;
5592 float dy = pinchPoint.y - m_lpinchPoint.y;
5593
5594 FastZoom(inc_zoom_val, m_pinchStart.x, m_pinchStart.y,
5595 -dx / m_total_zoom_val, dy / m_total_zoom_val);
5596
5597 m_lpinchPoint = pinchPoint;
5598 m_final_zoom_val *= inc_zoom_val;
5599 }
5600 } else {
5601 // qDebug() << "update totalzoom" << total_zoom_val << projected_scale;
5602 if (1 || ((m_total_zoom_val > 1) && !m_first_zout)) { // Zoom in
5603 wxPoint pinchPoint = event.GetPosition();
5604
5605 float dx = pinchPoint.x - m_lpinchPoint.x;
5606 float dy = pinchPoint.y - m_lpinchPoint.y;
5607
5608 if ((projected_scale > max_zoom_scale) &&
5609 (projected_scale < min_zoom_scale))
5610 FastZoom(inc_zoom_val, m_pinchStart.x, m_pinchStart.y,
5611 -dx / m_total_zoom_val, dy / m_total_zoom_val);
5612
5613 m_lpinchPoint = pinchPoint;
5614 m_final_zoom_val *= inc_zoom_val;
5615
5616 } else {
5617 m_first_zout = true;
5618 m_zoom_inc *= inc_zoom_val;
5619 if ((m_zoom_inc < 0.9) || (m_zoom_inc > 1.1)) {
5620 m_pParentCanvas->ZoomCanvas(m_zoom_inc, false);
5621 m_zoom_inc = 1.0;
5622 }
5623
5624 wxPoint pinchPoint = event.GetPosition();
5625 float dx = pinchPoint.x - m_lpinchPoint.x;
5626 float dy = pinchPoint.y - m_lpinchPoint.y;
5627 m_pParentCanvas->PanCanvas(-dx, -dy);
5628 m_lpinchPoint = pinchPoint;
5629 }
5630 }
5631 }
5632 m_gestureEeventTimer.Start(500, wxTIMER_ONE_SHOT);
5633 }
5634
5635 m_bgestureGuard = true;
5636 m_bpinchGuard = true;
5637}
5638
5639void glChartCanvas::onGestureTimerEvent(wxTimerEvent &event) {
5640 // On some devices, the pan GestureFinished event fails to show up
5641 // Watch for this case, and fix it.....
5642
5643 if (m_binPan) {
5644 m_binPan = false;
5645 Invalidate();
5646 Update();
5647 }
5648 m_bgestureGuard = false;
5649 m_bpinchGuard = false;
5650 m_binGesture = false;
5651 m_bforcefull = false;
5652}
5653
5654void glChartCanvas::onGestureFinishTimerEvent(wxTimerEvent &event) {
5655 // qDebug() << "onGestureFinishTimerEvent";
5656
5657 // signal gesture is finished after a delay
5658 m_binGesture = false;
5659 m_bforcefull = false;
5660 m_binPinch = false;
5661 m_pParentCanvas->m_inPinch = false;
5662 printf("******Finish\n");
5663}
5664
5665#endif
5666#endif
5667
5668void glChartCanvas::configureShaders(ViewPort &vp) {
5669#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
5670 mat4x4 I;
5671 mat4x4_identity(I);
5672
5673 ViewPort *pvp = (ViewPort *)&vp;
5674
5675 GLShaderProgram *shader = pcolor_tri_shader_program[GetCanvasIndex()];
5676 shader->Bind();
5677 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5678 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
5679 shader->UnBind();
5680
5681 // glUseProgram(color_tri_shader_program);
5682 // GLint matloc = glGetUniformLocation(color_tri_shader_program,
5683 // "MVMatrix"); glUniformMatrix4fv(matloc, 1, GL_FALSE,
5684 // (const GLfloat *)pvp->vp_transform);
5685 // GLint transloc =
5686 // glGetUniformLocation(color_tri_shader_program,
5687 // "TransformMatrix");
5688 // glUniformMatrix4fv(transloc, 1, GL_FALSE, (const GLfloat *)I);
5689
5690 // glUseProgram(texture_2D_shader_program);
5691 // matloc = glGetUniformLocation(texture_2D_shader_program, "MVMatrix");
5692 // glUniformMatrix4fv(matloc, 1, GL_FALSE,
5693 // (const GLfloat *)pvp->vp_transform);
5694 // transloc =
5695 // glGetUniformLocation(texture_2D_shader_program,
5696 // "TransformMatrix");
5697 // glUniformMatrix4fv(transloc, 1, GL_FALSE, (const GLfloat *)I);
5698
5699 shader = ptexture_2D_shader_program[GetCanvasIndex()];
5700 shader->Bind();
5701 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5702 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
5703 shader->UnBind();
5704
5705 // glUseProgram(circle_filled_shader_program);
5706 // matloc = glGetUniformLocation(circle_filled_shader_program,
5707 // "MVMatrix"); glUniformMatrix4fv(matloc, 1, GL_FALSE,
5708 // (const GLfloat *)pvp->vp_transform);
5709 // transloc =
5710 // glGetUniformLocation(circle_filled_shader_program,
5711 // "TransformMatrix");
5712 // glUniformMatrix4fv(transloc, 1, GL_FALSE, (const GLfloat *)I);
5713
5714 shader = pcircle_filled_shader_program[GetCanvasIndex()];
5715 shader->Bind();
5716 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5717 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
5718 shader->UnBind();
5719
5720 shader = ptexture_2DA_shader_program[GetCanvasIndex()];
5721 shader->Bind();
5722 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5723 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
5724 shader->UnBind();
5725
5726 // glUseProgram(AALine_shader_program);
5727 // matloc = glGetUniformLocation(AALine_shader_program, "MVMatrix");
5728 // glUniformMatrix4fv(matloc, 1, GL_FALSE,
5729 // (const GLfloat *)pvp->vp_transform);
5730
5731 shader = pAALine_shader_program[GetCanvasIndex()];
5732 shader->Bind();
5733 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5734 shader->UnBind();
5735
5736 shader = pring_shader_program[GetCanvasIndex()];
5737 shader->Bind();
5738 shader->SetUniformMatrix4fv("MVMatrix", (GLfloat *)pvp->vp_matrix_transform);
5739 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)I);
5740 shader->UnBind();
5741
5742 // Leftover shader required by some older Android plugins
5743 if (texture_2DA_shader_program) {
5744 glUseProgram(texture_2DA_shader_program);
5745 GLint matloc = glGetUniformLocation(texture_2DA_shader_program, "MVMatrix");
5746 glUniformMatrix4fv(matloc, 1, GL_FALSE,
5747 (const GLfloat *)pvp->vp_matrix_transform);
5748 GLint transloc =
5749 glGetUniformLocation(texture_2DA_shader_program, "TransformMatrix");
5750 glUniformMatrix4fv(transloc, 1, GL_FALSE, (const GLfloat *)I);
5751 }
5752
5753 m_gldc.m_texfont.PrepareShader(vp.pix_width, vp.pix_height, vp.rotation);
5754
5755#endif
5756}
5757
5758void glChartCanvas::RenderTextures(ocpnDC &dc, float *coords, float *uvCoords,
5759 int nVertex, ViewPort *vp) {
5760// #ifdef USE_ANDROID_GLES2
5761#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
5762 int nl = nVertex / 4;
5763 float *lc = coords;
5764 float *luv = uvCoords;
5765
5766 while (nl) {
5767 RenderSingleTexture(dc, lc, luv, vp, 0, 0, 0);
5768
5769 lc += 8;
5770 luv += 8;
5771 nl--;
5772 }
5773
5774#else
5775 glEnableClientState(GL_VERTEX_ARRAY);
5776 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
5777
5778 glTexCoordPointer(2, GL_FLOAT, 2 * sizeof(GLfloat), uvCoords);
5779 glVertexPointer(2, GL_FLOAT, 2 * sizeof(GLfloat), coords);
5780 glDrawArrays(GL_QUADS, 0, 4);
5781
5782#endif
5783
5784 return;
5785}
5786
5787void glChartCanvas::RenderSingleTexture(ocpnDC &dc, float *coords,
5788 float *uvCoords, ViewPort *vp, float dx,
5789 float dy, float angle_rad) {
5790#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
5791
5792 GLShaderProgram *shader = ptexture_2D_shader_program[dc.m_canvasIndex];
5793 if (!shader) return;
5794
5795 shader->Bind();
5796
5797 // Set up the texture sampler to texture unit 0
5798 shader->SetUniform1i("uTex", 0);
5799
5800 // Rotate
5801 mat4x4 I, Q;
5802 mat4x4_identity(I);
5803 mat4x4_rotate_Z(Q, I, angle_rad);
5804
5805 // Translate
5806 Q[3][0] = dx;
5807 Q[3][1] = dy;
5808
5809 shader->SetUniformMatrix4fv("TransformMatrix", (GLfloat *)Q);
5810
5811 float co1[8];
5812 float tco1[8];
5813
5814 shader->SetAttributePointerf("aPos", co1);
5815 shader->SetAttributePointerf("aUV", tco1);
5816
5817// Perform the actual drawing.
5818
5819// For some reason, glDrawElements is busted on Android
5820// So we do this a hard ugly way, drawing two triangles...
5821#if 0
5822 GLushort indices1[] = {0,1,3,2};
5823 glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, indices1);
5824#else
5825
5826 co1[0] = coords[0];
5827 co1[1] = coords[1];
5828 co1[2] = coords[2];
5829 co1[3] = coords[3];
5830 co1[4] = coords[6];
5831 co1[5] = coords[7];
5832 co1[6] = coords[4];
5833 co1[7] = coords[5];
5834
5835 tco1[0] = uvCoords[0];
5836 tco1[1] = uvCoords[1];
5837 tco1[2] = uvCoords[2];
5838 tco1[3] = uvCoords[3];
5839 tco1[4] = uvCoords[6];
5840 tco1[5] = uvCoords[7];
5841 tco1[6] = uvCoords[4];
5842 tco1[7] = uvCoords[5];
5843
5844 // glVertexAttribPointer(mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, co1);
5845 // glVertexAttribPointer(mUvAttrib, 2, GL_FLOAT, GL_FALSE, 0, tco1);
5846
5847 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
5848
5849 shader->UnBind();
5850
5851#endif
5852
5853#else
5854#endif
5855
5856 return;
5857}
5858
5859void glChartCanvas::RenderColorRect(wxRect r, wxColor &color) {
5860#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
5861
5862 GLShaderProgram *shader = pcolor_tri_shader_program[GetCanvasIndex()];
5863 shader->Bind();
5864
5865 shader->SetUniformMatrix4fv(
5866 "MVMatrix", (GLfloat *)m_pParentCanvas->GetpVP()->vp_matrix_transform);
5867
5868 float colorv[4];
5869 colorv[0] = color.Red() / float(256);
5870 colorv[1] = color.Green() / float(256);
5871 colorv[2] = color.Blue() / float(256);
5872 colorv[3] = 1.0;
5873 shader->SetUniform4fv("color", colorv);
5874
5875 float pf[8];
5876 pf[0] = r.x + r.width;
5877 pf[1] = r.y;
5878 pf[2] = r.x;
5879 pf[3] = r.y;
5880 pf[4] = r.x + r.width;
5881 pf[5] = r.y + r.height;
5882 pf[6] = r.x;
5883 pf[7] = r.y + r.height;
5884 shader->SetAttributePointerf("position", pf);
5885
5886 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
5887
5888 shader->UnBind();
5889
5890#else
5891#endif
5892}
5893
5894void glChartCanvas::RenderScene(bool bRenderCharts, bool bRenderOverlays) {
5895#if defined(USE_ANDROID_GLES2) || defined(ocpnUSE_GLSL)
5896
5897 ViewPort VPoint = m_pParentCanvas->VPoint;
5898 ocpnDC gldc(*this);
5899
5900 int w, h;
5901 GetClientSize(&w, &h);
5902 int sx = GetSize().x;
5903 int sy = GetSize().y;
5904
5905 OCPNRegion screen_region(wxRect(0, 0, VPoint.pix_width, VPoint.pix_height));
5906
5907 glViewport(0, 0, (GLint)w, (GLint)h);
5908
5909 if (s_b_useStencil) {
5910 glEnable(GL_STENCIL_TEST);
5911 glStencilMask(0xff);
5912 glClear(GL_STENCIL_BUFFER_BIT);
5913 glDisable(GL_STENCIL_TEST);
5914 }
5915
5916 // Make sure we have a valid quilt composition
5917 m_pParentCanvas->m_pQuilt->Compose(m_pParentCanvas->VPoint);
5918
5919 // set opengl settings that don't normally change
5920 // this should be able to go in SetupOpenGL, but it's
5921 // safer here incase a plugin mangles these
5922 glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
5923 glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
5924 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5925
5926 // enable rendering to texture in framebuffer object
5927 glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fb0);
5928
5929 glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0,
5930 g_texture_rectangle_format, m_cache_tex[m_cache_page],
5931 0);
5932
5933 m_fbo_offsetx = 0;
5934 m_fbo_offsety = 0;
5935 m_fbo_swidth = sx;
5936 m_fbo_sheight = sy;
5937
5938 if (bRenderCharts) RenderCharts(gldc, screen_region);
5939
5940 if (bRenderOverlays) {
5941 RenderS57TextOverlay(m_pParentCanvas->VPoint);
5942 RenderMBTilesOverlay(m_pParentCanvas->VPoint);
5943 g_overlayCanvas = m_pParentCanvas;
5944
5945 if (g_pi_manager) {
5946 g_pi_manager->SendViewPortToRequestingPlugIns(VPoint);
5947 g_pi_manager->RenderAllGLCanvasOverlayPlugIns(
5948 m_pcontext, VPoint, m_pParentCanvas->m_canvasIndex, OVERLAY_CHARTS);
5949 }
5950
5951 DrawStaticRoutesTracksAndWaypoints(m_pParentCanvas->VPoint);
5952 DrawDynamicRoutesTracksAndWaypoints(VPoint);
5953 DrawFloatingOverlayObjects(m_gldc);
5954 }
5955
5956 // All done, so disable Render to FBO
5957 glBindFramebuffer(GL_FRAMEBUFFER, 0);
5958
5959#endif
5960}
5961
5962wxBitmap &glChartCanvas::GetTouchBackingBitmap(ViewPort &vp) {
5963 wxBitmap tbm(vp.pix_width, vp.pix_height, -1);
5964 wxMemoryDC tdc(tbm);
5965 tdc.SetBackground(wxBrush(GetGlobalColor("BLUEBACK")));
5966 tdc.Clear();
5967 ocpnDC dc = ocpnDC(tdc);
5968 ViewPort tvp = vp;
5969
5970 tvp.view_scale_ppm /= 2;
5971 tvp.SetBoxes();
5972
5973 gShapeBasemap.SetBasemapLandColor(GetGlobalColor("LANDBACK"));
5974 dc.SetPen(*wxTRANSPARENT_PEN);
5975
5976 gShapeBasemap.RenderViewOnDC(dc, tvp);
5977 tdc.SelectObject(wxNullBitmap);
5978 m_touch_backing_bitmap = tbm;
5979 CreateBackingTexture();
5980
5981 return m_touch_backing_bitmap;
5982}
5983
5984void glChartCanvas::CreateBackingTexture() {
5985 wxImage image = m_touch_backing_bitmap.ConvertToImage();
5986 unsigned char *imgdata = image.GetData();
5987 unsigned char *imgalpha = image.GetAlpha();
5988 m_tex_w = image.GetWidth();
5989 m_tex_h = image.GetHeight();
5990 m_image_width = m_tex_w;
5991 m_image_height = m_tex_h;
5992
5993 GLuint format = GL_RGBA;
5994 GLuint internalformat = g_texture_rectangle_format;
5995#ifndef __ANDROID__
5996 internalformat = GL_RGBA;
5997#endif
5998 int stride = 4;
5999
6000 if (imgdata) {
6001 unsigned char *teximage =
6002 (unsigned char *)malloc(stride * m_tex_w * m_tex_h);
6003
6004 for (int i = 0; i < m_image_height; i++) {
6005 for (int j = 0; j < m_image_width; j++) {
6006 int s = (i * 3 * m_image_width) + (j * 3);
6007 int d = (i * stride * m_tex_w) + (j * stride);
6008
6009 teximage[d + 0] = imgdata[s + 0];
6010 teximage[d + 1] = imgdata[s + 1];
6011 teximage[d + 2] = imgdata[s + 2];
6012 teximage[d + 3] = 255;
6013 }
6014 }
6015
6016 glGenTextures(1, &m_TouchBackingTexture);
6017 glBindTexture(GL_TEXTURE_2D, m_TouchBackingTexture);
6018
6019 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
6020 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
6021 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
6022 GL_NEAREST); // No mipmapping
6023 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
6024
6025 glTexImage2D(GL_TEXTURE_2D, 0, internalformat, m_tex_w, m_tex_h, 0, format,
6026 GL_UNSIGNED_BYTE, teximage);
6027
6028 free(teximage);
6029 glBindTexture(GL_TEXTURE_2D, 0);
6030 }
6031}
BasePlatform * g_BasePlatform
points to g_platform, handles brain-dead MS linker.
Basic platform specific support utilities without GUI deps.
bool GetMemoryStatus(int *mem_total, int *mem_used)
Return total system RAM and size of program Values returned are in kilobytes.
Chart info panel.
Wrapper for creating a ChartCtx based on global vars.
General chart base definitions.
ChartDB * ChartData
Global instance.
Definition chartdb.cpp:71
Charts database management
BSB chart management.
ChartCanvas * g_focusCanvas
Global instance.
Definition chcanv.cpp:1316
ChartCanvas * g_overlayCanvas
Global instance.
Definition chcanv.cpp:1315
Generic Chart canvas base.
double GetDisplayDIPMult(wxWindow *win)
Get the display scaling factor for DPI-aware rendering.
Base class for all chart types.
Definition chartbase.h:126
ChartCanvas - Main chart display and interaction component.
Definition chcanv.h:174
wxFont * FindOrCreateFont(int point_size, wxFontFamily family, wxFontStyle style, wxFontWeight weight, bool underline=false, const wxString &facename=wxEmptyString, wxFontEncoding encoding=wxFONTENCODING_DEFAULT)
Creates or finds a matching font in the font cache.
Definition font_mgr.cpp:442
wxFont * GetFont(const wxString &TextElement, int requested_font_size=0)
Get a font object for a UI element.
Definition font_mgr.cpp:193
Wrapper class for OpenGL shader programs.
Definition shaders.h:57
char IDX_type
Entry type identifier "TCtcIUu".
Definition idx_entry.h:60
double IDX_lat
Latitude of the station (in degrees, +North).
Definition idx_entry.h:64
double IDX_lon
Longitude of the station (in degrees, +East).
Definition idx_entry.h:63
An iterator class for OCPNRegion.
A wrapper class for wxRegion with additional functionality.
Definition ocpn_region.h:37
ViewPort - Core geographic projection and coordinate transformation engine.
Definition viewport.h:56
void SetBoxes()
Computes the bounding box coordinates for the current viewport.
Definition viewport.cpp:809
double view_scale_ppm
Requested view scale in physical pixels per meter (ppm), before applying projections.
Definition viewport.h:204
double ref_scale
The nominal scale of the "reference chart" for this view.
Definition viewport.h:221
int pix_height
Height of the viewport in physical pixels.
Definition viewport.h:233
double rotation
Rotation angle of the viewport in radians.
Definition viewport.h:214
int pix_width
Width of the viewport in physical pixels.
Definition viewport.h:231
wxPoint2DDouble GetDoublePixFromLL(double lat, double lon)
Convert latitude and longitude on the ViewPort to physical pixel coordinates with double precision.
Definition viewport.cpp:133
double tilt
Tilt angle for perspective view in radians.
Definition viewport.h:216
double skew
Angular distortion (shear transform) applied to the viewport in radians.
Definition viewport.h:212
void GetLLFromPix(const wxPoint &p, double *lat, double *lon)
Convert physical pixel coordinates on the ViewPort to latitude and longitude.
Definition viewport.h:80
double clon
Center longitude of the viewport in degrees.
Definition viewport.h:199
double clat
Center latitude of the viewport in degrees.
Definition viewport.h:197
wxPoint GetPixFromLL(double lat, double lon)
Convert latitude and longitude on the ViewPort to physical pixel coordinates.
Definition viewport.cpp:124
double chart_scale
Chart scale denominator (e.g., 50000 for a 1:50000 scale).
Definition viewport.h:219
Stores emboss effect data for textures.
Definition emboss_data.h:34
OpenGL chart rendering canvas.
Device context class that can use either wxDC or OpenGL for drawing.
Definition ocpndc.h:60
void DrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, bool b_hiqual=true)
Draw a line between two points using either wxDC or OpenGL.
Definition ocpndc.cpp:473
bool m_bUseCanvasPanning
Controls OpenGL canvas hardware-accelerated panning mode.
Class cm93chart and helpers – CM93 chart state.
Global color handling by name.
Global variables stored in configuration file.
Texture emboss effects storage.
Font list manager.
bool g_running
Android only.
GLuint g_raster_format
Global instance.
OpenGL chart rendering canvas.
glTextureManager * g_glTextureManager
Global instance.
GLuint g_raster_format
Global instance.
OpenGL texture cache.
GSHHS Chart Object (Global Self-consistent, Hierarchical, High-resolution Shoreline) Derived from htt...
wxFont * GetOCPNScaledFont(wxString item, int default_size)
Retrieves a font from FontMgr, optionally scaled for physical readability.
Definition gui_lib.cpp:61
int g_mipmap_max_level
Global instance.
Definition gui_vars.cpp:87
bool b_inCompressAllCharts
Flag to control adaptive UI scaling.
Definition gui_vars.cpp:35
Miscellaneous globals primarely used by gui layer, not persisted in configuration file.
iENCToolbar * g_iENCToolbar
Global instance.
iENC specific chart operations floating toolbar extension
MUI (Modern User Interface) Control bar.
Utility functions.
User notifications manager.
OpenCPN Platform specific support utilities.
#define OVERLAY_CHARTS
Lowest priority for overlays to render above all basic charts.
#define OVERLAY_LEGACY
Overlay rendering priorities determine the layering order of plugin graphics.
#define OVERLAY_OVER_UI
Highest priority for overlays above all UI elements.
#define OVERLAY_OVER_EMBOSS
Priority for overlays above embossed chart features.
#define OVERLAY_OVER_SHIPS
Priority for overlays that should appear above ship symbols.
double OCPN_GetDisplayContentScaleFactor()
Gets content scaling factor for current display.
int GetChartbarHeight()
Gets height of chart bar in pixels.
double gHdt
True heading in degrees (0-359.99).
Definition own_ship.cpp:30
double gLat
Vessel's current latitude in decimal degrees.
Definition own_ship.cpp:26
double gCog
Course over ground in degrees (0-359.99).
Definition own_ship.cpp:28
double gSog
Speed over ground in knots.
Definition own_ship.cpp:29
double gLon
Vessel's current longitude in decimal degrees.
Definition own_ship.cpp:27
Position, course, speed, etc.
Chart Bar Window.
Tools to send data to plugins.
PlugInManager * g_pi_manager
Global instance.
PlugInManager and helper classes – Mostly gui parts (dialogs) and plugin API stuff.
Chart quilt support.
Route abstraction.
Route drawing stuff.
Purpose: Track and Trackpoint drawing stuff.
Routeman * g_pRouteMan
Global instance.
Definition routeman.cpp:60
RouteList * pRouteList
Global instance.
Definition routeman.cpp:66
float g_ChartScaleFactorExp
Global instance.
Definition routeman.cpp:68
Route Manager.
S57 Chart Object.
OpenGL shader interface.
ShapeBaseChartSet gShapeBasemap
global instance
Shapefile basemap.
TCMgr * ptcmgr
Global instance.
Definition tcmgr.cpp:42
Tide and Current Manager @TODO Add original author copyright.
Chart thumbnail object.
ocpnFloatingToolbarDialog * g_MainToolbar
Global instance.
Definition toolbar.cpp:66
OpenCPN Toolbar.
std::vector< Track * > g_TrackList
Global instance.
Definition track.cpp:97
Recorded track abstraction.
Track and Trackpoint drawing stuff.
Geographic projection and coordinate transformations.