479 lines
17 KiB

  1. //
  2. // Lol Engine - Fractal tutorial
  3. //
  4. // Copyright: (c) 2011 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://sam.zoy.org/projects/COPYING.WTFPL for more details.
  9. //
  10. #if defined HAVE_CONFIG_H
  11. # include "config.h"
  12. #endif
  13. #include <cstring>
  14. #include "core.h"
  15. #include "lolgl.h"
  16. #include "loldebug.h"
  17. using namespace std;
  18. using namespace lol;
  19. #if USE_SDL && defined __APPLE__
  20. # include <SDL_main.h>
  21. #endif
  22. #if defined _WIN32
  23. # undef main /* FIXME: still needed? */
  24. # include <direct.h>
  25. #endif
  26. class Fractal : public WorldEntity
  27. {
  28. public:
  29. Fractal(ivec2 const &size)
  30. {
  31. /* Ensure size has even X and Y values */
  32. m_size = size;
  33. m_size.x = (m_size.x + 1) & ~1;
  34. m_size.y = (m_size.y + 1) & ~1;
  35. m_window_size = Video::GetSize();
  36. m_pixels = new u8vec4[m_size.x * m_size.y];
  37. m_tmppixels = new u8vec4[m_size.x / 2 * m_size.y / 2];
  38. m_frame = -1;
  39. for (int i = 0; i < 4; i++)
  40. {
  41. m_deltashift[i] = 0.0;
  42. m_deltascale[i] = 1.0;
  43. m_dirty[i] = 2;
  44. }
  45. m_center = -0.75;
  46. m_radius = 1.5;
  47. m_texture_radius = 0.5 * (m_size.x < m_size.y ? m_size.x : m_size.y);
  48. m_window_radius = 0.5 * (m_window_size.x < m_window_size.y ? m_window_size.x : m_window_size.y);
  49. m_pixel_delta = vec4(vec2(1.0, 1.0) / (vec2)m_size, m_size);
  50. m_ready = false;
  51. m_palette = new u8vec4[(MAX_ITERATIONS + 1) * PALETTE_STEP];
  52. for (int i = 0; i < (MAX_ITERATIONS + 1) * PALETTE_STEP; i++)
  53. {
  54. float f = i / (double)PALETTE_STEP;
  55. double r = 0.5 * sin(f * 0.27 - 2.5) + 0.5;
  56. double g = 0.5 * sin(f * 0.13 + 1.1) + 0.5;
  57. double b = 0.5 * sin(f * 0.21 + 0.4) + 0.5;
  58. uint8_t red = r * 255.0f;
  59. uint8_t green = g * 255.0f;
  60. uint8_t blue = b * 255.0f;
  61. m_palette[i] = u8vec4(blue, green, red, 0);
  62. }
  63. m_centertext = new Text(NULL, "gfx/font/ascii.png");
  64. m_centertext->SetPos(ivec3(5, m_window_size.y - 15, 1));
  65. Ticker::Ref(m_centertext);
  66. m_mousetext = new Text(NULL, "gfx/font/ascii.png");
  67. m_mousetext->SetPos(ivec3(5, m_window_size.y - 29, 1));
  68. Ticker::Ref(m_mousetext);
  69. m_zoomtext = new Text(NULL, "gfx/font/ascii.png");
  70. m_zoomtext->SetPos(ivec3(5, m_window_size.y - 43, 1));
  71. Ticker::Ref(m_zoomtext);
  72. position = ivec3(0, 0, 0);
  73. bbox[0] = position;
  74. bbox[1] = ivec3(m_window_size, 0);
  75. Input::TrackMouse(this);
  76. }
  77. ~Fractal()
  78. {
  79. Input::UntrackMouse(this);
  80. Ticker::Unref(m_centertext);
  81. Ticker::Unref(m_mousetext);
  82. Ticker::Unref(m_zoomtext);
  83. delete m_pixels;
  84. delete m_tmppixels;
  85. delete m_palette;
  86. }
  87. inline f64cmplx TexelToWorldOffset(ivec2 texel)
  88. {
  89. f64cmplx tmp = f64cmplx(0.5 + texel.x - m_size.x / 2,
  90. 0.5 + m_size.y / 2 - texel.y);
  91. return tmp * (m_radius / m_texture_radius);
  92. }
  93. inline f64cmplx ScreenToWorldOffset(ivec2 pixel)
  94. {
  95. /* No 0.5 offset here, because we want to be able to position the
  96. * mouse at (0,0) exactly. */
  97. f64cmplx tmp = f64cmplx(pixel.x - m_window_size.x / 2,
  98. m_window_size.y / 2 - pixel.y);
  99. return tmp * (m_radius / m_window_radius);
  100. }
  101. virtual void TickGame(float deltams)
  102. {
  103. WorldEntity::TickGame(deltams);
  104. m_frame = (m_frame + 1) % 4;
  105. f64cmplx worldmouse = m_center + ScreenToWorldOffset(mousepos);
  106. ivec3 buttons = Input::GetMouseButtons();
  107. #ifdef __CELLOS_LV2__
  108. if (true)
  109. #else
  110. if ((buttons[0] || buttons[2]) && mousepos.x != -1)
  111. #endif
  112. {
  113. f64cmplx oldcenter = m_center;
  114. double oldradius = m_radius;
  115. #ifdef __CELLOS_LV2__
  116. m_radius *= pow(2.0, -deltams * 0.00015);
  117. m_center = f64cmplx(0.001643721971153, 0.822467633298876);
  118. #else
  119. double zoom = pow(2.0, (buttons[0] ? -deltams : deltams) * 0.0025);
  120. if (m_radius * zoom > 8.0)
  121. zoom = 8.0 / m_radius;
  122. else if (m_radius * zoom < 1e-14)
  123. zoom = 1e-14 / m_radius;
  124. m_radius *= zoom;
  125. m_center = (m_center - worldmouse) * zoom + worldmouse;
  126. worldmouse = m_center + ScreenToWorldOffset(mousepos);
  127. #endif
  128. /* Store the transformation properties to go from m_frame-1
  129. * to m_frame. */
  130. m_deltashift[m_frame] = (oldcenter - m_center) / m_radius;
  131. m_deltascale[m_frame] = oldradius / m_radius;
  132. m_dirty[0] = m_dirty[1] = m_dirty[2] = m_dirty[3] = 2;
  133. }
  134. else
  135. {
  136. /* If settings didn't change, set transformation from previous
  137. * frame to identity. */
  138. m_deltashift[m_frame] = 0.0;
  139. m_deltascale[m_frame] = 1.0;
  140. }
  141. if (buttons[1])
  142. m_dirty[0] = m_dirty[1] = m_dirty[2] = m_dirty[3] = 2;
  143. char buf[128];
  144. sprintf(buf, "center: %+16.14f%+16.14fi", m_center.x, m_center.y);
  145. m_centertext->SetText(buf);
  146. sprintf(buf, " mouse: %+16.14f%+16.14fi", worldmouse.x, worldmouse.y);
  147. m_mousetext->SetText(buf);
  148. sprintf(buf, " zoom: %g", 1.0 / m_radius);
  149. m_zoomtext->SetText(buf);
  150. u8vec4 *m_pixelstart = m_pixels + m_size.x * m_size.y / 4 * m_frame;
  151. if (m_dirty[m_frame])
  152. {
  153. m_dirty[m_frame]--;
  154. for (int j = ((m_frame + 1) % 4) / 2; j < m_size.y; j += 2)
  155. for (int i = m_frame % 2; i < m_size.x; i += 2)
  156. {
  157. double const maxsqlen = 1024;
  158. f64cmplx z0 = m_center + TexelToWorldOffset(ivec2(i, j));
  159. f64cmplx r0 = z0;
  160. //f64cmplx r0(0.28693186889504513, 0.014286693904085048);
  161. //f64cmplx r0(0.001643721971153, 0.822467633298876);
  162. //f64cmplx r0(-1.207205434596, 0.315432814901);
  163. //f64cmplx r0(-0.79192956889854, -0.14632423080102);
  164. //f64cmplx r0(0.3245046418497685, 0.04855101129280834);
  165. f64cmplx z;
  166. int iter = MAX_ITERATIONS;
  167. for (z = z0; iter && z.sqlen() < maxsqlen; z = z * z + r0)
  168. --iter;
  169. if (iter)
  170. {
  171. double f = iter;
  172. double n = z.sqlen();
  173. if (n > maxsqlen * maxsqlen)
  174. n = maxsqlen * maxsqlen;
  175. /* Approximate log(sqrt(n))/log(sqrt(maxsqlen)) */
  176. union { double n; uint64_t x; } u = { n };
  177. double k = (u.x >> 42) - (((1 << 10) - 1) << 10);
  178. k *= 1.0 / (1 << 10) / log2(maxsqlen);
  179. /* Approximate log2(k) in [1,2]. */
  180. f += (- 0.344847817623168308695977510213252644185 * k
  181. + 2.024664188044341212602376988171727038739) * k
  182. - 1.674876738008591047163498125918330313237;
  183. *m_pixelstart++ = m_palette[(int)(f * PALETTE_STEP)];
  184. }
  185. else
  186. {
  187. *m_pixelstart++ = u8vec4(0, 0, 0, 0);
  188. }
  189. }
  190. }
  191. }
  192. virtual void TickDraw(float deltams)
  193. {
  194. WorldEntity::TickDraw(deltams);
  195. static float const vertices[] =
  196. {
  197. 1.0f, 1.0f,
  198. -1.0f, 1.0f,
  199. -1.0f, -1.0f,
  200. -1.0f, -1.0f,
  201. 1.0f, -1.0f,
  202. 1.0f, 1.0f,
  203. };
  204. static float const texcoords[] =
  205. {
  206. 1.0f, 1.0f,
  207. 0.0f, 1.0f,
  208. 0.0f, 0.0f,
  209. 0.0f, 0.0f,
  210. 1.0f, 0.0f,
  211. 1.0f, 1.0f,
  212. };
  213. if (!m_ready)
  214. {
  215. /* Create a texture of half the width and twice the height
  216. * so that we can upload four different subimages each frame. */
  217. glGenTextures(1, &m_texid);
  218. glBindTexture(GL_TEXTURE_2D, m_texid);
  219. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_size.x / 2, m_size.y * 2,
  220. 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_pixels);
  221. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  222. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  223. m_shader = Shader::Create(
  224. #if !defined __CELLOS_LV2__
  225. "#version 120\n"
  226. "attribute vec2 in_TexCoord;\n"
  227. "attribute vec2 in_Vertex;"
  228. "void main(void) {"
  229. " gl_Position = vec4(in_Vertex, 0.0, 1.0);"
  230. " gl_TexCoord[0] = vec4(in_TexCoord, 0.0, 0.0);\n"
  231. "}",
  232. "#version 120\n"
  233. ""
  234. "uniform vec4 in_PixelDelta;"
  235. "uniform sampler2D in_Texture;"
  236. ""
  237. /* Get the coordinate of the nearest point in slice 0 in xy,
  238. * and the squared distance to that point in z.
  239. * p is in normalised [0,1] texture coordinates.
  240. * return value has the 0.25 Y scaling. */
  241. "vec3 nearest0(vec2 p) {"
  242. " vec2 q = p + 0.5 * in_PixelDelta.xy;"
  243. " q -= mod(q, 2.0 * in_PixelDelta.xy);"
  244. " q += 0.5 * in_PixelDelta.xy;"
  245. " return vec3(q * vec2(1.0, 0.25),"
  246. " length(q - p));"
  247. "}"
  248. ""
  249. "vec3 nearest1(vec2 p) {"
  250. " vec2 q = p - 0.5 * in_PixelDelta.xy;"
  251. " q -= mod(q, 2.0 * in_PixelDelta.xy);"
  252. " q += 1.5 * in_PixelDelta.xy;"
  253. " return vec3(q * vec2(1.0, 0.25) + vec2(0.0, 0.25),"
  254. " length(q - p));"
  255. "}"
  256. ""
  257. "vec3 nearest2(vec2 p) {"
  258. " vec2 q = p + vec2(0.5, -0.5) * in_PixelDelta.xy;"
  259. " q -= mod(q, 2.0 * in_PixelDelta.xy);"
  260. " q += vec2(0.5, 1.5) * in_PixelDelta.xy;"
  261. " return vec3(q * vec2(1.0, 0.25) + vec2(0.0, 0.50),"
  262. " length(q - p));"
  263. "}"
  264. ""
  265. "vec3 nearest3(vec2 p) {"
  266. " vec2 q = p + vec2(-0.5, 0.5) * in_PixelDelta.xy;"
  267. " q -= mod(q, 2.0 * in_PixelDelta.xy);"
  268. " q += vec2(1.5, 0.5) * in_PixelDelta.xy;"
  269. " return vec3(q * vec2(1.0, 0.25) + vec2(0.0, 0.75),"
  270. " length(q - p));"
  271. "}"
  272. ""
  273. "void main(void) {"
  274. " vec2 coord = gl_TexCoord[0].xy;"
  275. /* Slightly shift our pixel so that it does not lie at
  276. * an exact texel boundary. This would lead to visual
  277. * artifacts. */
  278. "coord -= 0.1 * in_PixelDelta.x;"
  279. /* Get a pixel from each slice */
  280. " vec4 p0 = texture2D(in_Texture, nearest0(coord).xy);"
  281. " vec4 p1 = texture2D(in_Texture, nearest1(coord).xy);"
  282. " vec4 p2 = texture2D(in_Texture, nearest2(coord).xy);"
  283. " vec4 p3 = texture2D(in_Texture, nearest3(coord).xy);"
  284. " gl_FragColor = 0.25 * (p0 + p1 + p2 + p3);"
  285. "}"
  286. #else
  287. "void main(float4 in_Position : POSITION,"
  288. " float2 in_TexCoord : TEXCOORD0,"
  289. " out float4 out_Position : POSITION,"
  290. " out float2 out_TexCoord : TEXCOORD0)"
  291. "{"
  292. " out_TexCoord = in_TexCoord;"
  293. " out_Position = in_Position;"
  294. "}",
  295. "void main(float4 in_FragCoord : WPOS,"
  296. " float2 in_TexCoord : TEXCOORD0,"
  297. " uniform float4 in_PixelDelta,"
  298. " uniform sampler2D in_Texture,"
  299. " out float4 out_FragColor : COLOR)"
  300. "{"
  301. " float2 coord = in_TexCoord.xy;"
  302. " float i = frac((in_FragCoord.x - 0.5) * 0.5) * 2.0;"
  303. " float j = frac((in_FragCoord.y - 0.5 + i) * 0.5) * 2.0;"
  304. " coord.y += i + j * 2;"
  305. " coord.y *= 0.25;"
  306. " float4 p = tex2D(in_Texture, coord);"
  307. " out_FragColor = p;"
  308. "}"
  309. #endif
  310. );
  311. m_vertexattrib = m_shader->GetAttribLocation("in_Vertex");
  312. m_texattrib = m_shader->GetAttribLocation("in_TexCoord");
  313. m_pixeluni = m_shader->GetUniformLocation("in_PixelDelta");
  314. m_ready = true;
  315. #if !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  316. /* Method 1: store vertex buffer on the GPU memory */
  317. glGenBuffers(1, &m_vbo);
  318. glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
  319. glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
  320. GL_STATIC_DRAW);
  321. glGenBuffers(1, &m_tbo);
  322. glBindBuffer(GL_ARRAY_BUFFER, m_tbo);
  323. glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords,
  324. GL_STATIC_DRAW);
  325. #elif !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  326. /* Method 2: upload vertex information at each frame */
  327. #else
  328. #endif
  329. /* FIXME: this object never cleans up */
  330. }
  331. glEnable(GL_TEXTURE_2D);
  332. glBindTexture(GL_TEXTURE_2D, m_texid);
  333. if (m_dirty[m_frame])
  334. {
  335. m_dirty[m_frame]--;
  336. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, m_frame * m_size.y / 2,
  337. m_size.x / 2, m_size.y / 2,
  338. GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  339. m_pixels + m_size.x * m_size.y / 4 * m_frame);
  340. }
  341. /* If other frames are dirty, upload fake data for now */
  342. if (0) for (int i = 0; i < 4; i++)
  343. {
  344. if (m_dirty[i])
  345. {
  346. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i * m_size.y / 2,
  347. m_size.x / 2, m_size.y / 2,
  348. GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  349. m_pixels + m_size.x * m_size.y / 4 * m_frame);
  350. }
  351. }
  352. m_shader->Bind();
  353. m_shader->SetUniform(m_pixeluni, m_pixel_delta);
  354. #if !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  355. glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
  356. glEnableVertexAttribArray(m_vertexattrib);
  357. glVertexAttribPointer(m_vertexattrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
  358. glBindBuffer(GL_ARRAY_BUFFER, m_tbo);
  359. glEnableVertexAttribArray(m_texattrib);
  360. glVertexAttribPointer(m_texattrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
  361. #elif !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  362. /* Never used for now */
  363. //glEnableVertexAttribArray(m_vertexattrib);
  364. //glVertexAttribPointer(m_vertexattrib, 2, GL_FLOAT, GL_FALSE, 0, vertices);
  365. #else
  366. glEnableClientState(GL_VERTEX_ARRAY);
  367. glVertexPointer(2, GL_FLOAT, 0, vertices);
  368. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  369. glTexCoordPointer(2, GL_FLOAT, 0, texcoords);
  370. #endif
  371. glDrawArrays(GL_TRIANGLES, 0, 6);
  372. #if !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  373. glDisableVertexAttribArray(m_vertexattrib);
  374. glDisableVertexAttribArray(m_texattrib);
  375. glBindBuffer(GL_ARRAY_BUFFER, 0);
  376. #elif !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  377. /* Never used for now */
  378. //glDisableVertexAttribArray(m_vertexattrib);
  379. //glDisableVertexAttribArray(m_texattrib);
  380. #else
  381. glDisableClientState(GL_VERTEX_ARRAY);
  382. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  383. #endif
  384. }
  385. private:
  386. static int const MAX_ITERATIONS = 170;
  387. static int const PALETTE_STEP = 32;
  388. ivec2 m_size, m_window_size;
  389. u8vec4 *m_pixels, *m_tmppixels, *m_palette;
  390. Shader *m_shader;
  391. GLuint m_texid;
  392. #if !defined __CELLOS_LV2__ && !defined __ANDROID__ && !defined __APPLE__
  393. GLuint m_vbo, m_tbo;
  394. GLuint m_tco;
  395. #endif
  396. int m_vertexattrib, m_texattrib, m_pixeluni;
  397. int m_frame, m_dirty[4];
  398. bool m_ready;
  399. f64cmplx m_center;
  400. double m_radius, m_texture_radius, m_window_radius;
  401. vec4 m_pixel_delta;
  402. f64cmplx m_deltashift[4];
  403. double m_deltascale[4];
  404. /* Debug information */
  405. Text *m_centertext, *m_mousetext, *m_zoomtext;
  406. };
  407. int main()
  408. {
  409. #if defined _WIN32
  410. _chdir("../..");
  411. #endif
  412. Application app("Tutorial 3: Fractal", ivec2(640, 480), 60.0f);
  413. new DebugFps(5, 5);
  414. new Fractal(ivec2(640, 480));
  415. //new DebugRecord("fractalol.ogm", 60.0f);
  416. app.Run();
  417. return EXIT_SUCCESS;
  418. }