MandelWidget.cpp 26 KB

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