MandelWidget.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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. auto& gl = *this->context()->functions();
  540. gl.glClearColor(0, 0, 0, 0);
  541. this->context()->makeCurrent(nullptr);
  542. gl.glDisable(GL_DEPTH_TEST);
  543. // looks not even better
  544. gl.glEnable(GL_FRAMEBUFFER_SRGB);
  545. //glShadeModel(GL_SMOOTH);
  546. mandelView = nullptr;
  547. requestRecalc();
  548. }
  549. void MandelWidget::resizeGL(int w, int h)
  550. {
  551. double aspect = double(w) / h;
  552. currentViewport.height = currentViewport.width / aspect;
  553. targetViewport = currentViewport;
  554. float pixelRatio = this->devicePixelRatioF();
  555. glViewport(0, 0, w * pixelRatio, h * pixelRatio);
  556. if (mandelView.get() != nullptr) {
  557. mandelView->width = w;
  558. mandelView->height = h;
  559. //printf("resize: %d, %d\n", w, h);
  560. }
  561. }
  562. void MandelWidget::paintGL(void)
  563. {
  564. if (mandelView == nullptr) {
  565. mandelView = std::make_unique<MandelView>(generator, *this);
  566. QObject::connect(mandelView.get(), &MandelView::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  567. }
  568. int width = this->width();
  569. int height = this->height();
  570. float pixelRatio = this->devicePixelRatioF();
  571. mandelView->width = width * pixelRatio;
  572. mandelView->height = height * pixelRatio;
  573. //glViewport(0, 0, width, height);
  574. glMatrixMode(GL_PROJECTION);
  575. glLoadIdentity();
  576. #ifdef QT_OPENGL_ES_1
  577. glOrthof(0, width * pixelRatio, height * pixelRatio, 0, -1.0, 1.0);
  578. #else
  579. glOrtho(0, width * pixelRatio, height * pixelRatio, 0, -1.0, 1.0);
  580. #endif
  581. glMatrixMode(GL_MODELVIEW);
  582. glLoadIdentity();
  583. glClear(GL_COLOR_BUFFER_BIT);
  584. updateAnimations();
  585. QPainter painter{ this };
  586. mandelView->paint(this->currentViewport, painter);
  587. if (rubberbanding)
  588. drawRubberband();
  589. if (displayInfo)
  590. drawInfo();
  591. if (selectingPoint)
  592. drawPoint();
  593. }
  594. void MandelWidget::updateAnimations(void)
  595. {
  596. if (mnd::abs(currentViewport.width / targetViewport.width - 1.0) < 0.1e-5
  597. && mnd::abs(currentViewport.height / targetViewport.height - 1.0) < 0.1e-5) {
  598. // animation finished
  599. currentViewport = targetViewport;
  600. }
  601. else {
  602. auto now = std::chrono::high_resolution_clock::now();
  603. auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastAnimUpdate).count();
  604. const mnd::Real factor = mnd::Real(::pow(0.97, millis));
  605. const mnd::Real one(1.0);
  606. currentViewport.x = currentViewport.x * factor + targetViewport.x * (one - factor);
  607. currentViewport.y = currentViewport.y * factor + targetViewport.y * (one - factor);
  608. currentViewport.width = currentViewport.width * factor + targetViewport.width * (one - factor);
  609. currentViewport.height = currentViewport.height * factor + targetViewport.height * (one - factor);
  610. lastAnimUpdate = now;
  611. emit update();
  612. }
  613. }
  614. void MandelWidget::drawRubberband(void)
  615. {
  616. QPainter rubberbandPainter{ this };
  617. rubberbandPainter.fillRect(rubberband, QColor{ 125, 140, 225, 120 });
  618. QPen pen{ QColor{ 100, 115, 200 } };
  619. pen.setWidth(2);
  620. rubberbandPainter.setPen(pen);
  621. rubberbandPainter.drawRect(rubberband);
  622. }
  623. void MandelWidget::drawInfo(void)
  624. {
  625. const float DIST_FROM_BORDER = 15;
  626. float maxWidth = this->width() - 2 * DIST_FROM_BORDER;
  627. mnd::Real distPerPixel = currentViewport.width / this->width();
  628. float log10 = (mnd::convert<float>(mnd::log(distPerPixel)) + ::logf(maxWidth)) / ::logf(10);
  629. mnd::Real displayDist = mnd::pow(mnd::Real(10), ::floor(log10));
  630. float pixels = mnd::convert<float>(displayDist / distPerPixel);
  631. int factor = 1;
  632. for (int i = 9; i > 1; i--) {
  633. if (pixels * i < maxWidth) {
  634. factor *= i;
  635. pixels *= i;
  636. displayDist *= i;
  637. break;
  638. }
  639. }
  640. std::stringstream dis;
  641. if (::abs(log10) < 3) {
  642. dis << mnd::convert<float>(displayDist);
  643. }
  644. else {
  645. dis << factor << "e" << int(::floor(log10));
  646. }
  647. if (maxWidth > 400) {
  648. dis << "; per pixel: " << distPerPixel;
  649. }
  650. float lineY = this->height() - DIST_FROM_BORDER;
  651. float lineXEnd = DIST_FROM_BORDER + pixels;
  652. QPainter infoPainter{ this };
  653. infoPainter.setPen(Qt::white);
  654. infoPainter.setFont(QFont("Arial", 12));
  655. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ lineXEnd, lineY });
  656. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ DIST_FROM_BORDER, lineY - 5 });
  657. infoPainter.drawLine(QPointF{ lineXEnd, lineY }, QPointF{ lineXEnd, lineY - 5 });
  658. infoPainter.drawText(int(DIST_FROM_BORDER), int(lineY - 20), int(lineXEnd - DIST_FROM_BORDER), 20,
  659. Qt::AlignCenter, QString::fromStdString(dis.str()));
  660. infoPainter.end();
  661. }
  662. void MandelWidget::drawPoint(void)
  663. {
  664. QPainter pointPainter{ this };
  665. pointPainter.setPen(QColor{ 255, 255, 255 });
  666. pointPainter.drawLine(0, pointY, width(), pointY);
  667. pointPainter.drawLine(pointX, 0, pointX, height());
  668. /*glColor3ub(255, 255, 255);
  669. glBegin(GL_LINES);
  670. glVertex2f(0, pointY);
  671. glVertex2f(width(), pointY);
  672. glVertex2f(pointX, 0);
  673. glVertex2f(pointX, height());
  674. glEnd();*/
  675. }
  676. void MandelWidget::zoom(float scale, float x, float y)
  677. {
  678. targetViewport.zoom(scale, x, y);
  679. lastAnimUpdate = std::chrono::high_resolution_clock::now();
  680. //currentViewport.zoom(scale, x, y);
  681. requestRecalc();
  682. }
  683. void MandelWidget::setViewport(const mnd::MandelViewport& viewport)
  684. {
  685. targetViewport = viewport;
  686. targetViewport.adjustAspectRatio(this->width(), this->height());
  687. currentViewport = targetViewport;
  688. //lastAnimUpdate = std::chrono::high_resolution_clock::now();
  689. //currentViewport.zoom(scale, x, y);
  690. requestRecalc();
  691. }
  692. void MandelWidget::selectPoint(void)
  693. {
  694. this->selectingPoint = true;
  695. this->setMouseTracking(true);
  696. }
  697. void MandelWidget::stopSelectingPoint(void)
  698. {
  699. this->selectingPoint = false;
  700. this->setMouseTracking(false);
  701. }
  702. void MandelWidget::requestRecalc()
  703. {
  704. emit update();
  705. }
  706. void MandelWidget::resizeEvent(QResizeEvent* re)
  707. {
  708. QOpenGLWidget::resizeEvent(re);
  709. double aspect = double(geometry().width()) / geometry().height();
  710. currentViewport.height = currentViewport.width / aspect;
  711. targetViewport = currentViewport;
  712. if (mandelView.get() != nullptr) {
  713. mandelView->width = this->width();
  714. mandelView->height = this->height();
  715. }
  716. requestRecalc();
  717. }
  718. void MandelWidget::mousePressEvent(QMouseEvent* me)
  719. {
  720. QOpenGLWidget::mousePressEvent(me);
  721. if (me->button() == Qt::RightButton) {
  722. rubberbanding = true;
  723. rubberband.setCoords(me->x(), me->y(), me->x(), me->y());
  724. emit repaint();
  725. me->accept();
  726. }
  727. else if (me->button() == Qt::LeftButton) {
  728. dragging = true;
  729. dragX = me->x();
  730. dragY = me->y();
  731. me->accept();
  732. }
  733. }
  734. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  735. {
  736. QOpenGLWidget::mouseMoveEvent(me);
  737. if (rubberbanding) {
  738. QRectF& rect = rubberband;
  739. double aspect = double(geometry().width()) / geometry().height();
  740. rect.setBottomRight(QPoint(me->x(), me->y()));
  741. if (rect.width() > rect.height() * aspect)
  742. rect.setHeight(rect.width() / aspect);
  743. else
  744. rect.setWidth(rect.height() * aspect);
  745. emit repaint();
  746. }
  747. else if (selectingPoint) {
  748. pointX = me->x();
  749. pointY = me->y();
  750. emit repaint();
  751. }
  752. else if (dragging) {
  753. double deltaX = me->x() - dragX;
  754. double deltaY = me->y() - dragY;
  755. this->currentViewport.x -= deltaX * currentViewport.width / this->width();
  756. this->currentViewport.y -= deltaY * currentViewport.height / this->height();
  757. targetViewport = currentViewport;
  758. dragX = me->x(); dragY = me->y();
  759. emit repaint();
  760. }
  761. me->accept();
  762. }
  763. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  764. {
  765. QOpenGLWidget::mouseReleaseEvent(me);
  766. if (rubberbanding) {
  767. QRect rect = rubberband.toRect();
  768. if(rect.width() != 0 && rect.height() != 0) {
  769. QRect full = this->geometry();
  770. targetViewport.x += mnd::Real(rect.left()) * targetViewport.width / full.width();
  771. targetViewport.y += mnd::Real(rect.top()) * targetViewport.height / full.height();
  772. targetViewport.width *= mnd::Real(rect.width()) / full.width();
  773. targetViewport.height *= mnd::Real(rect.height()) / full.height();
  774. targetViewport.normalize();
  775. currentViewport = targetViewport;
  776. }
  777. requestRecalc();
  778. rubberbanding = false;
  779. }
  780. else if (selectingPoint) {
  781. selectingPoint = false;
  782. this->setMouseTracking(false);
  783. mnd::Real x = currentViewport.x + currentViewport.width * mnd::convert<mnd::Real>(float(me->x()) / width());
  784. mnd::Real y = currentViewport.y + currentViewport.height * mnd::convert<mnd::Real>(float(me->y()) / height());
  785. emit pointSelected(x, y);
  786. emit repaint();
  787. }
  788. dragging = false;
  789. //requestRecalc();
  790. }
  791. void MandelWidget::wheelEvent(QWheelEvent* we)
  792. {
  793. QOpenGLWidget::wheelEvent(we);
  794. float x = float(we->x()) / this->width();
  795. float y = float(we->y()) / this->height();
  796. float scale = ::powf(0.9975f, we->angleDelta().y());
  797. zoom(scale, x, y);
  798. if (!we->pixelDelta().isNull())
  799. this->currentViewport = this->targetViewport;
  800. we->accept();
  801. }
  802. /*void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  803. {
  804. if (bitmap != nullptr) {
  805. delete bitmap;
  806. emit repaint();
  807. }
  808. }*/