MandelWidget.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. #include "MandelWidget.h"
  2. #include <cmath>
  3. #include <sstream>
  4. using namespace mnd;
  5. #include <cstdio>
  6. Texture::Texture(const Bitmap<RGBColor>& bitmap, GLint param)
  7. {
  8. glGenTextures(1, &id);
  9. glBindTexture(GL_TEXTURE_2D, id);
  10. //int lineLength = (bitmap.width * 3 + 3) & ~3;
  11. /*std::unique_ptr<unsigned char[]> pixels = std::make_unique<unsigned char[]>(lineLength * bitmap.height);
  12. for (int i = 0; i < bitmap.width; i++) {
  13. for (int j = 0; j < bitmap.height; j++) {
  14. int index = i * 3 + j * lineLength;
  15. RGBColor c = bitmap.get(i, j);
  16. pixels[index] = c.r;
  17. pixels[index + 1] = c.g;
  18. pixels[index + 2] = c.b;
  19. }
  20. }*/
  21. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, int(bitmap.width), int(bitmap.height), 0, GL_RGB, GL_UNSIGNED_BYTE, reinterpret_cast<char*> (bitmap.pixels.get()));
  22. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  23. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  24. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param);
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param);
  26. }
  27. Texture::~Texture(void)
  28. {
  29. if (id != 0)
  30. glDeleteTextures(1, &id);
  31. }
  32. Texture::Texture(Texture&& other) :
  33. id{ other.id }
  34. {
  35. other.id = 0;
  36. }
  37. Texture& Texture::operator=(Texture&& other)
  38. {
  39. this->id = other.id;
  40. other.id = 0;
  41. return *this;
  42. }
  43. void Texture::bind(void) const
  44. {
  45. glBindTexture(GL_TEXTURE_2D, id);
  46. }
  47. void Texture::drawRect(float x, float y, float width, float height)
  48. {
  49. glColor3ub(255, 255, 255);
  50. glEnable(GL_TEXTURE_2D);
  51. bind();
  52. glBegin(GL_TRIANGLE_STRIP);
  53. glTexCoord2f(0, 0);
  54. glVertex2f(x, y);
  55. glTexCoord2f(1, 0);
  56. glVertex2f(x + width, y);
  57. glTexCoord2f(0, 1);
  58. glVertex2f(x, y + height);
  59. glTexCoord2f(1, 1);
  60. glVertex2f(x + width, y + height);
  61. glEnd();
  62. glDisable(GL_TEXTURE_2D);
  63. }
  64. CellImage::~CellImage(void)
  65. {
  66. }
  67. TextureClip::~TextureClip(void)
  68. {
  69. }
  70. void TextureClip::drawRect(float x, float y, float width, float height)
  71. {
  72. glColor3ub(255, 255, 255);
  73. glEnable(GL_TEXTURE_2D);
  74. glBindTexture(GL_TEXTURE_2D, texture->getId());
  75. glBegin(GL_TRIANGLE_STRIP);
  76. glTexCoord2f(tx, ty);
  77. glVertex2f(x, y);
  78. glTexCoord2f(tx + tw, ty);
  79. glVertex2f(x + width, y);
  80. glTexCoord2f(tx, ty + th);
  81. glVertex2f(x, y + height);
  82. glTexCoord2f(tx + tw, ty + th);
  83. glVertex2f(x + width, y + height);
  84. glEnd();
  85. glDisable(GL_TEXTURE_2D);
  86. }
  87. TextureClip TextureClip::clip(float x, float y, float w, float h)
  88. {
  89. float tx = this->tx + x * this->tw;
  90. float ty = this->ty + y * this->th;
  91. float tw = this->tw * w;
  92. float th = this->th * h;
  93. return TextureClip{ this->texture, tx, ty, tw, th };
  94. }
  95. std::shared_ptr<CellImage> TextureClip::clip(short i, short j)
  96. {
  97. return std::make_shared<TextureClip>(clip(i * 0.5f, j * 0.5f, 0.5f, 0.5f));
  98. }
  99. int TextureClip::getRecalcPriority() const
  100. {
  101. return int(1.0f / tw);
  102. }
  103. QuadImage::~QuadImage(void)
  104. {
  105. }
  106. void QuadImage::drawRect(float x, float y, float width, float height)
  107. {
  108. for (int i = 0; i < 2; i++) {
  109. for (int j = 0; j < 2; j++) {
  110. this->cells[i][j]->drawRect(x + i * 0.5f * width,
  111. y + j * 0.5f * height,
  112. width * 0.5f,
  113. height * 0.5f);
  114. }
  115. }
  116. }
  117. std::shared_ptr<CellImage> QuadImage::clip(short i, short j)
  118. {
  119. return cells[i][j];
  120. }
  121. int QuadImage::getRecalcPriority() const
  122. {
  123. return 1;
  124. }
  125. TexGrid::TexGrid(MandelView& owner, int level) :
  126. owner{ owner },
  127. level{ level },
  128. dpp{ owner.getDpp(level) }
  129. {
  130. }
  131. std::pair<GridIndex, GridIndex> TexGrid::getCellIndices(mnd::Real x, mnd::Real y)
  132. {
  133. return { GridIndex(mnd::floor(x / dpp / MandelView::chunkSize)), GridIndex(mnd::floor(y / dpp / MandelView::chunkSize)) };
  134. }
  135. std::pair<mnd::Real, mnd::Real> TexGrid::getPositions(GridIndex x, GridIndex y)
  136. {
  137. return { mnd::Real(x) * dpp * MandelView::chunkSize, mnd::Real(y) * dpp * MandelView::chunkSize };
  138. }
  139. GridElement* TexGrid::getCell(GridIndex i, GridIndex j)
  140. {
  141. auto cIt = cells.find({i, j});
  142. if (cIt != cells.end()) {
  143. return cIt->second.get();
  144. }
  145. else {
  146. return nullptr;
  147. }
  148. }
  149. void TexGrid::setCell(GridIndex i, GridIndex j, std::unique_ptr<GridElement> tex)
  150. {
  151. cells[{i, j}] = std::move(tex);
  152. }
  153. void TexGrid::clearCells(void)
  154. {
  155. cells.clear();
  156. }
  157. void TexGrid::clearUncleanCells(void)
  158. {
  159. for (auto it = cells.begin(); it != cells.end();) {
  160. if (it->second->img->getRecalcPriority() > 1)
  161. cells.erase(it++);
  162. else ++it;
  163. }
  164. }
  165. void Job::run(void)
  166. {
  167. auto [absX, absY] = grid->getPositions(i, j);
  168. mnd::Real gw = grid->dpp * MandelView::chunkSize;
  169. Bitmap<float> f(MandelView::chunkSize, MandelView::chunkSize);
  170. mnd::MandelInfo mi = owner.getMandelInfo();
  171. mi.view.x = absX;
  172. mi.view.y = absY;
  173. mi.view.width = mi.view.height = gw;
  174. mi.bWidth = mi.bHeight = MandelView::chunkSize;
  175. try {
  176. generator->generate(mi, f.pixels.get());
  177. auto* rgb = new Bitmap<RGBColor>(f.map<RGBColor>([&mi, this] (float i) {
  178. return i >= mi.maxIter ? RGBColor{ 0, 0, 0 } : gradient.get(i);
  179. }));
  180. emit done(level, i, j, calcState, rgb);
  181. }
  182. catch(std::exception& ex) {
  183. printf("wat: %s?!\n", ex.what()); fflush(stdout);
  184. exit(1);
  185. }
  186. catch(...) {
  187. printf("wat?!\n"); fflush(stdout);
  188. exit(1);
  189. }
  190. }
  191. Calcer::Calcer(mnd::MandelGenerator* generator, MandelWidget& owner) :
  192. jobsMutex{ QMutex::Recursive },
  193. generator{ generator },
  194. threadPool{ std::make_unique<QThreadPool>() },
  195. owner{ owner },
  196. gradient{ owner.getGradient() }
  197. {
  198. threadPool->setMaxThreadCount(1);
  199. }
  200. void Calcer::clearAll(void)
  201. {
  202. this->threadPool->clear();
  203. }
  204. void Calcer::calc(TexGrid& grid, int level, GridIndex i, GridIndex j, int priority)
  205. {
  206. jobsMutex.lock();
  207. if (jobs.find({ level, i, j }) == jobs.end()) {
  208. Job* job = new Job(generator, gradient, owner, &grid, level, i, j, calcState);
  209. connect(job, &Job::done, this, &Calcer::redirect);
  210. connect(job, &QObject::destroyed, this, [this, level, i, j] () { this->notFinished(level, i, j); });
  211. jobs.emplace(std::tuple{level, i, j}, job);
  212. threadPool->start(job, priority);
  213. }
  214. jobsMutex.unlock();
  215. }
  216. void Calcer::setCurrentLevel(int level)
  217. {
  218. if (this->currentLevel != level) {
  219. this->currentLevel = level;
  220. std::vector<QRunnable*> toCancel;
  221. jobsMutex.lock();
  222. for (auto&[tup, job] : jobs) {
  223. auto& [level, i, j] = tup;
  224. if(level != currentLevel) {
  225. toCancel.push_back(job);
  226. }
  227. }
  228. jobsMutex.unlock();
  229. for (auto* job : toCancel) {
  230. if (threadPool->tryTake(job)) {
  231. delete job;
  232. }
  233. }
  234. }
  235. }
  236. void Calcer::notFinished(int level, GridIndex i, GridIndex j)
  237. {
  238. jobsMutex.lock();
  239. jobs.erase({ level, i, j });
  240. jobsMutex.unlock();
  241. }
  242. void Calcer::redirect(int level, GridIndex i, GridIndex j, long calcState, Bitmap<RGBColor>* bmp)
  243. {
  244. jobsMutex.lock();
  245. jobs.erase({ level, i, j });
  246. jobsMutex.unlock();
  247. if (this->calcState == calcState) {
  248. emit done(level, i, j, bmp);
  249. }
  250. else {
  251. delete bmp;
  252. }
  253. }
  254. const int MandelView::chunkSize = 256;
  255. MandelView::MandelView(mnd::MandelGenerator* generator, MandelWidget& owner) :
  256. generator{ generator },
  257. calcer{ generator, owner },
  258. owner{ owner }
  259. {
  260. /*Bitmap<RGBColor> emp(8, 8);
  261. for(auto i = 0; i < emp.width; i++) {
  262. for(auto j = 0; j < emp.height; j++) {
  263. if((i + j) & 0x1) { // if i+j is odd
  264. emp.get(i, j) = RGBColor{ 255, 255, 255 };
  265. }
  266. else {
  267. emp.get(i, j) = RGBColor{ 120, 120, 120 };
  268. }
  269. }
  270. }*/
  271. Bitmap<RGBColor> emp(1, 1);
  272. emp.get(0, 0) = RGBColor{ 0, 0, 0 };
  273. empty = std::make_unique<Texture>(emp, GL_NEAREST);
  274. connect(&calcer, &Calcer::done, this, &MandelView::cellReady);
  275. }
  276. int MandelView::getLevel(mnd::Real dpp)
  277. {
  278. return int(mnd::log2(dpp / chunkSize));
  279. }
  280. mnd::Real MandelView::getDpp(int level)
  281. {
  282. return mnd::pow(mnd::Real(2), mnd::Real(level)) * chunkSize;
  283. }
  284. TexGrid& MandelView::getGrid(int level)
  285. {
  286. auto it = levels.find(level);
  287. if (it != levels.end()) {
  288. return it->second;
  289. }
  290. else {
  291. levels.insert(std::pair<int, TexGrid>{ level, TexGrid{ *this, level } });
  292. return levels.at(level);
  293. }
  294. }
  295. void MandelView::setGenerator(mnd::MandelGenerator* generator)
  296. {
  297. if (this->generator != generator) {
  298. this->generator = generator;
  299. calcer.setGenerator(generator);
  300. clearCells();
  301. emit redrawRequested();
  302. }
  303. }
  304. void MandelView::clearCells(void)
  305. {
  306. for(auto& [level, grid] : this->levels) {
  307. grid.clearCells();
  308. }
  309. }
  310. void MandelView::garbageCollect(int level, GridIndex /*i*/, GridIndex /*j*/)
  311. {
  312. for(auto& [l, grid] : levels) {
  313. int dist = ::abs(l - level);
  314. if (dist == 1) {
  315. grid.clearUncleanCells();
  316. }
  317. if (dist > 20) {
  318. grid.clearCells();
  319. }
  320. else if (dist > 10) {
  321. if (grid.countAllocatedCells() > 50)
  322. grid.clearCells();
  323. }
  324. else if (dist > 3) {
  325. if (grid.countAllocatedCells() > 150)
  326. grid.clearCells();
  327. }
  328. else if (dist > 0) {
  329. if (grid.countAllocatedCells() > 350)
  330. grid.clearCells();
  331. }
  332. else {
  333. if (grid.countAllocatedCells() > 2500)
  334. grid.clearCells();
  335. }
  336. }
  337. }
  338. GridElement* MandelView::searchAbove(int level, GridIndex i, GridIndex j, int recursionLevel)
  339. {
  340. auto& grid = getGrid(level);
  341. auto& gridAbove = getGrid(level + 1);
  342. GridIndex ai = (i < 0 ? (i - 1) : i) / 2;
  343. GridIndex aj = (j < 0 ? (j - 1) : j) / 2;
  344. GridElement* above = gridAbove.getCell(ai, aj);
  345. if (above == nullptr && recursionLevel > 0) {
  346. auto abFound = searchAbove(level + 1, ai, aj, recursionLevel - 1);
  347. if (abFound)
  348. above = abFound;
  349. }
  350. if (above != nullptr) {
  351. auto newElement = std::make_unique<GridElement>(
  352. false, above->img->clip(short(i & 1), short(j & 1))
  353. );
  354. GridElement* ret = newElement.get();
  355. grid.setCell(i, j, std::move(newElement));
  356. return ret;
  357. }
  358. else {
  359. return nullptr;
  360. }
  361. }
  362. GridElement* MandelView::searchUnder(int level, GridIndex i, GridIndex j, int recursionLevel)
  363. {
  364. if (recursionLevel == 0)
  365. return nullptr;
  366. auto& grid = getGrid(level);
  367. auto& gridUnder = getGrid(level - 1);
  368. GridIndex ai = i * 2;
  369. GridIndex aj = j * 2;
  370. GridElement* u00 = gridUnder.getCell(ai, aj);
  371. GridElement* u01 = gridUnder.getCell(ai, aj + 1);
  372. GridElement* u10 = gridUnder.getCell(ai + 1, aj);
  373. GridElement* u11 = gridUnder.getCell(ai + 1, aj + 1);
  374. /*if ( u00 == nullptr
  375. || u01 == nullptr
  376. || u10 == nullptr
  377. || u11 == nullptr) {
  378. auto abFound = searchUnder(level + 1, ai, aj, recursionLevel - 1);
  379. if (abFound)
  380. above = abFound;
  381. }*/
  382. if ( u00 != nullptr
  383. && u01 != nullptr
  384. && u10 != nullptr
  385. && u11 != nullptr) {
  386. auto newElement = std::make_unique<GridElement>(
  387. false, std::make_shared<QuadImage>(u00->img, u01->img, u10->img, u11->img)
  388. );
  389. GridElement* ret = newElement.get();
  390. grid.setCell(i, j, std::move(newElement));
  391. return ret;
  392. }
  393. else {
  394. return nullptr;
  395. }
  396. }
  397. void MandelView::paint(const mnd::MandelViewport& mvp, QPainter& qp)
  398. {
  399. mnd::Real dpp = mvp.width / width;
  400. int level = getLevel(dpp) - 1;
  401. auto& grid = getGrid(level);
  402. mnd::Real gw = getDpp(level) * chunkSize;
  403. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  404. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  405. garbageCollect(level, (left + right) / 2, (top + bottom) / 2);
  406. emit calcer.setCurrentLevel(level);
  407. mnd::Real w = width * gw / mvp.width;
  408. auto [realXLeft, realYTop] = grid.getPositions(left, top);
  409. realXLeft = ((realXLeft - mvp.x) * mnd::Real(width)) / mvp.width;
  410. realYTop = ((realYTop - mvp.y) * mnd::Real(height)) / mvp.height;
  411. for(GridIndex i = left; i <= right; i++) {
  412. for(GridIndex j = top; j <= bottom; j++) {
  413. mnd::Real x = w * int(i - left) + realXLeft;
  414. mnd::Real y = w * int(j - top) + realYTop;
  415. GridElement* t = grid.getCell(i, j);
  416. if (t == nullptr) {
  417. auto under = searchUnder(level, i, j, 1);
  418. if (under) {
  419. t = under;
  420. }
  421. else {
  422. auto above = searchAbove(level, i, j, 3);
  423. if (above) {
  424. t = above;
  425. }
  426. }
  427. }
  428. if (t != nullptr) {
  429. t->img->drawRect(float(x), float(y), float(w), float(w));
  430. /*glBegin(GL_LINE_LOOP);
  431. glVertex2f(float(x), float(y));
  432. glVertex2f(float(x) + float(w), float(y));
  433. glVertex2f(float(x) + float(w), float(y) + float(w));
  434. glVertex2f(float(x), float(y) + float(w));
  435. glEnd();*/
  436. if (!t->enoughResolution) {
  437. calcer.calc(grid, level, i, j, t->img->getRecalcPriority());
  438. }
  439. }
  440. else {
  441. calcer.calc(grid, level, i, j, 1000);
  442. this->empty->drawRect(float(x), float(y), float(w), float(w));
  443. }
  444. }
  445. }
  446. }
  447. void MandelView::cellReady(int level, GridIndex i, GridIndex j, Bitmap<RGBColor>* bmp)
  448. {
  449. this->getGrid(level).setCell(i, j,
  450. std::make_unique<GridElement>(true, std::make_shared<TextureClip>(std::make_shared<Texture>(*bmp))));
  451. delete bmp;
  452. emit redrawRequested();
  453. }
  454. MandelWidget::MandelWidget(mnd::MandelContext& ctxt, mnd::MandelGenerator* generator, QWidget* parent) :
  455. QOpenGLWidget{ parent },
  456. mndContext{ ctxt },
  457. generator{ generator },
  458. gradient{ Gradient::defaultGradient() }
  459. {
  460. this->setContentsMargins(0, 0, 0, 0);
  461. this->setSizePolicy(QSizePolicy::Expanding,
  462. QSizePolicy::Expanding);
  463. qRegisterMetaType<GridIndex>("GridIndex");
  464. this->format().setSwapInterval(1);
  465. /*gradient = Gradient {
  466. {
  467. { RGBColor{ 0, 0, 0 }, 0 },
  468. { RGBColor{ 180, 20, 10 }, 30 },
  469. { RGBColor{ 210, 180, 15 }, 70 },
  470. { RGBColor{ 160, 220, 45 }, 170 },
  471. { RGBColor{ 50, 150, 170 }, 300 },
  472. }
  473. };*/
  474. }
  475. MandelWidget::~MandelWidget()
  476. {
  477. }
  478. void MandelWidget::setGradient(Gradient g)
  479. {
  480. this->gradient = std::move(g);
  481. if (mandelView) {
  482. mandelView->clearCells();
  483. mandelView->calcer.changeState();
  484. }
  485. emit update();
  486. }
  487. void MandelWidget::setSmoothColoring(bool sc)
  488. {
  489. if (sc != mandelInfo.smooth) {
  490. mandelInfo.smooth = sc;
  491. if (mandelView) {
  492. mandelView->clearCells();
  493. emit update();
  494. }
  495. }
  496. }
  497. void MandelWidget::setDisplayInfo(bool di)
  498. {
  499. if (di != this->displayInfo) {
  500. this->displayInfo = di;
  501. emit update();
  502. }
  503. }
  504. void MandelWidget::setMaxIterations(int maxIter)
  505. {
  506. if (mandelInfo.maxIter != maxIter) {
  507. mandelInfo.maxIter = maxIter;
  508. if (mandelView) {
  509. mandelView->clearCells();
  510. mandelView->calcer.clearAll();
  511. mandelView->calcer.changeState();
  512. }
  513. emit update();
  514. }
  515. }
  516. void MandelWidget::setJuliaPos(const mnd::Real& x, const mnd::Real& y)
  517. {
  518. mandelInfo.juliaX = x;
  519. mandelInfo.juliaY = y;
  520. if (mandelView)
  521. mandelView->calcer.changeState();
  522. emit update();
  523. }
  524. void MandelWidget::setGenerator(mnd::MandelGenerator* generator)
  525. {
  526. if (this->generator != generator) {
  527. this->generator = generator;
  528. if (mandelView)
  529. mandelView->setGenerator(generator);
  530. }
  531. }
  532. void MandelWidget::clearAll(void)
  533. {
  534. mandelView->clearCells();
  535. mandelView->calcer.clearAll();
  536. }
  537. void MandelWidget::initializeGL(void)
  538. {
  539. this->context()->functions()->glClearColor(0, 0, 0, 0);
  540. this->context()->makeCurrent(nullptr);
  541. glDisable(GL_DEPTH_TEST);
  542. // looks not even better
  543. glEnable(GL_FRAMEBUFFER_SRGB);
  544. //glShadeModel(GL_SMOOTH);
  545. mandelView = nullptr;
  546. requestRecalc();
  547. }
  548. void MandelWidget::resizeGL(int w, int h)
  549. {
  550. double aspect = double(w) / h;
  551. currentViewport.height = currentViewport.width / aspect;
  552. targetViewport = currentViewport;
  553. float x = this->devicePixelRatioF();
  554. glViewport(0, 0, w * x, h * x);
  555. if (mandelView.get() != nullptr) {
  556. mandelView->width = w;
  557. mandelView->height = h;
  558. //printf("resize: %d, %d\n", w, h);
  559. }
  560. }
  561. void MandelWidget::paintGL(void)
  562. {
  563. if (mandelView == nullptr) {
  564. mandelView = std::make_unique<MandelView>(generator, *this);
  565. QObject::connect(mandelView.get(), &MandelView::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  566. }
  567. int width = this->width();
  568. int height = this->height();
  569. float x = this->devicePixelRatioF();
  570. mandelView->width = width * x;
  571. mandelView->height = height * x;
  572. //glViewport(0, 0, width, height);
  573. glMatrixMode(GL_PROJECTION);
  574. glLoadIdentity();
  575. #ifdef QT_OPENGL_ES_1
  576. glOrthof(0, width * x, height * x, 0, -1.0, 1.0);
  577. #else
  578. glOrtho(0, width * x, height * x, 0, -1.0, 1.0);
  579. #endif
  580. glMatrixMode(GL_MODELVIEW);
  581. glLoadIdentity();
  582. glClear(GL_COLOR_BUFFER_BIT);
  583. updateAnimations();
  584. QPainter painter{ this };
  585. mandelView->paint(this->currentViewport, painter);
  586. if (rubberbanding)
  587. drawRubberband();
  588. if (displayInfo)
  589. drawInfo();
  590. if (selectingPoint)
  591. drawPoint();
  592. }
  593. void MandelWidget::updateAnimations(void)
  594. {
  595. if (mnd::abs(currentViewport.width / targetViewport.width - 1.0) < 0.1e-5
  596. && mnd::abs(currentViewport.height / targetViewport.height - 1.0) < 0.1e-5) {
  597. // animation finished
  598. currentViewport = targetViewport;
  599. }
  600. else {
  601. auto now = std::chrono::high_resolution_clock::now();
  602. auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastAnimUpdate).count();
  603. const mnd::Real factor = mnd::Real(::pow(0.97, millis));
  604. const mnd::Real one(1.0);
  605. currentViewport.x = currentViewport.x * factor + targetViewport.x * (one - factor);
  606. currentViewport.y = currentViewport.y * factor + targetViewport.y * (one - factor);
  607. currentViewport.width = currentViewport.width * factor + targetViewport.width * (one - factor);
  608. currentViewport.height = currentViewport.height * factor + targetViewport.height * (one - factor);
  609. lastAnimUpdate = now;
  610. emit update();
  611. }
  612. }
  613. void MandelWidget::drawRubberband(void)
  614. {
  615. QPainter rubberbandPainter{ this };
  616. rubberbandPainter.fillRect(rubberband, QColor{ 25, 225, 25, 50 });
  617. QPen pen{ QColor{ 10, 200, 10 } };
  618. pen.setWidth(2);
  619. rubberbandPainter.setPen(pen);
  620. rubberbandPainter.drawRect(rubberband);
  621. /*glColor3ub(10, 200, 10);
  622. glBegin(GL_LINE_LOOP);
  623. glVertex2d(rubberband.x(), rubberband.y());
  624. glVertex2d(rubberband.right(), rubberband.y());
  625. glVertex2d(rubberband.right(), rubberband.bottom());
  626. glVertex2d(rubberband.x(), rubberband.bottom());
  627. glEnd();
  628. glEnable(GL_BLEND);
  629. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  630. glColor4f(0.1f, 0.9f, 0.1f, 0.2f);
  631. glBegin(GL_TRIANGLE_FAN);
  632. glVertex2d(rubberband.x(), rubberband.y());
  633. glVertex2d(rubberband.right(), rubberband.y());
  634. glVertex2d(rubberband.right(), rubberband.bottom());
  635. glVertex2d(rubberband.x(), rubberband.bottom());
  636. glEnd();
  637. glDisable(GL_BLEND);*/
  638. }
  639. void MandelWidget::drawInfo(void)
  640. {
  641. const float DIST_FROM_BORDER = 15;
  642. float maxWidth = this->width() - 2 * DIST_FROM_BORDER;
  643. mnd::Real distPerPixel = currentViewport.width / this->width();
  644. float log10 = (mnd::convert<float>(mnd::log(distPerPixel)) + ::logf(maxWidth)) / ::logf(10);
  645. mnd::Real displayDist = mnd::pow(mnd::Real(10), ::floor(log10));
  646. float pixels = mnd::convert<float>(displayDist / distPerPixel);
  647. int factor = 1;
  648. for (int i = 9; i > 1; i--) {
  649. if (pixels * i < maxWidth) {
  650. factor *= i;
  651. pixels *= i;
  652. displayDist *= i;
  653. break;
  654. }
  655. }
  656. std::stringstream dis;
  657. if (::abs(log10) < 3) {
  658. dis << mnd::convert<float>(displayDist);
  659. }
  660. else {
  661. dis << factor << "e" << int(::floor(log10));
  662. }
  663. if (maxWidth > 400) {
  664. dis << "; per pixel: " << distPerPixel;
  665. }
  666. float lineY = this->height() - DIST_FROM_BORDER;
  667. float lineXEnd = DIST_FROM_BORDER + pixels;
  668. QPainter infoPainter{ this };
  669. infoPainter.setPen(Qt::white);
  670. infoPainter.setFont(QFont("Arial", 12));
  671. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ lineXEnd, lineY });
  672. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ DIST_FROM_BORDER, lineY - 5 });
  673. infoPainter.drawLine(QPointF{ lineXEnd, lineY }, QPointF{ lineXEnd, lineY - 5 });
  674. infoPainter.drawText(int(DIST_FROM_BORDER), int(lineY - 20), int(lineXEnd - DIST_FROM_BORDER), 20,
  675. Qt::AlignCenter, QString::fromStdString(dis.str()));
  676. infoPainter.end();
  677. }
  678. void MandelWidget::drawPoint(void)
  679. {
  680. QPainter pointPainter{ this };
  681. pointPainter.setPen(QColor{ 255, 255, 255 });
  682. pointPainter.drawLine(0, pointY, width(), pointY);
  683. pointPainter.drawLine(pointX, 0, pointX, height());
  684. /*glColor3ub(255, 255, 255);
  685. glBegin(GL_LINES);
  686. glVertex2f(0, pointY);
  687. glVertex2f(width(), pointY);
  688. glVertex2f(pointX, 0);
  689. glVertex2f(pointX, height());
  690. glEnd();*/
  691. }
  692. void MandelWidget::zoom(float scale, float x, float y)
  693. {
  694. targetViewport.zoom(scale, x, y);
  695. lastAnimUpdate = std::chrono::high_resolution_clock::now();
  696. //currentViewport.zoom(scale, x, y);
  697. requestRecalc();
  698. }
  699. void MandelWidget::setViewport(const mnd::MandelViewport& viewport)
  700. {
  701. targetViewport = viewport;
  702. targetViewport.adjustAspectRatio(this->width(), this->height());
  703. currentViewport = targetViewport;
  704. //lastAnimUpdate = std::chrono::high_resolution_clock::now();
  705. //currentViewport.zoom(scale, x, y);
  706. requestRecalc();
  707. }
  708. void MandelWidget::selectPoint(void)
  709. {
  710. this->selectingPoint = true;
  711. this->setMouseTracking(true);
  712. }
  713. void MandelWidget::stopSelectingPoint(void)
  714. {
  715. this->selectingPoint = false;
  716. this->setMouseTracking(false);
  717. }
  718. void MandelWidget::requestRecalc()
  719. {
  720. emit update();
  721. }
  722. void MandelWidget::resizeEvent(QResizeEvent* re)
  723. {
  724. QOpenGLWidget::resizeEvent(re);
  725. double aspect = double(geometry().width()) / geometry().height();
  726. currentViewport.height = currentViewport.width / aspect;
  727. targetViewport = currentViewport;
  728. if (mandelView.get() != nullptr) {
  729. mandelView->width = this->width();
  730. mandelView->height = this->height();
  731. }
  732. requestRecalc();
  733. }
  734. void MandelWidget::mousePressEvent(QMouseEvent* me)
  735. {
  736. QOpenGLWidget::mousePressEvent(me);
  737. if (me->button() == Qt::RightButton) {
  738. rubberbanding = true;
  739. rubberband.setCoords(me->x(), me->y(), me->x(), me->y());
  740. emit repaint();
  741. me->accept();
  742. }
  743. else if (me->button() == Qt::LeftButton) {
  744. dragging = true;
  745. dragX = me->x();
  746. dragY = me->y();
  747. me->accept();
  748. }
  749. }
  750. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  751. {
  752. QOpenGLWidget::mouseMoveEvent(me);
  753. if (rubberbanding) {
  754. QRectF& rect = rubberband;
  755. double aspect = double(geometry().width()) / geometry().height();
  756. rect.setBottomRight(QPoint(me->x(), me->y()));
  757. if (rect.width() > rect.height() * aspect)
  758. rect.setHeight(rect.width() / aspect);
  759. else
  760. rect.setWidth(rect.height() * aspect);
  761. emit repaint();
  762. }
  763. else if (selectingPoint) {
  764. pointX = me->x();
  765. pointY = me->y();
  766. emit repaint();
  767. }
  768. else if (dragging) {
  769. double deltaX = me->x() - dragX;
  770. double deltaY = me->y() - dragY;
  771. this->currentViewport.x -= deltaX * currentViewport.width / this->width();
  772. this->currentViewport.y -= deltaY * currentViewport.height / this->height();
  773. targetViewport = currentViewport;
  774. dragX = me->x(); dragY = me->y();
  775. emit repaint();
  776. }
  777. me->accept();
  778. }
  779. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  780. {
  781. QOpenGLWidget::mouseReleaseEvent(me);
  782. if (rubberbanding) {
  783. QRect rect = rubberband.toRect();
  784. if(rect.width() != 0 && rect.height() != 0) {
  785. QRect full = this->geometry();
  786. targetViewport.x += mnd::Real(rect.left()) * targetViewport.width / full.width();
  787. targetViewport.y += mnd::Real(rect.top()) * targetViewport.height / full.height();
  788. targetViewport.width *= mnd::Real(rect.width()) / full.width();
  789. targetViewport.height *= mnd::Real(rect.height()) / full.height();
  790. targetViewport.normalize();
  791. currentViewport = targetViewport;
  792. }
  793. requestRecalc();
  794. rubberbanding = false;
  795. }
  796. else if (selectingPoint) {
  797. selectingPoint = false;
  798. this->setMouseTracking(false);
  799. mnd::Real x = currentViewport.x + currentViewport.width * mnd::convert<mnd::Real>(float(me->x()) / width());
  800. mnd::Real y = currentViewport.y + currentViewport.height * mnd::convert<mnd::Real>(float(me->y()) / height());
  801. emit pointSelected(x, y);
  802. emit repaint();
  803. }
  804. dragging = false;
  805. //requestRecalc();
  806. }
  807. void MandelWidget::wheelEvent(QWheelEvent* we)
  808. {
  809. QOpenGLWidget::wheelEvent(we);
  810. float x = float(we->x()) / this->width();
  811. float y = float(we->y()) / this->height();
  812. float scale = ::powf(0.9975f, we->angleDelta().y());
  813. zoom(scale, x, y);
  814. if (!we->pixelDelta().isNull())
  815. this->currentViewport = this->targetViewport;
  816. we->accept();
  817. }
  818. /*void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  819. {
  820. if (bitmap != nullptr) {
  821. delete bitmap;
  822. emit repaint();
  823. }
  824. }*/