OpenCPN Partial API docs
Loading...
Searching...
No Matches
gl_texture_mgr.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2016 by David S. Register *
3 * Copyright (C) 2016 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#include <algorithm>
26#include <list>
27#include <vector>
28
29#include <wx/wxprec.h>
30#include <wx/progdlg.h>
31#include <wx/wx.h>
32#include <wx/thread.h>
33
34#if defined(__ANDROID__)
35#include <GLES2/gl2.h>
36#elif defined(__WXQT__) || defined(__WXGTK__)
37#include <GL/glew.h>
38#endif
39
40#include <wx/datetime.h>
41#include <wx/event.h>
42#include <wx/filename.h>
43#include <wx/font.h>
44#include <wx/gdicmn.h>
45#include <wx/log.h>
46#include <wx/progdlg.h>
47#include <wx/stopwatch.h>
48#include <wx/string.h>
49#include <wx/thread.h>
50#include <wx/utils.h>
51
52#include <wx/listimpl.cpp>
53#include <wx/arrimpl.cpp>
54
55#include "mipmap/mipmap.h"
56#include "ssl/sha1.h"
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
63#include "chartbase.h"
64#include "chartdb.h"
65#include "chartimg.h"
66#include "chcanv.h"
67#include "dychart.h"
68#include "font_mgr.h"
69#include "gl_chart_canvas.h"
70#include "gl_tex_cache.h"
71#include "gl_texture_descr.h"
72#include "gui_lib.h"
73#include "lz4.h"
74#include "lz4hc.h"
75#include "ocpn_platform.h"
76#include "quilt.h"
77#include "squish.h"
78#include "top_frame.h"
79#include "viewport.h"
80
81#ifndef GL_ETC1_RGB8_OES
82#define GL_ETC1_RGB8_OES 0x8D64
83#endif
84
85using JobList = std::list<JobTicket *>;
86
87extern GLuint g_raster_format; // FIXME (leamas) Find a home
88
90
91static bool bthread_debug;
92
93wxString CompressedCachePath(wxString path) {
94#if defined(__WXMSW__)
95 int colon = path.find(':', 0);
96 if (colon != wxNOT_FOUND) path.Remove(colon, 1);
97#endif
98
99 /* replace path separators with ! */
100 wxChar separator = wxFileName::GetPathSeparator();
101 for (unsigned int pos = 0; pos < path.size(); pos = path.find(separator, pos))
102 path.replace(pos, 1, "!");
103
104 // Obfuscate the compressed chart file name, to (slightly) protect some
105 // encrypted raster chart data.
106 wxCharBuffer buf = path.ToUTF8();
107 unsigned char sha1_out[20];
108 sha1((unsigned char *)buf.data(), strlen(buf.data()), sha1_out);
109
110 wxString sha1;
111 for (unsigned int i = 0; i < 20; i++) {
112 wxString s;
113 s.Printf("%02X", sha1_out[i]);
114 sha1 += s;
115 }
116
117 return g_Platform->GetPrivateDataDir() + separator + "raster_texture_cache" +
118 separator + sha1;
119}
120
121#if 0
122OCPN_CompressProgressEvent::OCPN_CompressProgressEvent(wxEventType commandType, int id)
123:wxEvent(id, commandType)
124{
125}
126
127OCPN_CompressProgressEvent::~OCPN_CompressProgressEvent()
128{
129}
130
131wxEvent* OCPN_CompressProgressEvent::Clone() const
132{
133 OCPN_CompressProgressEvent *newevent=new OCPN_CompressProgressEvent(*this);
134 newevent->m_string=this->m_string;
135 newevent->count=this->count;
136 newevent->thread=this->thread;
137 return newevent;
138}
139#endif
140
141static double chart_dist(int index) {
142 double d;
143 float clon;
144 float clat;
145 const ChartTableEntry &cte = ChartData->GetChartTableEntry(index);
146 // if the chart contains ownship position set the distance to 0
147 if (cte.GetBBox().Contains(gLat, gLon))
148 d = 0.;
149 else {
150 // find the nearest edge
151 double t;
152 clon = (cte.GetLonMax() + cte.GetLonMin()) / 2;
153 d = DistGreatCircle(cte.GetLatMax(), clon, gLat, gLon);
154 t = DistGreatCircle(cte.GetLatMin(), clon, gLat, gLon);
155 if (t < d) d = t;
156
157 clat = (cte.GetLatMax() + cte.GetLatMin()) / 2;
158 t = DistGreatCircle(clat, cte.GetLonMin(), gLat, gLon);
159 if (t < d) d = t;
160 t = DistGreatCircle(clat, cte.GetLonMax(), gLat, gLon);
161 if (t < d) d = t;
162 }
163 return d;
164}
165
166WX_DEFINE_SORTED_ARRAY_INT(int, MySortedArrayInt);
167int CompareInts(int n1, int n2) {
168 double d1 = chart_dist(n1);
169 double d2 = chart_dist(n2);
170 return (int)(d1 - d2);
171}
172
173static MySortedArrayInt idx_sorted_by_distance(CompareInts);
174
176public:
177 wxString chart_path;
178 double distance;
179};
180
181WX_DECLARE_OBJARRAY(compress_target, ArrayOfCompressTargets);
182// WX_DEFINE_OBJARRAY(ArrayOfCompressTargets);
183
184JobTicket::JobTicket() {
185 for (int i = 0; i < 10; i++) {
186 compcomp_size_array[i] = 0;
187 comp_bits_array[i] = NULL;
188 compcomp_bits_array[i] = NULL;
189 }
190}
191
192#if 0
193/* reduce pixel values to 5/6/5, because this is the format they are stored
194 * when compressed anyway, and this way the compression algorithm will use
195 * the exact same color in adjacent 4x4 tiles and the result is nicer for our purpose.
196 * the lz4 compressed texture is smaller as well. */
197static
198void FlattenColorsForCompression(unsigned char *data, int dim, bool swap_colors=true)
199{
200#ifdef __WXMSW__ /* undo BGR flip from ocpn_pixel (if ocpnUSE_ocpnBitmap is \
201 defined) */
202 if(swap_colors)
203 for(int i = 0; i<dim*dim; i++) {
204 int off = 3*i;
205 unsigned char t = data[off + 0];
206 data[off + 0] = data[off + 2] & 0xfc;
207 data[off + 1] &= 0xf8;
208 data[off + 2] = t & 0xfc;
209 }
210 else
211#endif
212 for(int i = 0; i<dim*dim; i++) {
213 int off = 3*i;
214 data[off + 0] &= 0xfc;
215 data[off + 1] &= 0xf8;
216 data[off + 2] &= 0xfc;
217 }
218}
219#endif
220
221/* return malloced data which is the etc compressed texture of the source */
222static void CompressDataETC(const unsigned char *data, int dim, int size,
223 unsigned char *tex_data, volatile bool &b_abort) {
224 wxASSERT(dim * dim == 2 * size || (dim < 4 && size == 8)); // must be 4bpp
225 uint64_t *tex_data64 = (uint64_t *)tex_data;
226
227 int mbrow = wxMin(4, dim), mbcol = wxMin(4, dim);
228 uint8_t block[48] = {};
229 for (int row = 0; row < dim; row += 4) {
230 for (int col = 0; col < dim; col += 4) {
231 for (int brow = 0; brow < mbrow; brow++)
232 for (int bcol = 0; bcol < mbcol; bcol++)
233 memcpy(block + (bcol * 4 + brow) * 3,
234 data + ((row + brow) * dim + col + bcol) * 3, 3);
235
236 extern uint64_t ProcessRGB(const uint8_t *src);
237 *tex_data64++ = ProcessRGB(block);
238 }
239 if (b_abort) break;
240 }
241}
242
243static bool CompressUsingGPU(const unsigned char *data, int dim, int size,
244 unsigned char *tex_data, int level, bool inplace) {
245#ifndef USE_ANDROID_GLES2
246
247 GLuint comp_tex;
248 if (!inplace) {
249 glGenTextures(1, &comp_tex);
250 glBindTexture(GL_TEXTURE_2D, comp_tex);
251 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
252 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
253 level = 0;
254 }
255
256 glTexImage2D(GL_TEXTURE_2D, level, g_raster_format, dim, dim, 0, GL_RGB,
257 GL_UNSIGNED_BYTE, data);
258
259 GLint compressed;
260 glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED_ARB,
261 &compressed);
262 /* if the compression has been successful */
263 if (compressed == GL_TRUE) {
264 // If our compressed size is reasonable, save it.
265 GLint compressedSize;
266 glGetTexLevelParameteriv(GL_TEXTURE_2D, level,
267 GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &compressedSize);
268
269 if (compressedSize != size) return false;
270
271 // Read back the compressed texture.
272 glGetCompressedTexImage(GL_TEXTURE_2D, level, tex_data);
273 }
274
275 if (!inplace) glDeleteTextures(1, &comp_tex);
276
277 return true;
278#else
279 return false;
280#endif
281}
282
283static void GetLevel0Map(glTextureDescriptor *ptd, const wxRect &rect,
284 wxString &chart_path) {
285 // Load level 0 uncompressed data
286 wxRect ncrect(rect);
287 ptd->map_array[0] = 0;
288
289 ChartBase *pChart = ChartData->OpenChartFromDB(chart_path, FULL_INIT);
290 if (!pChart) {
291 ptd->map_array[0] =
292 (unsigned char *)calloc(ncrect.width * ncrect.height * 4, 1);
293 return;
294 }
295
296 // Prime the pump with the "zero" level bits, ie. 1x native chart bits
297 ChartBaseBSB *pBSBChart = dynamic_cast<ChartBaseBSB *>(pChart);
298
299 if (pBSBChart) {
300 unsigned char *t_buf =
301 (unsigned char *)malloc(ncrect.width * ncrect.height * 4);
302 pBSBChart->GetChartBits(ncrect, t_buf, 1);
303
304 // and cache them here
305 ptd->map_array[0] = t_buf;
306 } else {
307 ptd->map_array[0] =
308 (unsigned char *)calloc(ncrect.width * ncrect.height * 4, 1);
309 return;
310 }
311}
312
313void GetFullMap(glTextureDescriptor *ptd, const wxRect &rect,
314 wxString chart_path, int level) {
315 // Confirm that the uncompressed bits are all available, get them if not
316 // there yet
317 if (ptd->map_array[level]) return;
318
319 // find next lower level with map_array
320 int first_level;
321 for (first_level = level; first_level; first_level--)
322 if (ptd->map_array[first_level - 1]) break;
323
324 // Get level 0 bits from chart?
325 if (!first_level) {
326 GetLevel0Map(ptd, rect, chart_path);
327 first_level = 1;
328 }
329
330 int dim = g_GLOptions.m_iTextureDimension;
331 for (int i = 0; i <= level; i++) {
332 if (i >= first_level) {
333 ptd->map_array[i] = (unsigned char *)malloc(dim * dim * 3);
334 MipMap_24(2 * dim, 2 * dim, ptd->map_array[i - 1], ptd->map_array[i]);
335 }
336 dim /= 2;
337 }
338}
339
340int TextureDim(int level) {
341 int dim = g_GLOptions.m_iTextureDimension;
342 for (int i = 0; i < level; i++) dim /= 2;
343 return dim;
344}
345
346int TextureTileSize(int level, bool compressed) {
347 if (level == g_mipmap_max_level + 1) return 0;
348
349 int size;
350 if (compressed) {
351 size = g_tile_size;
352 for (int i = 0; i < level; i++) {
353 size /= 4;
354 if (size < 8) size = 8;
355 }
356 } else {
357 size = g_uncompressed_tile_size;
358 for (int i = 0; i < level; i++) size /= 4;
359 }
360
361 return size;
362}
363
364bool JobTicket::DoJob() {
365 if (!m_rect.IsEmpty()) return DoJob(m_rect);
366
367 // otherwise this ticket covers all the rects in the chart
368 ChartBase *pchart = ChartData->OpenChartFromDB(m_ChartPath, FULL_INIT);
369 if (!pchart) return false;
370
371 ChartBaseBSB *pBSBChart = dynamic_cast<ChartBaseBSB *>(pchart);
372 if (!pBSBChart) return false;
373
374 int size_X = pBSBChart->GetSize_X();
375 int size_Y = pBSBChart->GetSize_Y();
376
377 int dim = g_GLOptions.m_iTextureDimension;
378
379 int nx_tex = ceil((float)size_X / dim);
380 int ny_tex = ceil((float)size_Y / dim);
381
382 wxRect rect;
383 rect.y = 0;
384 rect.width = dim;
385 rect.height = dim;
386 for (int y = 0; y < ny_tex; y++) {
387 if (pthread && pthread->m_pMessageTarget) {
388 OCPN_CompressionThreadEvent Nevent(wxEVT_OCPN_COMPRESSIONTHREAD, 0);
389 Nevent.nstat = y;
390 Nevent.nstat_max = ny_tex;
391 Nevent.type = 1;
392 Nevent.SetTicket(this);
393 pthread->m_pMessageTarget->AddPendingEvent(Nevent);
394 }
395
396 rect.x = 0;
397 for (int x = 0; x < nx_tex; x++) {
398 if (!DoJob(rect)) return false;
399
400 pFact->UpdateCacheAllLevels(rect, global_color_scheme,
401 compcomp_bits_array, compcomp_size_array);
402
403 for (int i = 0; i < g_mipmap_max_level + 1; i++) {
404 free(comp_bits_array[i]), comp_bits_array[i] = 0;
405 free(compcomp_bits_array[i]), compcomp_bits_array[i] = 0;
406 }
407
408 rect.x += rect.width;
409 }
410 rect.y += rect.height;
411 }
412
413 return true;
414}
415
416#if 0 // defined( __UNIX__ ) && !defined(__WXOSX__) // high resolution
417 // stopwatch for pro
418class OCPNStopWatch
419{
420public:
421 OCPNStopWatch() { Start(); }
422 void Start() { clock_gettime(CLOCK_REALTIME, &tp); }
423
424 double Time() {
425 timespec tp_end;
426 clock_gettime(CLOCK_REALTIME, &tp_end);
427 return (tp_end.tv_sec - tp.tv_sec) * 1.e3 + (tp_end.tv_nsec - tp.tv_nsec) / 1.e6;
428 }
429
430private:
431 timespec tp;
432};
433#else
434class OCPNStopWatch : public wxStopWatch {};
435#endif
436
437static void throttle_func(void *data) {
438 if (!wxThread::IsMain()) {
439 OCPNStopWatch *sww = (OCPNStopWatch *)data;
440 if (sww->Time() > 1) {
441 sww->Start();
442 wxThread::Sleep(2);
443 }
444 }
445}
446
447static wxMutex s_mutexProtectingChartBitRead;
448
449bool JobTicket::DoJob(const wxRect &rect) {
450 unsigned char *bit_array[10];
451 for (int i = 0; i < 10; i++) bit_array[i] = 0;
452
453 wxRect ncrect(rect);
454
455 bit_array[0] = level0_bits;
456 level0_bits = NULL;
457
458 if (!bit_array[0]) {
459 // Grab a copy of the level0 chart bits
460 // we could alternately subsample grabbing leveln chart bits
461 // directly here to speed things up...
462 ChartBase *pchart;
463 int index;
464
465 if (ChartData) {
466 wxMutexLocker lock(s_mutexProtectingChartBitRead);
467
468 index = ChartData->FinddbIndex(m_ChartPath);
469 pchart = ChartData->OpenChartFromDBAndLock(index, FULL_INIT);
470
471 if (pchart && ChartData->IsChartLocked(index)) {
472 ChartBaseBSB *pBSBChart = dynamic_cast<ChartBaseBSB *>(pchart);
473 if (pBSBChart) {
474 bit_array[0] =
475 (unsigned char *)malloc(ncrect.width * ncrect.height * 4);
476 pBSBChart->GetChartBits(ncrect, bit_array[0], 1);
477 }
478 ChartData->UnLockCacheChart(index);
479 } else
480 bit_array[0] = NULL;
481 }
482 }
483
484 // OK, got the bits?
485 int dim;
486 if (!bit_array[0]) return false;
487
488 // Fill in the rest of the private uncompressed array
489 dim = g_GLOptions.m_iTextureDimension;
490 dim /= 2;
491 for (int i = 1; i < g_mipmap_max_level + 1; i++) {
492 size_t nmalloc = wxMax(dim * dim * 3, 4 * 4 * 3);
493 bit_array[i] = (unsigned char *)malloc(nmalloc);
494 MipMap_24(2 * dim, 2 * dim, bit_array[i - 1], bit_array[i]);
495 dim /= 2;
496 }
497
498 int texture_level = 0;
499 for (int level = level_min_request; level < g_mipmap_max_level + 1; level++) {
500 int dim = TextureDim(level);
501 int size = TextureTileSize(level, true);
502 unsigned char *tex_data = (unsigned char *)malloc(size);
503 if (g_raster_format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT) {
504 // color range fit is worse quality but twice as fast
505 int flags = squish::kDxt1 | squish::kColourRangeFit;
506
507 if (g_GLOptions.m_bTextureCompressionCaching) {
508 /* use slower cluster fit since we are building the cache for
509 * better quality, this takes roughly 25% longer and uses about
510 * 10% more disk space (result doesn't compress as well with lz4) */
511 flags = squish::kDxt1 | squish::kColourClusterFit;
512 }
513
514 OCPNStopWatch sww;
515 squish::CompressImageRGBpow2_Flatten_Throttle_Abort(
516 bit_array[level], dim, dim, tex_data, flags, true,
517 b_throttle ? throttle_func : 0, &sww, b_abort);
518
519 } else if (g_raster_format == GL_ETC1_RGB8_OES)
520 CompressDataETC(bit_array[level], dim, size, tex_data, b_abort);
521 else if (g_raster_format == GL_COMPRESSED_RGB_FXT1_3DFX) {
522 if (!CompressUsingGPU(bit_array[level], dim, size, tex_data,
523 texture_level, binplace)) {
524 b_abort = true;
525 break;
526 }
527
528 if (binplace) g_tex_mem_used += size;
529
530 texture_level++;
531 }
532 comp_bits_array[level] = tex_data;
533
534 if (b_abort) {
535 for (int i = 0; i < g_mipmap_max_level + 1; i++) {
536 free(bit_array[i]);
537 bit_array[i] = 0;
538 }
539 return false;
540 }
541 }
542
543 // All done with the uncompressed data in the thread
544 for (int i = 0; i < g_mipmap_max_level + 1; i++) {
545 free(bit_array[i]);
546 bit_array[i] = 0;
547 }
548
549 if (b_throttle) wxThread::Sleep(1);
550
551 if (b_abort) return false;
552
553 if (bpost_zip_compress) {
554 int max_compressed_size = LZ4_COMPRESSBOUND(g_tile_size);
555 for (int level = level_min_request; level < g_mipmap_max_level + 1;
556 level++) {
557 if (b_abort) return false;
558
559 unsigned char *compressed_data =
560 (unsigned char *)malloc(max_compressed_size);
561 int csize = TextureTileSize(level, true);
562
563 char *src = (char *)comp_bits_array[level];
564#if LZ4_VERSION_MAJOR > 1 || (LZ4_VERSION_MAJOR == 1 && LZ4_VERSION_MINOR >= 7)
565 // LZ4_compressHC2() was deprecated in LZ4 1.7.0 and removed in 1.11.
566 int compressed_size = LZ4_compress_HC(src, (char *)compressed_data, csize,
567 max_compressed_size, 4);
568#else
569 // Old LZ4, e.g. the bundled libs/lz4, lacks LZ4_compress_HC().
570 int compressed_size =
571 LZ4_compressHC2(src, (char *)compressed_data, csize, 4);
572#endif
573 // shrink buffer to actual size.
574 // This will greatly reduce ram usage, ratio usually 10:1
575 // there might be a more efficient way than realloc...
576 compressed_data =
577 (unsigned char *)realloc(compressed_data, compressed_size);
578 compcomp_bits_array[level] = compressed_data;
579 compcomp_size_array[level] = compressed_size;
580 }
581 }
582
583 return true;
584}
585
586// On Windows, we will use a translator to convert SEH exceptions (e.g. access
587// violations),
588// into c++ standard exception handling method.
589// This class and helper function facilitate the conversion.
590
591// We only do this in the compression worker threads, as they are vulnerable
592// due to possibly errant code in the chart database management class,
593// especially on low memory systems where chart cahing is stressed heavily.
594
595#ifdef __WXMSW__
596class SE_Exception {
597private:
598 unsigned int nSE;
599
600public:
601 SE_Exception() {}
602 SE_Exception(unsigned int n) : nSE(n) {}
603 ~SE_Exception() {}
604 unsigned int getSeNumber() { return nSE; }
605};
606
607void my_translate(unsigned int code, _EXCEPTION_POINTERS *ep) {
608 throw SE_Exception();
609}
610#endif
611
612OCPN_CompressionThreadEvent::OCPN_CompressionThreadEvent(
613 wxEventType commandType, int id)
614 : wxEvent(id, commandType) {
615 type = 0;
616}
617
618OCPN_CompressionThreadEvent::~OCPN_CompressionThreadEvent() {}
619
620wxEvent *OCPN_CompressionThreadEvent::Clone() const {
621 OCPN_CompressionThreadEvent *newevent =
622 new OCPN_CompressionThreadEvent(*this);
623 newevent->m_ticket = this->m_ticket;
624 newevent->type = this->type;
625 newevent->nstat = this->nstat;
626 newevent->nstat_max = this->nstat_max;
627 /*
628 newevent->m_ticket = new JobTicket;
629
630 newevent->m_ticket->pFact = this->m_ticket->pFact;
631 newevent->m_ticket->rect = this->m_ticket->rect;
632 newevent->m_ticket->level_min_request = this->m_ticket->level_min_request;
633 newevent->m_ticket->ident = this->m_ticket->ident;
634 newevent->m_ticket->b_throttle = this->m_ticket->b_throttle;
635 newevent->m_ticket->pthread = this->m_ticket->pthread;
636 newevent->m_ticket->level0_bits = this->m_ticket->level0_bits;
637 newevent->m_ticket->m_ChartPath = this->m_ticket->m_ChartPath;
638 newevent->m_ticket->b_abort = this->m_ticket->b_abort;
639 newevent->m_ticket->b_isaborted = this->m_ticket->b_isaborted;
640 newevent->m_ticket->bpost_zip_compress =
641 this->m_ticket->bpost_zip_compress; newevent->m_ticket->state =
642 this->m_ticket->state; newevent->m_ticket->tx = this->m_ticket->tx;
643 newevent->m_ticket->nx = this->m_ticket->nx;
644 newevent->m_ticket->ty = this->m_ticket->ty;
645 newevent->m_ticket->ny = this->m_ticket->ny;
646 for(int i = 0 ; i < 10 ; i++){
647 newevent->m_ticket->comp_bits_array[i] =
648 this->m_ticket->comp_bits_array[i];
649 newevent->m_ticket->compcomp_bits_array[i] =
650 this->m_ticket->compcomp_bits_array[i];
651 newevent->m_ticket->compcomp_size_array[i] =
652 this->m_ticket->compcomp_size_array[i];
653 }
654 */
655 return newevent;
656}
657
658CompressionPoolThread::CompressionPoolThread(JobTicket *ticket,
659 wxEvtHandler *message_target) {
660 m_pMessageTarget = message_target;
661 m_ticket = ticket;
662
663 Create();
664}
665
666void *CompressionPoolThread::Entry() {
667#ifdef __MSVC__
668 _set_se_translator(my_translate);
669
670 // On Windows, if anything in this thread produces a SEH exception (like
671 // access violation) we handle the exception locally, and simply alow the
672 // thread to exit smoothly with no results. Upstream will notice that nothing
673 // got done, and maybe try again later.
674
675 try
676#endif
677 {
678 SetPriority(WXTHREAD_MIN_PRIORITY);
679
680 if (!m_ticket->DoJob()) m_ticket->b_isaborted = true;
681
682 if (m_pMessageTarget) {
683 OCPN_CompressionThreadEvent Nevent(wxEVT_OCPN_COMPRESSIONTHREAD, 0);
684 Nevent.SetTicket(m_ticket);
685 Nevent.type = 0;
686 m_pMessageTarget->QueueEvent(Nevent.Clone());
687 // from here m_ticket is undefined (if deleted in event handler)
688 }
689
690 return 0;
691
692 } // try
693#ifdef __MSVC__
694 catch (SE_Exception e) {
695 if (m_pMessageTarget) {
696 OCPN_CompressionThreadEvent Nevent(wxEVT_OCPN_COMPRESSIONTHREAD, 0);
697 m_ticket->b_isaborted = true;
698 Nevent.SetTicket(m_ticket);
699 Nevent.type = 0;
700 m_pMessageTarget->QueueEvent(Nevent.Clone());
701 }
702
703 return 0;
704 }
705#endif
706}
707
708// ProgressInfoItem Implementation
709
710// glTextureManager Implementation
711glTextureManager::glTextureManager() {
712 // ideally we would use the cpu count -1, and only launch jobs
713 // when the idle load average is sufficient (greater than 1)
714 int nCPU = wxMax(1, wxThread::GetCPUCount());
715 if (g_nCPUCount > 0) nCPU = g_nCPUCount;
716
717 if (nCPU < 1)
718 // obviously there's at least one CPU!
719 nCPU = 1;
720
721 // m_max_jobs = wxMax(nCPU, 1);
722 m_max_jobs = wxMax(nCPU / 2, 1);
723
724 m_prevMemUsed = 0;
725
726 if (bthread_debug) printf(" nCPU: %d m_max_jobs :%d\n", nCPU, m_max_jobs);
727
728 m_progDialog = NULL;
729
730 for (int i = 0; i < m_max_jobs; i++) progList.push_back(new ProgressInfoItem);
731
732 // Create/connect a dynamic event handler slot for messages from the worker
733 // threads
734 Connect(
735 wxEVT_OCPN_COMPRESSIONTHREAD,
736 (wxObjectEventFunction)(wxEventFunction)&glTextureManager::OnEvtThread);
737
738 m_ticks = 0;
739 m_skip = false;
740 m_bcompact = false;
741 m_skipout = false;
742
743 m_timer.Connect(wxEVT_TIMER, wxTimerEventHandler(glTextureManager::OnTimer),
744 NULL, this);
745 m_timer.Start(500);
746}
747
748glTextureManager::~glTextureManager() {
749 // ClearAllRasterTextures();
750 ClearJobList();
751 for (int i = 0; i < m_max_jobs; i++) {
752 auto it = progList.begin();
753 std::advance(it, i);
754 delete *it;
755 }
756 progList.clear();
757 for (auto hash : m_chart_texfactory_hash) {
758 delete hash.second;
759 }
760 m_chart_texfactory_hash.clear();
761}
762
763#define NBAR_LENGTH 40
764
765void glTextureManager::OnEvtThread(OCPN_CompressionThreadEvent &event) {
766 JobTicket *ticket = event.GetTicket();
767
768 if (event.type == 1) {
769 if (!m_progDialog) {
770 // currently unreachable, but...
771 return;
772 }
773 // Look for a matching entry...
774 bool bfound = false;
775 ProgressInfoItem *item;
776 for (auto tnode = progList.begin(); tnode != progList.end(); tnode++) {
777 item = *tnode;
778 if (item->file_path == ticket->m_ChartPath) {
779 bfound = true;
780 break;
781 }
782 }
783
784 if (!bfound) {
785 // look for an empty slot
786 for (auto tnode = progList.begin(); tnode != progList.end(); tnode++) {
787 item = *tnode;
788 if (item->file_path.IsEmpty()) {
789 bfound = true;
790 item->file_path = ticket->m_ChartPath;
791 break;
792 }
793 }
794 }
795
796 if (bfound) {
797 wxString msgx;
798 if (1) {
799 int bar_length = NBAR_LENGTH;
800 if (m_bcompact) bar_length = 20;
801
802 msgx += "\n[";
803 wxString block = wxString::Format("%c", 0x2588);
804 float cutoff = -1.;
805 if (event.nstat_max != 0)
806 cutoff = ((event.nstat + 1) / (float)event.nstat_max) * bar_length;
807 for (int i = 0; i < bar_length; i++) {
808 if (i <= cutoff)
809 msgx += block;
810 else
811 msgx += "-";
812 }
813 msgx += "]";
814
815 if (!m_bcompact) {
816 wxString msgy;
817 msgy.Printf(" [%3d/%3d] ", event.nstat + 1, event.nstat_max);
818 msgx += msgy;
819
820 wxFileName fn(ticket->m_ChartPath);
821 msgx += fn.GetFullName();
822 }
823 } else
824 msgx.Printf("\n %3d/%3d", event.nstat + 1, event.nstat_max);
825
826 item->msgx = msgx;
827 }
828
829 // Ready to compose
830 wxString msg;
831 for (auto tnode = progList.begin(); tnode != progList.end(); tnode++) {
832 item = *tnode;
833 msg += item->msgx + "\n";
834 }
835
836 if (m_skipout) m_progMsg = "Skipping, please wait...\n\n";
837
838 if (!m_progDialog->Update(m_jcnt, m_progMsg + msg, &m_skip)) m_skip = true;
839 if (m_skip) m_skipout = true;
840 return;
841 }
842
843 if (ticket->b_isaborted || ticket->b_abort) {
844 for (int i = 0; i < g_mipmap_max_level + 1; i++) {
845 free(ticket->comp_bits_array[i]);
846 free(ticket->compcomp_bits_array[i]);
847 }
848
849 if (bthread_debug)
850 printf(
851 " Abort job: %08X Jobs running: %d Job count: %lu "
852 "\n",
853 ticket->ident, GetRunningJobCount(), (unsigned long)todo_list.size());
854 } else if (!ticket->b_inCompressAll) {
855 // Normal completion from here
856 glTextureDescriptor *ptd = ticket->pFact->GetpTD(ticket->m_rect);
857 if (ptd) {
858 for (int i = 0; i < g_mipmap_max_level + 1; i++)
859 ptd->comp_array[i] = ticket->comp_bits_array[i];
860
861 if (ticket->bpost_zip_compress) {
862 for (int i = 0; i < g_mipmap_max_level + 1; i++) {
863 ptd->compcomp_array[i] = ticket->compcomp_bits_array[i];
864 ptd->compcomp_size[i] = ticket->compcomp_size_array[i];
865 }
866 }
867
868 // We need to force a refresh to replace the uncompressed texture
869 // This frees video memory and is also really required if we had
870 // gone up a mipmap level
871 top_frame::Get()->InvalidateAllGL();
872 ptd->compdata_ticks = 10;
873 }
874
875 if (bthread_debug)
876 printf(
877 " Finished job: %08X Jobs running: %d Job count: %lu "
878 " \n",
879 ticket->ident, GetRunningJobCount(), (unsigned long)todo_list.size());
880 }
881
882 // Free all possible memory
883 if (ticket->b_inCompressAll) { // if compressing all write cache here
884 ChartBase *pchart =
885 ChartData->OpenChartFromDB(ticket->m_ChartPath, FULL_INIT);
886 ChartData->DeleteCacheChart(pchart);
887 delete ticket->pFact;
888 }
889
890 for (auto tnode = progList.begin(); tnode != progList.end(); ++tnode) {
891 ProgressInfoItem *item = *tnode;
892 if (item->file_path == ticket->m_ChartPath) item->file_path = "";
893 }
894
895 if (g_raster_format != GL_COMPRESSED_RGB_FXT1_3DFX) {
896 auto found = std::find(running_list.begin(), running_list.end(), ticket);
897 if (found != running_list.end()) running_list.erase(found);
898 StartTopJob();
899 }
900
901 delete ticket;
902}
903
904void glTextureManager::OnTimer(wxTimerEvent &event) {
905 m_ticks++;
906
907 // Scrub all the TD's, looking for any completed compression jobs
908 // that have finished
909 // In the interest of not disturbing the GUI, process only one TD per tick
910 if (g_GLOptions.m_bTextureCompression) {
911 for (ChartPathHashTexfactType::iterator itt =
912 m_chart_texfactory_hash.begin();
913 itt != m_chart_texfactory_hash.end(); ++itt) {
914 glTexFactory *ptf = itt->second;
915 if (ptf && ptf->OnTimer()) {
916 // break;
917 }
918 }
919 }
920
921#if 0
922 if((m_ticks % 4/*120*/) == 0){
923
924 // inventory
925 int mem_total, mem_used;
926 platform::GetMemoryStatus(&mem_total, &mem_used);
927
928 int map_size = 0;
929 int comp_size = 0;
930 int compcomp_size = 0;
931
932 for(ChartPathHashTexfactType::iterator itt = m_chart_texfactory_hash.begin();
933 itt != m_chart_texfactory_hash.end(); ++itt ) {
934 glTexFactory *ptf = itt->second;
935
936 ptf->AccumulateMemStatistics(map_size, comp_size, compcomp_size);
937 }
938
939 int m1 = 1024 * 1024;
940// wxString path = wxFileName(m_ChartPath).GetName();
941 printf("%6d %6ld Map: %10d Comp:%10d CompComp: %10d \n", mem_used/1024, g_tex_mem_used/m1, map_size, comp_size, compcomp_size);//, path.mb_str().data());
942
944 }
945#endif
946}
947
948bool glTextureManager::ScheduleJob(glTexFactory *client, const wxRect &rect,
949 int level, bool b_throttle_thread,
950 bool b_nolimit, bool b_postZip,
951 bool b_inplace) {
952 wxString chart_path = client->GetChartPath();
953 if (!b_nolimit) {
954 if (todo_list.size() >= 50) {
955 // remove last job which is least important
956 auto node = todo_list.rbegin();
957 JobTicket *ticket = *node;
958 auto found = std::find(todo_list.begin(), todo_list.end(), ticket);
959 todo_list.erase(found);
960 delete ticket;
961 }
962
963 // Avoid adding duplicate jobs, i.e. the same chart_path, and the same
964 // rectangle
965 for (auto node = todo_list.begin(); node != todo_list.end(); ++node) {
966 JobTicket *ticket = *node;
967 if (ticket->m_ChartPath == chart_path && ticket->m_rect == rect) {
968 // Move the existing job to the front in O(1) without invalidating
969 // others
970 todo_list.splice(todo_list.begin(), todo_list, node);
971 ticket->level_min_request = level;
972 return false;
973 }
974 }
975
976 // avoid duplicate worker jobs
977 for (auto node = todo_list.begin(); node != todo_list.end(); ++node) {
978 JobTicket *ticket = *node;
979 if (ticket->m_rect == rect && ticket->m_ChartPath == chart_path) {
980 return false;
981 }
982 }
983 }
984
985 JobTicket *pt = new JobTicket;
986 pt->pFact = client;
987 pt->m_rect = rect;
988 pt->level_min_request = level;
989 glTextureDescriptor *ptd = client->GetOrCreateTD(pt->m_rect);
990 pt->ident = (ptd->tex_name << 16) + level;
991 pt->b_throttle = b_throttle_thread;
992 pt->m_ChartPath = chart_path;
993
994 pt->level0_bits = NULL;
995 pt->b_abort = false;
996 pt->b_isaborted = false;
997 pt->bpost_zip_compress = b_postZip;
998 pt->binplace = b_inplace;
999 pt->b_inCompressAll = b_inCompressAllCharts;
1000
1001 /* do we compress in ram using builtin libraries, or do we
1002 upload to the gpu and use the driver to perform compression?
1003 we have builtin libraries for DXT1 (squish) and ETC1 (etcpak)
1004 FXT1 must use the driver, ETC1 cannot, and DXT1 can use the driver
1005 but the results are worse and don't compress well.
1006
1007 additionally, if we use the driver we must stay single threaded in this thread
1008 (unless we created multiple opengl contexts), but with with our own libraries,
1009 we can use multiple threads to take advantage of multiple cores */
1010
1011 if (g_raster_format != GL_COMPRESSED_RGB_FXT1_3DFX) {
1012 todo_list.insert(todo_list.begin(), pt); // push to front as a stack
1013 if (bthread_debug) {
1014 int mem_used;
1015 platform::GetMemoryStatus(0, &mem_used);
1016 printf("Adding job: %08X Job Count: %lu mem_used %d\n", pt->ident,
1017 (unsigned long)todo_list.size(), mem_used);
1018 }
1019
1020 StartTopJob();
1021 } else {
1022 // give level 0 buffer to the ticket
1023 pt->level0_bits = ptd->map_array[0];
1024 ptd->map_array[0] = NULL;
1025
1026 pt->DoJob();
1027
1028 OCPN_CompressionThreadEvent Nevent(wxEVT_OCPN_COMPRESSIONTHREAD, 0);
1029 Nevent.type = 0;
1030 Nevent.SetTicket(pt);
1031 ProcessEventLocally(Nevent);
1032 // from here m_ticket is undefined (if deleted in event handler)
1033 }
1034 return true;
1035}
1036
1037bool glTextureManager::StartTopJob() {
1038 auto node = todo_list.begin();
1039 if (node == todo_list.end()) return false;
1040
1041 JobTicket *ticket = *node;
1042
1043 // Is it possible to start another job?
1044 if (GetRunningJobCount() >= wxMax(m_max_jobs - ticket->b_throttle, 1))
1045 return false;
1046 auto found = std::find(todo_list.begin(), todo_list.end(), ticket);
1047 if (found != todo_list.end()) todo_list.erase(found);
1048
1049 glTextureDescriptor *ptd = ticket->pFact->GetpTD(ticket->m_rect);
1050 // don't need the job if we already have the compressed data
1051 if (ptd->comp_array[0]) {
1052 delete ticket;
1053 return StartTopJob();
1054 }
1055
1056 if (ptd->map_array[0]) {
1057 if (ticket->level_min_request == 0) {
1058 // give level 0 buffer to the ticket
1059 ticket->level0_bits = ptd->map_array[0];
1060 ptd->map_array[0] = NULL;
1061 } else {
1062 // would be nicer to use reference counters
1063 int size = TextureTileSize(0, false);
1064 ticket->level0_bits = (unsigned char *)malloc(size);
1065 memcpy(ticket->level0_bits, ptd->map_array[0], size);
1066 }
1067 }
1068
1069 running_list.push_back(ticket);
1070 DoThreadJob(ticket);
1071
1072 return true;
1073}
1074
1075bool glTextureManager::DoThreadJob(JobTicket *pticket) {
1076 if (bthread_debug)
1077 printf(" Starting job: %08X Jobs running: %d Jobs left: %lu\n",
1078 pticket->ident, GetRunningJobCount(),
1079 (unsigned long)todo_list.size());
1080
1083 CompressionPoolThread *t = new CompressionPoolThread(pticket, this);
1084 pticket->pthread = t;
1085
1086 t->Run();
1087
1088 return true;
1089}
1090
1091bool glTextureManager::AsJob(wxString const &chart_path) const {
1092 if (chart_path.Len()) {
1093 for (auto node = todo_list.begin(); node != todo_list.end(); ++node) {
1094 JobTicket *ticket = *node;
1095 if (ticket->m_ChartPath.IsSameAs(chart_path)) {
1096 return true;
1097 }
1098 }
1099 }
1100 return false;
1101}
1102
1103void glTextureManager::PurgeJobList(wxString chart_path) {
1104 if (chart_path.Len()) {
1105 // Remove all pending jobs relating to the passed chart path
1106 auto &list = todo_list;
1107 auto removed_begin =
1108 std::remove_if(list.begin(), list.end(), [chart_path](JobTicket *t) {
1109 bool is_chart_match = t->m_ChartPath == chart_path;
1110 if (is_chart_match) delete t;
1111 return is_chart_match;
1112 });
1113 list.erase(removed_begin, list.end());
1114
1115 // Mark running tasks for this chart as "abort"
1116 for (auto node = running_list.begin(); node != running_list.end(); ++node) {
1117 JobTicket *ticket = *node;
1118 if (ticket->m_ChartPath == chart_path) ticket->b_abort = true;
1119 }
1120
1121 if (bthread_debug)
1122 std::cout << "Pool: Purge, todo count: " << list.size() << "\n";
1123 } else {
1124 for (auto node = todo_list.begin(); node != todo_list.end(); ++node) {
1125 JobTicket *ticket = *node;
1126 delete ticket;
1127 }
1128 todo_list.clear();
1129 // Mark all running tasks for "abort"
1130 for (auto node = running_list.begin(); node != running_list.end(); ++node) {
1131 JobTicket *ticket = *node;
1132 ticket->b_abort = true;
1133 }
1134 }
1135}
1136
1137void glTextureManager::ClearJobList() {
1138 for (auto node = todo_list.begin(); node != todo_list.end(); ++node) {
1139 JobTicket *ticket = *node;
1140 delete ticket;
1141 }
1142 todo_list.clear();
1143}
1144
1145void glTextureManager::ClearAllRasterTextures() {
1146 // Delete all the TexFactory instances
1147 ChartPathHashTexfactType::iterator itt;
1148 for (itt = m_chart_texfactory_hash.begin();
1149 itt != m_chart_texfactory_hash.end(); ++itt) {
1150 glTexFactory *ptf = itt->second;
1151
1152 delete ptf;
1153 }
1154 m_chart_texfactory_hash.clear();
1155
1156 if (g_tex_mem_used != 0)
1157 wxLogMessage("Texture memory use calculation error\n");
1158}
1159
1160bool glTextureManager::PurgeChartTextures(ChartBase *pc, bool b_purge_factory) {
1161 // Look for the texture factory for this chart
1162 ChartPathHashTexfactType::iterator ittf =
1163 m_chart_texfactory_hash.find(pc->GetHashKey());
1164
1165 // Found ?
1166 if (ittf != m_chart_texfactory_hash.end()) {
1167 glTexFactory *pTexFact = ittf->second;
1168
1169 if (pTexFact) {
1170 if (b_purge_factory) {
1171 m_chart_texfactory_hash.erase(ittf); // This chart becoming invalid
1172
1173 delete pTexFact;
1174 }
1175
1176 return true;
1177 } else {
1178 m_chart_texfactory_hash.erase(ittf);
1179 return false;
1180 }
1181 } else
1182 return false;
1183}
1184
1185bool glTextureManager::TextureCrunch(double factor) {
1186 double hysteresis = 0.90;
1187
1188 bool bGLMemCrunch =
1189 g_tex_mem_used >
1190 (double)(g_GLOptions.m_iTextureMemorySize * 1024 * 1024) * factor;
1191 if (!bGLMemCrunch) return false;
1192
1193 ChartPathHashTexfactType::iterator it0;
1194 for (it0 = m_chart_texfactory_hash.begin();
1195 it0 != m_chart_texfactory_hash.end(); ++it0) {
1196 glTexFactory *ptf = it0->second;
1197 if (!ptf) continue;
1198 wxString chart_full_path = ptf->GetChartPath();
1199
1200 bGLMemCrunch = g_tex_mem_used >
1201 (double)(g_GLOptions.m_iTextureMemorySize * 1024 * 1024) *
1202 factor * hysteresis;
1203 if (!bGLMemCrunch) break;
1204
1205 // For each canvas
1206 for (unsigned int i = 0; i < g_canvasArray.GetCount(); i++) {
1207 ChartCanvas *cc = g_canvasArray.Item(i);
1208 if (cc) {
1209 if (cc->GetVP().b_quilt) // quilted
1210 {
1211 if (cc->m_pQuilt && cc->m_pQuilt->IsComposed() &&
1212 !cc->m_pQuilt->IsChartInQuilt(chart_full_path)) {
1213 ptf->DeleteSomeTextures(g_GLOptions.m_iTextureMemorySize * 1024 *
1214 1024 * factor * hysteresis);
1215 }
1216 } else // not quilted
1217 {
1218 if (!cc->m_singleChart->GetFullPath().IsSameAs(chart_full_path)) {
1219 ptf->DeleteSomeTextures(g_GLOptions.m_iTextureMemorySize * 1024 *
1220 1024 * factor * hysteresis);
1221 }
1222 }
1223 }
1224 }
1225 }
1226
1227 return true;
1228}
1229
1230#define MAX_CACHE_FACTORY 50
1231bool glTextureManager::FactoryCrunch(double factor) {
1232 if (m_chart_texfactory_hash.size() == 0) {
1233 /* nothing to free */
1234 return false;
1235 }
1236
1237 int mem_used;
1238 platform::GetMemoryStatus(0, &mem_used);
1239 double hysteresis = 0.90;
1240 ChartPathHashTexfactType::iterator it0;
1241
1242 bool bMemCrunch =
1243 (g_memCacheLimit &&
1244 ((mem_used > (double)(g_memCacheLimit)*factor * hysteresis &&
1245 mem_used > (double)(m_prevMemUsed)*factor * hysteresis) ||
1246 (m_chart_texfactory_hash.size() > MAX_CACHE_FACTORY)));
1247
1248 if (!bMemCrunch) return false;
1249
1250 // Need more, so delete the oldest factory
1251 // Find the oldest unused factory
1252 int lru_oldest = 2147483647;
1253 glTexFactory *ptf_oldest = NULL;
1254
1255 for (it0 = m_chart_texfactory_hash.begin();
1256 it0 != m_chart_texfactory_hash.end(); ++it0) {
1257 glTexFactory *ptf = it0->second;
1258 if (!ptf) continue;
1259 wxString chart_full_path = ptf->GetChartPath();
1260
1261 // we better have to find one because glTexFactory keep cache texture open
1262 // and ocpn will eventually run out of file descriptors
1263
1264 // For each canvas
1265 for (unsigned int i = 0; i < g_canvasArray.GetCount(); i++) {
1266 ChartCanvas *cc = g_canvasArray.Item(i);
1267 if (cc) {
1268 if (cc->GetVP().b_quilt) // quilted
1269 {
1270 if (cc->m_pQuilt && cc->m_pQuilt->IsComposed() &&
1271 !cc->m_pQuilt->IsChartInQuilt(chart_full_path)) {
1272 int lru = ptf->GetLRUTime();
1273 if (lru < lru_oldest && !ptf->BackgroundCompressionAsJob()) {
1274 lru_oldest = lru;
1275 ptf_oldest = ptf;
1276 }
1277 }
1278 } else {
1279 if (!cc->m_singleChart->GetFullPath().IsSameAs(chart_full_path)) {
1280 int lru = ptf->GetLRUTime();
1281 if (lru < lru_oldest && !ptf->BackgroundCompressionAsJob()) {
1282 lru_oldest = lru;
1283 ptf_oldest = ptf;
1284 }
1285 }
1286 }
1287 }
1288 }
1289 }
1290
1291 // Found one?
1292 if (!ptf_oldest) return false;
1293
1294 ptf_oldest->FreeSome(g_memCacheLimit * factor * hysteresis);
1295
1296 platform::GetMemoryStatus(0, &mem_used);
1297
1298 bMemCrunch = (g_memCacheLimit &&
1299 ((mem_used > (double)(g_memCacheLimit)*factor * hysteresis &&
1300 mem_used > (double)(m_prevMemUsed)*factor * hysteresis) ||
1301 (m_chart_texfactory_hash.size() > MAX_CACHE_FACTORY)));
1302
1303 if (!bMemCrunch) return false;
1304
1305 // Need more, so delete the oldest chart too
1306
1307 m_chart_texfactory_hash.erase(
1308 ptf_oldest->GetHashKey()); // This chart becoming invalid
1309
1310 delete ptf_oldest;
1311
1312 return true;
1313}
1314
1315void glTextureManager::BuildCompressedCache() {
1316 idx_sorted_by_distance.Clear();
1317
1318 // Building the cache may take a long time....
1319 // Be a little smarter.
1320 // Build a sorted array of chart database indices, sorted on distance from the
1321 // ownship currently. This way, a user may build a few charts textures for
1322 // immediate use, then "skip" out on the rest until later.
1323 int count = 0;
1324 for (int i = 0; i < ChartData->GetChartTableEntries(); i++) {
1325 /* skip if not kap */
1326 const ChartTableEntry &cte = ChartData->GetChartTableEntry(i);
1327 ChartTypeEnum chart_type = (ChartTypeEnum)cte.GetChartType();
1328 if (chart_type == CHART_TYPE_PLUGIN) {
1329 if (cte.GetChartFamily() != CHART_FAMILY_RASTER) continue;
1330 } else {
1331 if (chart_type != CHART_TYPE_KAP) continue;
1332 }
1333
1334 wxString CompressedCacheFilePath =
1335 CompressedCachePath(ChartData->GetDBChartFileName(i));
1336 wxFileName fn(CompressedCacheFilePath);
1337 // if(fn.FileExists()) /* skip if file exists */
1338 // continue;
1339
1340 idx_sorted_by_distance.Add(i);
1341
1342 count++;
1343 }
1344
1345 if (count == 0) return;
1346
1347 wxLogMessage(wxString::Format("BuildCompressedCache() count = %d", count));
1348
1349 m_timer.Stop();
1350 PurgeJobList();
1351 if (GetRunningJobCount()) {
1352 wxLogMessage("Starting compressor pool drain");
1353 wxDateTime now = wxDateTime::Now();
1354 time_t stall = now.GetTicks();
1355#define THREAD_WAIT_SECONDS 5
1356 time_t end = stall + THREAD_WAIT_SECONDS;
1357
1358 int n_comploop = 0;
1359 while (stall < end) {
1360 wxDateTime later = wxDateTime::Now();
1361 stall = later.GetTicks();
1362
1363 wxString msg;
1364 msg.Printf("Time: %d Job Count: %d", n_comploop, GetRunningJobCount());
1365 wxLogMessage(msg);
1366 if (!GetRunningJobCount()) break;
1367 wxYield();
1368 wxSleep(1);
1369 }
1370
1371 wxString fmsg;
1372 fmsg.Printf("Finished compressor pool drain..Time: %d Job Count: %d",
1373 n_comploop, GetRunningJobCount());
1374 wxLogMessage(fmsg);
1375 }
1376 ClearAllRasterTextures();
1377 b_inCompressAllCharts = true;
1378
1379 // Build another array of sorted compression targets.
1380 // We need to do this, as the chart table will not be invariant
1381 // after the compression threads start, so our index array will be invalid.
1382
1383 ArrayOfCompressTargets ct_array;
1384 for (unsigned int j = 0; j < idx_sorted_by_distance.GetCount(); j++) {
1385 int i = idx_sorted_by_distance[j];
1386
1387 const ChartTableEntry &cte = ChartData->GetChartTableEntry(i);
1388 double distance = chart_dist(i);
1389
1390 wxString filename = cte.GetFullSystemPath();
1391
1392 compress_target *pct = new compress_target;
1393 pct->distance = distance;
1394 pct->chart_path = filename;
1395
1396 ct_array.Add(pct);
1397 }
1398
1399 // create progress dialog
1400 long style = wxPD_SMOOTH | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME |
1401 wxPD_REMAINING_TIME | wxPD_CAN_ABORT;
1402
1403 wxString msg0;
1404 msg0 =
1405 " "
1406 " \n \n ";
1407
1408#ifdef __WXQT__
1409 msg0 =
1410 "Very "
1411 "longgggggggggggggggggggggggggggggggggggggggggggg\ngggggggggggggggggg"
1412 "gggggggggggggggggggggggggg top line ";
1413#endif
1414
1415 for (int i = 0; i < m_max_jobs + 1; i++)
1416 msg0 += "\n ";
1417
1418 m_progDialog = new wxGenericProgressDialog();
1419
1420 wxFont *qFont = GetOCPNScaledFont(_("Dialog"));
1421 int fontSize = qFont->GetPointSize();
1422 wxFont *sFont;
1423 wxSize csz = wxTheApp->GetTopWindow()->GetClientSize();
1424 if (csz.x < 500 || csz.y < 500)
1425 sFont = FontMgr::Get().FindOrCreateFont(
1426 10, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
1427 else
1428 sFont = FontMgr::Get().FindOrCreateFont(fontSize, wxFONTFAMILY_TELETYPE,
1429 wxFONTSTYLE_NORMAL,
1430 wxFONTWEIGHT_NORMAL);
1431
1432 m_progDialog->SetFont(*sFont);
1433
1434 // Should we use "compact" screen layout?
1435 wxScreenDC sdc;
1436 int height, width;
1437 sdc.GetTextExtent("[WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW]", &width, &height, NULL,
1438 NULL, sFont);
1439 if (width > (csz.x / 2)) m_bcompact = true;
1440
1441 m_progDialog->Create(_("OpenCPN Compressed Cache Update"), msg0, count + 1,
1442 NULL, style);
1443
1444 // Make sure the dialog is big enough to be readable
1445 m_progDialog->Hide();
1446 wxSize sz = m_progDialog->GetSize();
1447 sz.x = csz.x * 9 / 10;
1448 m_progDialog->SetSize(sz);
1449
1450 m_progDialog->Layout();
1451 wxSize sza = m_progDialog->GetSize();
1452
1453 m_progDialog->Centre();
1454 m_progDialog->Show();
1455 m_progDialog->Raise();
1456
1457 m_skipout = false;
1458 m_skip = false;
1459 int yield = 0;
1460
1461 for (m_jcnt = 0; m_jcnt < ct_array.GetCount(); m_jcnt++) {
1462 wxString filename = ct_array[m_jcnt].chart_path;
1463 wxString CompressedCacheFilePath = CompressedCachePath(filename);
1464 double distance = ct_array[m_jcnt].distance;
1465
1466 ChartBase *pchart = ChartData->OpenChartFromDBAndLock(filename, FULL_INIT);
1467 if (!pchart) /* probably a corrupt chart */
1468 continue;
1469
1470 // bad things if more than one texfactory for a chart
1471 g_glTextureManager->PurgeChartTextures(pchart, true);
1472
1473 ChartBaseBSB *pBSBChart = dynamic_cast<ChartBaseBSB *>(pchart);
1474 if (pBSBChart == 0) continue;
1475
1476 glTexFactory *tex_fact = new glTexFactory(pchart, g_raster_format);
1477
1478 m_progMsg.Printf(_("Distance from Ownship: %4.0f NMi"), distance);
1479 m_progMsg += "\n";
1480 m_progMsg.Prepend("Preparing RNC Cache...\n");
1481
1482 if (m_skipout) {
1483 g_glTextureManager->PurgeJobList();
1484 ChartData->DeleteCacheChart(pchart);
1485 delete tex_fact;
1486 break;
1487 }
1488
1489 int size_X = pBSBChart->GetSize_X();
1490 int size_Y = pBSBChart->GetSize_Y();
1491
1492 int tex_dim = g_GLOptions.m_iTextureDimension;
1493
1494 int nx_tex = ceil((float)size_X / tex_dim);
1495 int ny_tex = ceil((float)size_Y / tex_dim);
1496
1497 wxRect rect;
1498 rect.y = 0;
1499 rect.width = tex_dim;
1500 rect.height = tex_dim;
1501 for (int y = 0; y < ny_tex; y++) {
1502 rect.x = 0;
1503 for (int x = 0; x < nx_tex; x++) {
1504 for (int level = 0; level < g_mipmap_max_level + 1; level++) {
1505 if (!tex_fact->IsLevelInCache(level, rect, global_color_scheme)) {
1506 goto schedule;
1507 }
1508 }
1509 rect.x += rect.width;
1510 }
1511 rect.y += rect.height;
1512 }
1513 // Nothing to do
1514 // Free all possible memory
1515 ChartData->DeleteCacheChart(pchart);
1516 delete tex_fact;
1517 yield++;
1518 if (yield == 200) {
1519 ::wxYield();
1520 yield = 0;
1521 if (!m_progDialog->Update(m_jcnt)) {
1522 m_skip = true;
1523 m_skipout = true;
1524 }
1525 }
1526 continue;
1527
1528 // some work to do
1529 schedule:
1530
1531 yield = 0;
1532 ScheduleJob(tex_fact, wxRect(), 0, false, true, true, false);
1533 while (!m_skip) {
1534 ::wxYield();
1535 int cnt = GetJobCount() - GetRunningJobCount();
1536 if (!cnt) break;
1537 wxThread::Sleep(1);
1538 }
1539
1540 if (m_skipout) {
1541 g_glTextureManager->PurgeJobList();
1542 ChartData->DeleteCacheChart(pchart);
1543 delete tex_fact;
1544 break;
1545 }
1546 }
1547
1548 while (GetRunningJobCount()) {
1549 wxThread::Sleep(1);
1550 ::wxYield();
1551 }
1552
1553 b_inCompressAllCharts = false;
1554 m_timer.Start(500);
1555
1556 delete m_progDialog;
1557 m_progDialog = nullptr;
1558}
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.
General chart base definitions.
ChartDB * ChartData
Global instance.
Definition chartdb.cpp:71
Charts database management
BSB chart management.
arrayofCanvasPtr g_canvasArray
Global instance.
Definition chcanv.cpp:173
Generic Chart canvas base.
Base class for BSB (Maptech/NOS) format nautical charts.
Definition chartimg.h:128
Base class for all chart types.
Definition chartbase.h:126
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
Global variables stored in configuration file.
Font list manager.
GLuint g_raster_format
Global instance.
OpenGL chart rendering canvas.
glTextureManager * g_glTextureManager
Global instance.
OpenGL texture cache.
OpenGL texture container.
int g_mipmap_max_level
Global instance.
Definition gui_vars.cpp:87
wxFont * GetOCPNScaledFont(wxString item, int default_size)
Retrieves a font from FontMgr, optionally scaled for physical readability.
Definition gui_lib.cpp:61
General purpose GUI support.
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.
OpenCPN Platform specific support utilities.
double gLat
Vessel's current latitude in decimal degrees.
Definition own_ship.cpp:26
double gLon
Vessel's current longitude in decimal degrees.
Definition own_ship.cpp:27
Position, course, speed, etc.
struct block block
Runtime representation of a plugin block.
Chart quilt support.
Represents an entry in the chart table, containing information about a single chart.
Definition chartdbs.h:190
Runtime representation of a plugin block.
Abstract gFrame/MyFrame interface.
Geographic projection and coordinate transformations.