25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

562 satır
18 KiB

  1. //
  2. // Lol Engine — Fractal tutorial
  3. //
  4. // Copyright © 2011—2015 Sam Hocevar <sam@hocevar.net>
  5. //
  6. // Lol Engine is free software. It comes without any warranty, to
  7. // the extent permitted by applicable law. You can redistribute it
  8. // and/or modify it under the terms of the Do What the Fuck You Want
  9. // to Public License, Version 2, as published by the WTFPL Task Force.
  10. // See http://www.wtfpl.net/ for more details.
  11. //
  12. #if HAVE_CONFIG_H
  13. # include "config.h"
  14. #endif
  15. #include <cstring>
  16. #include <cstdio>
  17. #include <lol/engine.h>
  18. #include "loldebug.h"
  19. using namespace lol;
  20. LOLFX_RESOURCE_DECLARE(11_fractal);
  21. class Fractal : public WorldEntity
  22. {
  23. public:
  24. Fractal(ivec2 const &size)
  25. {
  26. /* Ensure texture size is a multiple of 16 for better aligned
  27. * data access. Store the dimensions of a texel for our shader,
  28. * as well as the half-size of the screen. */
  29. m_size = size;
  30. m_size.x = (m_size.x + 15) & ~15;
  31. m_size.y = (m_size.y + 15) & ~15;
  32. m_texel_settings = vec4(1.0, 1.0, 2.0, 2.0) / (vec4)m_size.xyxy;
  33. m_screen_settings = vec4(1.0, 1.0, 0.5, 0.5) * (vec4)m_size.xyxy;
  34. /* Window size decides the world aspect ratio. For instance, 640×480
  35. * will be mapped to (-0.66,-0.5) - (0.66,0.5). */
  36. #if !defined __native_client__
  37. m_window_size = Video::GetSize();
  38. #else
  39. /* FIXME: it's illegal to call this on the game thread! */
  40. m_window_size = ivec2(640, 480);
  41. #endif
  42. if (m_window_size.y < m_window_size.x)
  43. m_window2world = 0.5 / m_window_size.y;
  44. else
  45. m_window2world = 0.5 / m_window_size.x;
  46. m_texel2world = (dvec2)m_window_size / (dvec2)m_size * m_window2world;
  47. m_oldmouse = ivec2(0, 0);
  48. m_pixels.resize(m_size.x * m_size.y);
  49. m_frame = -1;
  50. m_slices = 4;
  51. for (int i = 0; i < 4; i++)
  52. {
  53. m_deltashift[i] = real("0");
  54. m_deltascale[i] = real("1");
  55. m_dirty[i] = 2;
  56. }
  57. m_center = rcmplx(-0.75, 0.0);
  58. m_zoom_speed = 0.0;
  59. m_translate = rcmplx(0.0, 0.0);
  60. m_radius = 5.0;
  61. m_ready = false;
  62. m_drag = false;
  63. for (int i = 0; i < (MAX_ITERATIONS + 1) * PALETTE_STEP; i++)
  64. {
  65. double f = (double)i / PALETTE_STEP;
  66. double r = 0.5 * lol::sin(f * 0.27 + 2.0) + 0.5;
  67. double g = 0.5 * lol::sin(f * 0.17 - 1.8) + 0.5;
  68. double b = 0.5 * lol::sin(f * 0.21 - 2.6) + 0.5;
  69. if (f < 7.0)
  70. {
  71. f = f < 1.0 ? 0.0 : (f - 1.0) / 6.0;
  72. r *= f;
  73. g *= f;
  74. b *= f;
  75. }
  76. uint8_t red = (uint8_t)r * 256;
  77. uint8_t green = (uint8_t)g * 256;
  78. uint8_t blue = (uint8_t)b * 256;
  79. #if defined __native_client__
  80. m_palette.push(u8vec4(red, green, blue, 255));
  81. #else
  82. m_palette.push(u8vec4(blue, green, red, 255));
  83. #endif
  84. }
  85. #if !defined __native_client__
  86. m_centertext = new Text(nullptr, "data/font/ascii.png");
  87. m_centertext->SetPos(vec3(5, (float)m_window_size.y - 15, 1));
  88. Ticker::Ref(m_centertext);
  89. m_mousetext = new Text(nullptr, "data/font/ascii.png");
  90. m_mousetext->SetPos(vec3(5, (float)m_window_size.y - 29, 1));
  91. Ticker::Ref(m_mousetext);
  92. m_zoomtext = new Text(nullptr, "data/font/ascii.png");
  93. m_zoomtext->SetPos(vec3(5, (float)m_window_size.y - 43, 1));
  94. Ticker::Ref(m_zoomtext);
  95. #endif
  96. m_position = vec3::zero;
  97. m_aabb.aa = m_position;
  98. m_aabb.bb = vec3((vec2)m_window_size, 0);
  99. //Input::TrackMouse(this);
  100. #if LOL_FEATURE_THREADS
  101. /* Spawn worker threads and wait for their readiness. */
  102. for (int i = 0; i < MAX_THREADS; i++)
  103. m_threads[i] = new thread(std::bind(&Fractal::DoWorkHelper, this, std::placeholders::_1));
  104. for (int i = 0; i < MAX_THREADS; i++)
  105. m_spawnqueue.pop();
  106. #endif
  107. }
  108. ~Fractal()
  109. {
  110. #if LOL_FEATURE_THREADS
  111. /* Signal worker threads for completion and wait for
  112. * them to quit. */
  113. for (int i = 0; i < MAX_THREADS; i++)
  114. m_jobqueue.push(-1);
  115. for (int i = 0; i < MAX_THREADS; i++)
  116. m_donequeue.pop();
  117. #endif
  118. //Input::UntrackMouse(this);
  119. #if !defined __native_client__
  120. Ticker::Unref(m_centertext);
  121. Ticker::Unref(m_mousetext);
  122. Ticker::Unref(m_zoomtext);
  123. #endif
  124. }
  125. inline dcmplx TexelToWorldOffset(vec2 texel)
  126. {
  127. double dx = (0.5 + texel.x - m_size.x / 2) * m_texel2world.x;
  128. double dy = (0.5 + m_size.y / 2 - texel.y) * m_texel2world.y;
  129. return m_radius * dcmplx(dx, dy);
  130. }
  131. inline dcmplx ScreenToWorldOffset(vec2 pixel)
  132. {
  133. /* No 0.5 offset here, because we want to be able to position the
  134. * mouse at (0,0) exactly. */
  135. double dx = pixel.x - m_window_size.x / 2;
  136. double dy = m_window_size.y / 2 - pixel.y;
  137. return m_radius * m_window2world * dcmplx(dx, dy);
  138. }
  139. virtual void TickGame(float seconds)
  140. {
  141. WorldEntity::TickGame(seconds);
  142. ivec2 mousepos = ivec2::zero; /* FIXME: input */
  143. int prev_frame = (m_frame + 4) % 4;
  144. m_frame = (m_frame + 1) % 4;
  145. rcmplx worldmouse = m_center
  146. + rcmplx(ScreenToWorldOffset((vec2)mousepos));
  147. uint32_t buttons = 0;
  148. //uint32_t buttons = Input::GetMouseButtons();
  149. if (buttons & 0x2)
  150. {
  151. if (!m_drag)
  152. {
  153. m_oldmouse = mousepos;
  154. m_drag = true;
  155. }
  156. m_translate = rcmplx(ScreenToWorldOffset((vec2)m_oldmouse)
  157. - ScreenToWorldOffset((vec2)mousepos));
  158. /* XXX: the purpose of this hack is to avoid translating by
  159. * an exact number of pixels. If this were to happen, the step()
  160. * optimisation for i915 cards in our shader would behave
  161. * incorrectly because a quarter of the pixels in the image
  162. * would have tied rankings in the distance calculation. */
  163. m_translate *= real(1023.0 / 1024.0);
  164. m_oldmouse = mousepos;
  165. }
  166. else
  167. {
  168. m_drag = false;
  169. if (m_translate != rcmplx(0.0, 0.0))
  170. {
  171. m_translate *= real(std::pow(2.0, -seconds * 5.0));
  172. if ((double)norm(m_translate) < m_radius * 1e-4)
  173. m_translate = rcmplx(0.0, 0.0);
  174. }
  175. }
  176. if (buttons & 0x5 && mousepos.x != -1)
  177. {
  178. double zoom = (buttons & 0x1) ? -0.5 : 0.5;
  179. m_zoom_speed += zoom * seconds;
  180. if (m_zoom_speed / zoom > 5e-3f)
  181. m_zoom_speed = zoom * 5e-3f;
  182. }
  183. else if (m_zoom_speed)
  184. {
  185. m_zoom_speed *= std::pow(2.0, -seconds * 5.0);
  186. if (lol::abs(m_zoom_speed) < 1e-5 || m_drag)
  187. m_zoom_speed = 0.0;
  188. }
  189. if (m_zoom_speed || m_translate != rcmplx(0.0, 0.0))
  190. {
  191. rcmplx oldcenter = m_center;
  192. double oldradius = m_radius;
  193. double zoom = std::pow(2.0, seconds * 1e3f * m_zoom_speed);
  194. if (m_radius * zoom > 8.0)
  195. {
  196. m_zoom_speed *= -1.0;
  197. zoom = 8.0 / m_radius;
  198. }
  199. else if (m_radius * zoom < 1e-14)
  200. {
  201. m_zoom_speed *= -1.0;
  202. zoom = 1e-14 / m_radius;
  203. }
  204. m_radius *= zoom;
  205. m_center += m_translate;
  206. m_center = (m_center - worldmouse) * real(zoom) + worldmouse;
  207. worldmouse = m_center
  208. + rcmplx(ScreenToWorldOffset((vec2)mousepos));
  209. /* Store the transformation properties to go from m_frame - 1
  210. * to m_frame. */
  211. m_deltashift[prev_frame] = (m_center - oldcenter) / real(oldradius);
  212. m_deltashift[prev_frame].x /= m_size.x * m_texel2world.x;
  213. m_deltashift[prev_frame].y /= m_size.y * m_texel2world.y;
  214. m_deltascale[prev_frame] = m_radius / oldradius;
  215. m_dirty[0] = m_dirty[1] = m_dirty[2] = m_dirty[3] = 2;
  216. }
  217. else
  218. {
  219. /* If settings didn't change, set transformation from previous
  220. * frame to identity. */
  221. m_deltashift[prev_frame] = real::R_0();
  222. m_deltascale[prev_frame] = real::R_1();
  223. }
  224. /* Transformation from current frame to current frame is always
  225. * identity. */
  226. m_zoom_settings[m_frame][0] = 0.0f;
  227. m_zoom_settings[m_frame][1] = 0.0f;
  228. m_zoom_settings[m_frame][2] = 1.0f;
  229. /* Compute transformation from other frames to current frame */
  230. for (int i = 0; i < 3; i++)
  231. {
  232. int prev_index = (m_frame + 4 - i) % 4;
  233. int cur_index = (m_frame + 3 - i) % 4;
  234. m_zoom_settings[cur_index][0] = (real)m_zoom_settings[prev_index][0] * m_deltascale[cur_index] + m_deltashift[cur_index].x;
  235. m_zoom_settings[cur_index][1] = (real)m_zoom_settings[prev_index][1] * m_deltascale[cur_index] + m_deltashift[cur_index].y;
  236. m_zoom_settings[cur_index][2] = (real)m_zoom_settings[prev_index][2] * m_deltascale[cur_index];
  237. }
  238. /* Precompute texture offset change instead of doing it in GLSL */
  239. for (int i = 0; i < 4; i++)
  240. {
  241. m_zoom_settings[i][0] += 0.5f * (1.0f - m_zoom_settings[i][2]);
  242. m_zoom_settings[i][1] -= 0.5f * (1.0f - m_zoom_settings[i][2]);
  243. }
  244. #if !defined __native_client__
  245. char buf[256];
  246. std::sprintf(buf, "center: ");
  247. m_center.x.sprintf(buf + strlen(buf), 30);
  248. std::sprintf(buf + strlen(buf), " ");
  249. m_center.y.sprintf(buf + strlen(buf), 30);
  250. m_centertext->SetText(buf);
  251. std::sprintf(buf, " mouse: ");
  252. worldmouse.x.sprintf(buf + strlen(buf), 30);
  253. std::sprintf(buf + strlen(buf), " ");
  254. worldmouse.y.sprintf(buf + strlen(buf), 30);
  255. m_mousetext->SetText(buf);
  256. std::sprintf(buf, " zoom: %g", 1.0 / m_radius);
  257. m_zoomtext->SetText(buf);
  258. #endif
  259. if (m_dirty[m_frame])
  260. {
  261. m_dirty[m_frame]--;
  262. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  263. {
  264. #if LOL_FEATURE_THREADS
  265. m_jobqueue.push(i);
  266. #else
  267. DoWork(i);
  268. #endif
  269. }
  270. }
  271. }
  272. #if LOL_FEATURE_THREADS
  273. void DoWorkHelper(thread *inst)
  274. {
  275. m_spawnqueue.push(0);
  276. for ( ; ; )
  277. {
  278. int line = m_jobqueue.pop();
  279. if (line == -1)
  280. break;
  281. DoWork(line);
  282. m_donequeue.push(0);
  283. }
  284. m_donequeue.push(0);
  285. };
  286. #endif
  287. void DoWork(int line)
  288. {
  289. double const maxsqlen = 1024;
  290. double const k1 = 1.0 / (1 << 10) / (std::log(maxsqlen) / std::log(2.0));
  291. int jmin = ((m_frame + 1) % 4) / 2 + line;
  292. int jmax = jmin + MAX_LINES * 2;
  293. if (jmax > m_size.y)
  294. jmax = m_size.y;
  295. u8vec4 *m_pixelstart = &m_pixels[0]
  296. + m_size.x * (m_size.y / 4 * m_frame + line / 4);
  297. dcmplx c = (dcmplx)m_center;
  298. for (int j = jmin; j < jmax; j += 2)
  299. for (int i = m_frame % 2; i < m_size.x; i += 2)
  300. {
  301. double xr, yr, x0, y0, x1, y1, x2, y2, x3, y3;
  302. dcmplx z0 = c + TexelToWorldOffset(vec2(ivec2(i, j)));
  303. //dcmplx r0(0.28693186889504513, 0.014286693904085048);
  304. //dcmplx r0(0.001643721971153, 0.822467633298876);
  305. //dcmplx r0(-1.207205434596, 0.315432814901);
  306. //dcmplx r0(-0.79192956889854, -0.14632423080102);
  307. //dcmplx r0(0.3245046418497685, 0.04855101129280834);
  308. dcmplx r0 = z0;
  309. x0 = z0.x; y0 = z0.y;
  310. xr = r0.x; yr = r0.y;
  311. int iter = MAX_ITERATIONS - 4;
  312. for (;;)
  313. {
  314. /* Unroll the loop: tests are more expensive to do at each
  315. * iteration than the few extra multiplications. */
  316. x1 = x0 * x0 - y0 * y0 + xr;
  317. y1 = x0 * y0 + x0 * y0 + yr;
  318. x2 = x1 * x1 - y1 * y1 + xr;
  319. y2 = x1 * y1 + x1 * y1 + yr;
  320. x3 = x2 * x2 - y2 * y2 + xr;
  321. y3 = x2 * y2 + x2 * y2 + yr;
  322. x0 = x3 * x3 - y3 * y3 + xr;
  323. y0 = x3 * y3 + x3 * y3 + yr;
  324. if (x0 * x0 + y0 * y0 >= maxsqlen)
  325. break;
  326. iter -= 4;
  327. if (iter < 4)
  328. break;
  329. }
  330. if (iter)
  331. {
  332. double n = x0 * x0 + y0 * y0;
  333. if (x1 * x1 + y1 * y1 >= maxsqlen)
  334. {
  335. iter += 3; n = x1 * x1 + y1 * y1;
  336. }
  337. else if (x2 * x2 + y2 * y2 >= maxsqlen)
  338. {
  339. iter += 2; n = x2 * x2 + y2 * y2;
  340. }
  341. else if (x3 * x3 + y3 * y3 >= maxsqlen)
  342. {
  343. iter += 1; n = x3 * x3 + y3 * y3;
  344. }
  345. if (n > maxsqlen * maxsqlen)
  346. n = maxsqlen * maxsqlen;
  347. /* Approximate log(sqrt(n))/log(sqrt(maxsqlen)) */
  348. double f = iter;
  349. union { double n; uint64_t x; } u = { n };
  350. double k = (double)(u.x >> 42) - (((1 << 10) - 1) << 10);
  351. k *= k1;
  352. /* Approximate log2(k) in [1,2]. */
  353. f += (- 0.344847817623168308695977510213252644185 * k
  354. + 2.024664188044341212602376988171727038739) * k
  355. - 1.674876738008591047163498125918330313237;
  356. *m_pixelstart++ = m_palette[(int)(f * PALETTE_STEP)];
  357. }
  358. else
  359. {
  360. *m_pixelstart++ = u8vec4(0, 0, 0, 255);
  361. }
  362. }
  363. }
  364. virtual void TickDraw(float seconds, Scene &scene)
  365. {
  366. WorldEntity::TickDraw(seconds, scene);
  367. static float const vertices[] =
  368. {
  369. 1.0f, 1.0f,
  370. -1.0f, 1.0f,
  371. -1.0f, -1.0f,
  372. -1.0f, -1.0f,
  373. 1.0f, -1.0f,
  374. 1.0f, 1.0f,
  375. };
  376. static float const texcoords[] =
  377. {
  378. 1.0f, 1.0f,
  379. 0.0f, 1.0f,
  380. 0.0f, 0.0f,
  381. 0.0f, 0.0f,
  382. 1.0f, 0.0f,
  383. 1.0f, 1.0f,
  384. };
  385. if (!m_ready)
  386. {
  387. /* Create a texture of half the width and twice the height
  388. * so that we can upload four different subimages each frame. */
  389. m_texture = new Texture(ivec2(m_size.x / 2, m_size.y * 2),
  390. PixelFormat::RGBA_8);
  391. /* Ensure the texture data is complete at least once, otherwise
  392. * uploading subimages will not work. */
  393. m_texture->SetData(&m_pixels[0]);
  394. m_shader = Shader::Create(LOLFX_RESOURCE_NAME(11_fractal));
  395. m_vertexattrib = m_shader->GetAttribLocation(VertexUsage::Position, 0);
  396. m_texattrib = m_shader->GetAttribLocation(VertexUsage::TexCoord, 0);
  397. m_texeluni = m_shader->GetUniformLocation("u_TexelSize");
  398. m_screenuni = m_shader->GetUniformLocation("u_ScreenSize");
  399. m_zoomuni = m_shader->GetUniformLocation("u_ZoomSettings");
  400. m_vdecl =
  401. new VertexDeclaration(VertexStream<vec2>(VertexUsage::Position),
  402. VertexStream<vec2>(VertexUsage::TexCoord));
  403. m_vbo = new VertexBuffer(sizeof(vertices));
  404. m_tbo = new VertexBuffer(sizeof(texcoords));
  405. void *tmp = m_vbo->Lock(0, 0);
  406. memcpy(tmp, vertices, sizeof(vertices));
  407. m_vbo->Unlock();
  408. tmp = m_tbo->Lock(0, 0);
  409. memcpy(tmp, texcoords, sizeof(texcoords));
  410. m_tbo->Unlock();
  411. /* FIXME: this object never cleans up */
  412. m_ready = true;
  413. }
  414. m_texture->Bind();
  415. if (m_dirty[m_frame])
  416. {
  417. #if LOL_FEATURE_THREADS
  418. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  419. m_donequeue.pop();
  420. #endif
  421. m_dirty[m_frame]--;
  422. m_texture->SetSubData(ivec2(0, m_frame * m_size.y / 2),
  423. m_size / 2,
  424. &m_pixels[m_size.x * m_size.y / 4 * m_frame]);
  425. }
  426. m_shader->Bind();
  427. m_shader->SetUniform(m_texeluni, m_texel_settings);
  428. m_shader->SetUniform(m_screenuni, m_screen_settings);
  429. m_shader->SetUniform(m_zoomuni, m_zoom_settings);
  430. m_vdecl->Bind();
  431. m_vdecl->SetStream(m_vbo, m_vertexattrib);
  432. m_vdecl->SetStream(m_tbo, m_texattrib);
  433. m_texture->Bind();
  434. m_vdecl->DrawElements(MeshPrimitive::Triangles, 0, 6);
  435. m_vdecl->Unbind();
  436. }
  437. private:
  438. static int const MAX_ITERATIONS = 340;
  439. static int const PALETTE_STEP = 32;
  440. static int const MAX_THREADS = 8;
  441. static int const MAX_LINES = 8;
  442. ivec2 m_size, m_window_size, m_oldmouse;
  443. double m_window2world;
  444. dvec2 m_texel2world;
  445. array<u8vec4> m_pixels, m_palette;
  446. Shader *m_shader;
  447. ShaderAttrib m_vertexattrib, m_texattrib;
  448. ShaderUniform m_texeluni, m_screenuni, m_zoomuni;
  449. VertexDeclaration *m_vdecl;
  450. VertexBuffer *m_vbo, *m_tbo;
  451. Texture *m_texture;
  452. int m_frame, m_slices, m_dirty[4];
  453. bool m_ready, m_drag;
  454. rcmplx m_deltashift[4], m_center, m_translate;
  455. real m_deltascale[4];
  456. double m_zoom_speed, m_radius;
  457. vec4 m_texel_settings, m_screen_settings;
  458. mat4 m_zoom_settings;
  459. #if LOL_FEATURE_THREADS
  460. /* Worker threads */
  461. thread *m_threads[MAX_THREADS];
  462. queue<int> m_spawnqueue, m_jobqueue, m_donequeue;
  463. #endif
  464. #if !defined __native_client__
  465. /* Debug information */
  466. Text *m_centertext, *m_mousetext, *m_zoomtext;
  467. #endif
  468. };
  469. int main(int argc, char **argv)
  470. {
  471. ivec2 window_size(640, 480);
  472. System::Init(argc, argv);
  473. Application app("Tutorial 3: Fractal", window_size, 60.0f);
  474. new DebugFps(5, 5);
  475. new Fractal(window_size);
  476. //new DebugRecord("fractalol.ogm", 60.0f);
  477. app.Run();
  478. return EXIT_SUCCESS;
  479. }