source: trunk/tutorial/11_fractal.cpp @ 2285

Last change on this file since 2285 was 2277, checked in by sam, 10 years ago

build: hide LolFx external declarations behind macros.

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