MandelWidget.cpp 26 KB

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