MandelWidget.cpp 25 KB

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