MandelWidget.cpp 28 KB

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