MandelWidget.cpp 26 KB

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