MandelWidget.cpp 31 KB

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