1
0

MandelWidget.cpp 31 KB

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