MandelWidget.cpp 31 KB

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