1
0

MandelWidget.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. #include "MandelWidget.h"
  2. #include <cmath>
  3. #include <sstream>
  4. using namespace mnd;
  5. #include <QPainter>
  6. #include <QTimer>
  7. #include <cstdio>
  8. Texture::Texture(const Bitmap<RGBColor>& bitmap, GLint param)
  9. {
  10. glGenTextures(1, &id);
  11. glBindTexture(GL_TEXTURE_2D, id);
  12. //int lineLength = (bitmap.width * 3 + 3) & ~3;
  13. /*std::unique_ptr<unsigned char[]> pixels = std::make_unique<unsigned char[]>(lineLength * bitmap.height);
  14. for (int i = 0; i < bitmap.width; i++) {
  15. for (int j = 0; j < bitmap.height; j++) {
  16. int index = i * 3 + j * lineLength;
  17. RGBColor c = bitmap.get(i, j);
  18. pixels[index] = c.r;
  19. pixels[index + 1] = c.g;
  20. pixels[index + 2] = c.b;
  21. }
  22. }*/
  23. 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()));
  24. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  26. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param);
  27. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param);
  28. }
  29. Texture::~Texture(void)
  30. {
  31. if (id != 0)
  32. glDeleteTextures(1, &id);
  33. }
  34. Texture::Texture(Texture&& other) :
  35. id{ other.id }
  36. {
  37. other.id = 0;
  38. }
  39. Texture& Texture::operator=(Texture&& other)
  40. {
  41. this->id = other.id;
  42. other.id = 0;
  43. return *this;
  44. }
  45. void Texture::bind(void) const
  46. {
  47. glBindTexture(GL_TEXTURE_2D, id);
  48. }
  49. void Texture::drawRect(float x, float y, float width, float height)
  50. {
  51. glColor3ub(255, 255, 255);
  52. glEnable(GL_TEXTURE_2D);
  53. bind();
  54. glBegin(GL_TRIANGLE_STRIP);
  55. glTexCoord2f(0, 0);
  56. glVertex2f(x, y);
  57. glTexCoord2f(1, 0);
  58. glVertex2f(x + width, y);
  59. glTexCoord2f(0, 1);
  60. glVertex2f(x, y + height);
  61. glTexCoord2f(1, 1);
  62. glVertex2f(x + width, y + height);
  63. glEnd();
  64. glDisable(GL_TEXTURE_2D);
  65. }
  66. CellImage::~CellImage(void)
  67. {
  68. }
  69. TextureClip::~TextureClip(void)
  70. {
  71. }
  72. void TextureClip::drawRect(float x, float y, float width, float height)
  73. {
  74. glColor3ub(255, 255, 255);
  75. glEnable(GL_TEXTURE_2D);
  76. glBindTexture(GL_TEXTURE_2D, texture->getId());
  77. glBegin(GL_TRIANGLE_STRIP);
  78. glTexCoord2f(tx, ty);
  79. glVertex2f(x, y);
  80. glTexCoord2f(tx + tw, ty);
  81. glVertex2f(x + width, y);
  82. glTexCoord2f(tx, ty + th);
  83. glVertex2f(x, y + height);
  84. glTexCoord2f(tx + tw, ty + th);
  85. glVertex2f(x + width, y + height);
  86. glEnd();
  87. glDisable(GL_TEXTURE_2D);
  88. }
  89. TextureClip TextureClip::clip(float x, float y, float w, float h)
  90. {
  91. float tx = this->tx + x * this->tw;
  92. float ty = this->ty + y * this->th;
  93. float tw = this->tw * w;
  94. float th = this->th * h;
  95. return TextureClip{ this->texture, tx, ty, tw, th };
  96. }
  97. std::shared_ptr<CellImage> TextureClip::clip(short i, short j)
  98. {
  99. return std::make_shared<TextureClip>(clip(i * 0.5f, j * 0.5f, 0.5f, 0.5f));
  100. }
  101. int TextureClip::getRecalcPriority() const
  102. {
  103. return int(1.0f / tw);
  104. }
  105. QuadImage::~QuadImage(void)
  106. {
  107. }
  108. void QuadImage::drawRect(float x, float y, float width, float height)
  109. {
  110. for (int i = 0; i < 2; i++) {
  111. for (int j = 0; j < 2; j++) {
  112. this->cells[i][j]->drawRect(x + i * 0.5f * width,
  113. y + j * 0.5f * height,
  114. width * 0.5f,
  115. height * 0.5f);
  116. }
  117. }
  118. }
  119. std::shared_ptr<CellImage> QuadImage::clip(short i, short j)
  120. {
  121. return cells[i][j];
  122. }
  123. int QuadImage::getRecalcPriority() const
  124. {
  125. return 1;
  126. }
  127. TexGrid::TexGrid(MandelView& owner, int level) :
  128. owner{ owner },
  129. level{ level },
  130. dpp{ owner.getDpp(level) }
  131. {
  132. }
  133. std::pair<GridIndex, GridIndex> TexGrid::getCellIndices(mnd::Real x, mnd::Real y)
  134. {
  135. return { GridIndex(mnd::floor(x / dpp / MandelView::chunkSize)), GridIndex(mnd::floor(y / dpp / MandelView::chunkSize)) };
  136. }
  137. std::pair<mnd::Real, mnd::Real> TexGrid::getPositions(GridIndex x, GridIndex y)
  138. {
  139. return { mnd::Real(x) * dpp * MandelView::chunkSize, mnd::Real(y) * dpp * MandelView::chunkSize };
  140. }
  141. GridElement* TexGrid::getCell(GridIndex i, GridIndex j)
  142. {
  143. auto cIt = cells.find({i, j});
  144. if (cIt != cells.end()) {
  145. return cIt->second.get();
  146. }
  147. else {
  148. return nullptr;
  149. }
  150. }
  151. void TexGrid::setCell(GridIndex i, GridIndex j, std::unique_ptr<GridElement> tex)
  152. {
  153. cells[{i, j}] = std::move(tex);
  154. }
  155. void TexGrid::clearCells(void)
  156. {
  157. cells.clear();
  158. }
  159. void TexGrid::clearUncleanCells(void)
  160. {
  161. for (auto it = cells.begin(); it != cells.end();) {
  162. if (it->second->img->getRecalcPriority() > 1)
  163. cells.erase(it++);
  164. else ++it;
  165. }
  166. }
  167. void Job::run(void)
  168. {
  169. auto [absX, absY] = grid->getPositions(i, j);
  170. mnd::Real gw = grid->dpp * MandelView::chunkSize;
  171. Bitmap<float> f(MandelView::chunkSize, MandelView::chunkSize);
  172. mnd::MandelInfo mi = owner.getMandelInfo();
  173. mi.view.x = absX;
  174. mi.view.y = absY;
  175. mi.view.width = mi.view.height = gw;
  176. mi.bWidth = mi.bHeight = MandelView::chunkSize;
  177. try {
  178. generator->generate(mi, f.pixels.get());
  179. auto* rgb = new Bitmap<RGBColor>(f.map<RGBColor>([&mi, this] (float i) {
  180. return i >= mi.maxIter ? RGBColor{ 0, 0, 0 } : gradient.get(i);
  181. }));
  182. emit done(level, i, j, calcState, rgb);
  183. }
  184. catch(std::exception& ex) {
  185. printf("wat: %s?!\n", ex.what()); fflush(stdout);
  186. exit(1);
  187. }
  188. catch(...) {
  189. printf("wat?!\n"); fflush(stdout);
  190. exit(1);
  191. }
  192. }
  193. Calcer::Calcer(mnd::MandelGenerator* generator, MandelWidget& owner) :
  194. jobsMutex{ QMutex::Recursive },
  195. generator{ generator },
  196. threadPool{ std::make_unique<QThreadPool>() },
  197. owner{ owner },
  198. gradient{ owner.getGradient() }
  199. {
  200. threadPool->setMaxThreadCount(1);
  201. }
  202. void Calcer::clearAll(void)
  203. {
  204. this->threadPool->clear();
  205. }
  206. void Calcer::calc(TexGrid& grid, int level, GridIndex i, GridIndex j, int priority)
  207. {
  208. jobsMutex.lock();
  209. if (jobs.find({ level, i, j }) == jobs.end()) {
  210. Job* job = new Job(generator, gradient, owner, &grid, level, i, j, calcState);
  211. connect(job, &Job::done, this, &Calcer::redirect);
  212. connect(job, &QObject::destroyed, this, [this, level, i, j] () { this->notFinished(level, i, j); });
  213. jobs.emplace(std::tuple{level, i, j}, job);
  214. threadPool->start(job, priority);
  215. }
  216. jobsMutex.unlock();
  217. }
  218. void Calcer::setCurrentLevel(int level)
  219. {
  220. if (this->currentLevel != level) {
  221. this->currentLevel = level;
  222. std::vector<QRunnable*> toCancel;
  223. jobsMutex.lock();
  224. for (auto&[tup, job] : jobs) {
  225. auto& [level, i, j] = tup;
  226. if(level != currentLevel) {
  227. toCancel.push_back(job);
  228. }
  229. }
  230. jobsMutex.unlock();
  231. for (auto* job : toCancel) {
  232. if (threadPool->tryTake(job)) {
  233. delete job;
  234. }
  235. }
  236. }
  237. }
  238. void Calcer::notFinished(int level, GridIndex i, GridIndex j)
  239. {
  240. jobsMutex.lock();
  241. jobs.erase({ level, i, j });
  242. jobsMutex.unlock();
  243. }
  244. void Calcer::redirect(int level, GridIndex i, GridIndex j, long calcState, Bitmap<RGBColor>* bmp)
  245. {
  246. jobsMutex.lock();
  247. jobs.erase({ level, i, j });
  248. jobsMutex.unlock();
  249. if (this->calcState == calcState) {
  250. emit done(level, i, j, bmp);
  251. }
  252. else {
  253. delete bmp;
  254. }
  255. }
  256. const int MandelView::chunkSize = 256;
  257. MandelView::MandelView(mnd::MandelGenerator* generator, MandelWidget& owner) :
  258. generator{ generator },
  259. calcer{ generator, owner },
  260. owner{ owner }
  261. {
  262. Bitmap<RGBColor> emp(8, 8);
  263. for(auto i = 0; i < emp.width; i++) {
  264. for(auto j = 0; j < emp.height; j++) {
  265. if((i + j) & 0x1) { // if i+j is odd
  266. emp.get(i, j) = RGBColor{ 255, 255, 255 };
  267. }
  268. else {
  269. emp.get(i, j) = RGBColor{ 120, 120, 120 };
  270. }
  271. }
  272. }
  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)
  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::paintGL(void)
  549. {
  550. if (mandelView == nullptr) {
  551. mandelView = std::make_unique<MandelView>(generator, *this);
  552. QObject::connect(mandelView.get(), &MandelView::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  553. }
  554. int width = this->width();
  555. int height = this->height();
  556. mandelView->width = width;
  557. mandelView->height = height;
  558. glViewport(0, 0, width, height);
  559. glMatrixMode(GL_PROJECTION);
  560. glLoadIdentity();
  561. #ifdef QT_OPENGL_ES_1
  562. glOrthof(0, width, height, 0, -1.0, 1.0);
  563. #else
  564. glOrtho(0, width, height, 0, -1.0, 1.0);
  565. #endif
  566. glMatrixMode(GL_MODELVIEW);
  567. glClear(GL_COLOR_BUFFER_BIT);
  568. glLoadIdentity();
  569. updateAnimations();
  570. mandelView->paint(this->currentViewport);
  571. if (rubberbanding)
  572. drawRubberband();
  573. if (displayInfo)
  574. drawInfo();
  575. if (selectingPoint)
  576. drawPoint();
  577. }
  578. void MandelWidget::updateAnimations(void)
  579. {
  580. if (mnd::abs(currentViewport.width / targetViewport.width - 1.0) < 0.1e-5
  581. && mnd::abs(currentViewport.height / targetViewport.height - 1.0) < 0.1e-5) {
  582. // animation finished
  583. currentViewport = targetViewport;
  584. }
  585. else {
  586. auto now = std::chrono::high_resolution_clock::now();
  587. auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastAnimUpdate).count();
  588. const mnd::Real factor = mnd::Real(::pow(0.97, millis));
  589. const mnd::Real one(1.0);
  590. currentViewport.x = currentViewport.x * factor + targetViewport.x * (one - factor);
  591. currentViewport.y = currentViewport.y * factor + targetViewport.y * (one - factor);
  592. currentViewport.width = currentViewport.width * factor + targetViewport.width * (one - factor);
  593. currentViewport.height = currentViewport.height * factor + targetViewport.height * (one - factor);
  594. lastAnimUpdate = now;
  595. emit update();
  596. }
  597. }
  598. void MandelWidget::drawRubberband(void)
  599. {
  600. glColor3ub(10, 200, 10);
  601. glBegin(GL_LINE_LOOP);
  602. glVertex2d(rubberband.x(), rubberband.y());
  603. glVertex2d(rubberband.right(), rubberband.y());
  604. glVertex2d(rubberband.right(), rubberband.bottom());
  605. glVertex2d(rubberband.x(), rubberband.bottom());
  606. glEnd();
  607. glEnable(GL_BLEND);
  608. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  609. glColor4f(0.1f, 0.9f, 0.1f, 0.2f);
  610. glBegin(GL_TRIANGLE_FAN);
  611. glVertex2d(rubberband.x(), rubberband.y());
  612. glVertex2d(rubberband.right(), rubberband.y());
  613. glVertex2d(rubberband.right(), rubberband.bottom());
  614. glVertex2d(rubberband.x(), rubberband.bottom());
  615. glEnd();
  616. glDisable(GL_BLEND);
  617. }
  618. void MandelWidget::drawInfo(void)
  619. {
  620. const float DIST_FROM_BORDER = 15;
  621. float maxWidth = this->width() - 2 * DIST_FROM_BORDER;
  622. mnd::Real distPerPixel = currentViewport.width / this->width();
  623. float log10 = (mnd::convert<float>(mnd::log(distPerPixel)) + ::logf(maxWidth)) / ::logf(10);
  624. mnd::Real displayDist = mnd::pow(mnd::Real(10), ::floor(log10));
  625. float pixels = mnd::convert<float>(displayDist / distPerPixel);
  626. int factor = 1;
  627. for (int i = 9; i > 1; i--) {
  628. if (pixels * i < maxWidth) {
  629. factor *= i;
  630. pixels *= i;
  631. displayDist *= i;
  632. break;
  633. }
  634. }
  635. std::stringstream dis;
  636. if (::abs(log10) < 3) {
  637. dis << mnd::convert<float>(displayDist);
  638. }
  639. else {
  640. dis << factor << "e" << int(::floor(log10));
  641. }
  642. if (maxWidth > 400) {
  643. dis << "; per pixel: " << distPerPixel;
  644. }
  645. float lineY = this->height() - DIST_FROM_BORDER;
  646. float lineXEnd = DIST_FROM_BORDER + pixels;
  647. QPainter infoPainter{ this };
  648. infoPainter.setPen(Qt::white);
  649. infoPainter.setFont(QFont("Arial", 12));
  650. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ lineXEnd, lineY });
  651. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ DIST_FROM_BORDER, lineY - 5 });
  652. infoPainter.drawLine(QPointF{ lineXEnd, lineY }, QPointF{ lineXEnd, lineY - 5 });
  653. infoPainter.drawText(int(DIST_FROM_BORDER), int(lineY - 20), int(lineXEnd - DIST_FROM_BORDER), 20,
  654. Qt::AlignCenter, QString::fromStdString(dis.str()));
  655. infoPainter.end();
  656. }
  657. void MandelWidget::drawPoint(void)
  658. {
  659. glColor3ub(255, 255, 255);
  660. glBegin(GL_LINES);
  661. glVertex2f(0, pointY);
  662. glVertex2f(width(), pointY);
  663. glVertex2f(pointX, 0);
  664. glVertex2f(pointX, height());
  665. glEnd();
  666. }
  667. void MandelWidget::zoom(float scale, float x, float y)
  668. {
  669. targetViewport.zoom(scale, x, y);
  670. lastAnimUpdate = std::chrono::high_resolution_clock::now();
  671. //currentViewport.zoom(scale, x, y);
  672. requestRecalc();
  673. }
  674. void MandelWidget::setViewport(const mnd::MandelViewport& viewport)
  675. {
  676. targetViewport = viewport;
  677. targetViewport.adjustAspectRatio(this->width(), this->height());
  678. currentViewport = targetViewport;
  679. //lastAnimUpdate = std::chrono::high_resolution_clock::now();
  680. //currentViewport.zoom(scale, x, y);
  681. requestRecalc();
  682. }
  683. void MandelWidget::selectPoint(void)
  684. {
  685. this->selectingPoint = true;
  686. this->setMouseTracking(true);
  687. }
  688. void MandelWidget::stopSelectingPoint(void)
  689. {
  690. this->selectingPoint = false;
  691. this->setMouseTracking(false);
  692. }
  693. void MandelWidget::requestRecalc()
  694. {
  695. emit update();
  696. }
  697. void MandelWidget::resizeEvent(QResizeEvent* re)
  698. {
  699. QOpenGLWidget::resizeEvent(re);
  700. double aspect = double(geometry().width()) / geometry().height();
  701. currentViewport.height = currentViewport.width / aspect;
  702. targetViewport = currentViewport;
  703. if (mandelView.get() != nullptr) {
  704. mandelView->width = this->width();
  705. mandelView->height = this->height();
  706. }
  707. requestRecalc();
  708. }
  709. void MandelWidget::mousePressEvent(QMouseEvent* me)
  710. {
  711. QOpenGLWidget::mousePressEvent(me);
  712. if (me->button() == Qt::RightButton) {
  713. rubberbanding = true;
  714. rubberband.setCoords(me->x(), me->y(), me->x(), me->y());
  715. emit repaint();
  716. me->accept();
  717. }
  718. else if (me->button() == Qt::LeftButton) {
  719. dragging = true;
  720. dragX = me->x();
  721. dragY = me->y();
  722. me->accept();
  723. }
  724. }
  725. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  726. {
  727. QOpenGLWidget::mouseMoveEvent(me);
  728. if (rubberbanding) {
  729. QRectF& rect = rubberband;
  730. double aspect = double(geometry().width()) / geometry().height();
  731. rect.setBottomRight(QPoint(me->x(), me->y()));
  732. if (rect.width() > rect.height() * aspect)
  733. rect.setHeight(rect.width() / aspect);
  734. else
  735. rect.setWidth(rect.height() * aspect);
  736. emit repaint();
  737. }
  738. else if (selectingPoint) {
  739. pointX = me->x();
  740. pointY = me->y();
  741. emit repaint();
  742. }
  743. else if (dragging) {
  744. double deltaX = me->x() - dragX;
  745. double deltaY = me->y() - dragY;
  746. this->currentViewport.x -= deltaX * currentViewport.width / this->width();
  747. this->currentViewport.y -= deltaY * currentViewport.height / this->height();
  748. targetViewport = currentViewport;
  749. dragX = me->x(); dragY = me->y();
  750. emit repaint();
  751. }
  752. me->accept();
  753. }
  754. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  755. {
  756. QOpenGLWidget::mouseReleaseEvent(me);
  757. if (rubberbanding) {
  758. QRect rect = rubberband.toRect();
  759. if(rect.width() != 0 && rect.height() != 0) {
  760. QRect full = this->geometry();
  761. targetViewport.x += mnd::Real(rect.left()) * targetViewport.width / full.width();
  762. targetViewport.y += mnd::Real(rect.top()) * targetViewport.height / full.height();
  763. targetViewport.width *= mnd::Real(rect.width()) / full.width();
  764. targetViewport.height *= mnd::Real(rect.height()) / full.height();
  765. targetViewport.normalize();
  766. currentViewport = targetViewport;
  767. }
  768. requestRecalc();
  769. rubberbanding = false;
  770. }
  771. else if (selectingPoint) {
  772. selectingPoint = false;
  773. this->setMouseTracking(false);
  774. mnd::Real x = currentViewport.x + currentViewport.width * mnd::convert<mnd::Real>(float(me->x()) / width());
  775. mnd::Real y = currentViewport.y + currentViewport.height * mnd::convert<mnd::Real>(float(me->y()) / height());
  776. emit pointSelected(x, y);
  777. emit repaint();
  778. }
  779. dragging = false;
  780. //requestRecalc();
  781. }
  782. void MandelWidget::wheelEvent(QWheelEvent* we)
  783. {
  784. QOpenGLWidget::wheelEvent(we);
  785. float x = float(we->x()) / this->width();
  786. float y = float(we->y()) / this->height();
  787. float scale = ::powf(0.9975f, we->angleDelta().y());
  788. zoom(scale, x, y);
  789. if (!we->pixelDelta().isNull())
  790. this->currentViewport = this->targetViewport;
  791. we->accept();
  792. }
  793. /*void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  794. {
  795. if (bitmap != nullptr) {
  796. delete bitmap;
  797. emit repaint();
  798. }
  799. }*/