Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

11_fractal.cpp 19 KiB

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