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

Last change on this file since 1987 was 1987, checked in by sam, 7 years ago

gpu: put the texture creation code in its own class; for now a lot of things are
hardcoded and only the fractal demo uses it, but everything will eventually switch.

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