MandelWidget.cpp 26 KB

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