Home | History | Annotate | Download | only in jni
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  *
     16  */
     17 
     18 #include <android_native_app_glue.h>
     19 
     20 #include <errno.h>
     21 #include <jni.h>
     22 #include <sys/time.h>
     23 #include <time.h>
     24 #include <android/log.h>
     25 
     26 #include <stdio.h>
     27 #include <stdlib.h>
     28 #include <math.h>
     29 
     30 #define  LOG_TAG    "libplasma"
     31 #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
     32 #define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
     33 #define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
     34 
     35 /* Set to 1 to enable debug log traces. */
     36 #define DEBUG 0
     37 
     38 /* Set to 1 to optimize memory stores when generating plasma. */
     39 #define OPTIMIZE_WRITES  1
     40 
     41 /* Return current time in milliseconds */
     42 static double now_ms(void)
     43 {
     44     struct timeval tv;
     45     gettimeofday(&tv, NULL);
     46     return tv.tv_sec*1000. + tv.tv_usec/1000.;
     47 }
     48 
     49 /* We're going to perform computations for every pixel of the target
     50  * bitmap. floating-point operations are very slow on ARMv5, and not
     51  * too bad on ARMv7 with the exception of trigonometric functions.
     52  *
     53  * For better performance on all platforms, we're going to use fixed-point
     54  * arithmetic and all kinds of tricks
     55  */
     56 
     57 typedef int32_t  Fixed;
     58 
     59 #define  FIXED_BITS           16
     60 #define  FIXED_ONE            (1 << FIXED_BITS)
     61 #define  FIXED_AVERAGE(x,y)   (((x) + (y)) >> 1)
     62 
     63 #define  FIXED_FROM_INT(x)    ((x) << FIXED_BITS)
     64 #define  FIXED_TO_INT(x)      ((x) >> FIXED_BITS)
     65 
     66 #define  FIXED_FROM_FLOAT(x)  ((Fixed)((x)*FIXED_ONE))
     67 #define  FIXED_TO_FLOAT(x)    ((x)/(1.*FIXED_ONE))
     68 
     69 #define  FIXED_MUL(x,y)       (((int64_t)(x) * (y)) >> FIXED_BITS)
     70 #define  FIXED_DIV(x,y)       (((int64_t)(x) * FIXED_ONE) / (y))
     71 
     72 #define  FIXED_DIV2(x)        ((x) >> 1)
     73 #define  FIXED_AVERAGE(x,y)   (((x) + (y)) >> 1)
     74 
     75 #define  FIXED_FRAC(x)        ((x) & ((1 << FIXED_BITS)-1))
     76 #define  FIXED_TRUNC(x)       ((x) & ~((1 << FIXED_BITS)-1))
     77 
     78 #define  FIXED_FROM_INT_FLOAT(x,f)   (Fixed)((x)*(FIXED_ONE*(f)))
     79 
     80 typedef int32_t  Angle;
     81 
     82 #define  ANGLE_BITS              9
     83 
     84 #if ANGLE_BITS < 8
     85 #  error ANGLE_BITS must be at least 8
     86 #endif
     87 
     88 #define  ANGLE_2PI               (1 << ANGLE_BITS)
     89 #define  ANGLE_PI                (1 << (ANGLE_BITS-1))
     90 #define  ANGLE_PI2               (1 << (ANGLE_BITS-2))
     91 #define  ANGLE_PI4               (1 << (ANGLE_BITS-3))
     92 
     93 #define  ANGLE_FROM_FLOAT(x)   (Angle)((x)*ANGLE_PI/M_PI)
     94 #define  ANGLE_TO_FLOAT(x)     ((x)*M_PI/ANGLE_PI)
     95 
     96 #if ANGLE_BITS <= FIXED_BITS
     97 #  define  ANGLE_FROM_FIXED(x)     (Angle)((x) >> (FIXED_BITS - ANGLE_BITS))
     98 #  define  ANGLE_TO_FIXED(x)       (Fixed)((x) << (FIXED_BITS - ANGLE_BITS))
     99 #else
    100 #  define  ANGLE_FROM_FIXED(x)     (Angle)((x) << (ANGLE_BITS - FIXED_BITS))
    101 #  define  ANGLE_TO_FIXED(x)       (Fixed)((x) >> (ANGLE_BITS - FIXED_BITS))
    102 #endif
    103 
    104 static Fixed  angle_sin_tab[ANGLE_2PI+1];
    105 
    106 static void init_angles(void)
    107 {
    108     int  nn;
    109     for (nn = 0; nn < ANGLE_2PI+1; nn++) {
    110         double  radians = nn*M_PI/ANGLE_PI;
    111         angle_sin_tab[nn] = FIXED_FROM_FLOAT(sin(radians));
    112     }
    113 }
    114 
    115 static __inline__ Fixed angle_sin( Angle  a )
    116 {
    117     return angle_sin_tab[(uint32_t)a & (ANGLE_2PI-1)];
    118 }
    119 
    120 static __inline__ Fixed angle_cos( Angle  a )
    121 {
    122     return angle_sin(a + ANGLE_PI2);
    123 }
    124 
    125 static __inline__ Fixed fixed_sin( Fixed  f )
    126 {
    127     return angle_sin(ANGLE_FROM_FIXED(f));
    128 }
    129 
    130 static __inline__ Fixed  fixed_cos( Fixed  f )
    131 {
    132     return angle_cos(ANGLE_FROM_FIXED(f));
    133 }
    134 
    135 /* Color palette used for rendering the plasma */
    136 #define  PALETTE_BITS   8
    137 #define  PALETTE_SIZE   (1 << PALETTE_BITS)
    138 
    139 #if PALETTE_BITS > FIXED_BITS
    140 #  error PALETTE_BITS must be smaller than FIXED_BITS
    141 #endif
    142 
    143 static uint16_t  palette[PALETTE_SIZE];
    144 
    145 static uint16_t  make565(int red, int green, int blue)
    146 {
    147     return (uint16_t)( ((red   << 8) & 0xf800) |
    148                        ((green << 2) & 0x03e0) |
    149                        ((blue  >> 3) & 0x001f) );
    150 }
    151 
    152 static void init_palette(void)
    153 {
    154     int  nn, mm = 0;
    155     /* fun with colors */
    156     for (nn = 0; nn < PALETTE_SIZE/4; nn++) {
    157         int  jj = (nn-mm)*4*255/PALETTE_SIZE;
    158         palette[nn] = make565(255, jj, 255-jj);
    159     }
    160 
    161     for ( mm = nn; nn < PALETTE_SIZE/2; nn++ ) {
    162         int  jj = (nn-mm)*4*255/PALETTE_SIZE;
    163         palette[nn] = make565(255-jj, 255, jj);
    164     }
    165 
    166     for ( mm = nn; nn < PALETTE_SIZE*3/4; nn++ ) {
    167         int  jj = (nn-mm)*4*255/PALETTE_SIZE;
    168         palette[nn] = make565(0, 255-jj, 255);
    169     }
    170 
    171     for ( mm = nn; nn < PALETTE_SIZE; nn++ ) {
    172         int  jj = (nn-mm)*4*255/PALETTE_SIZE;
    173         palette[nn] = make565(jj, 0, 255);
    174     }
    175 }
    176 
    177 static __inline__ uint16_t  palette_from_fixed( Fixed  x )
    178 {
    179     if (x < 0) x = -x;
    180     if (x >= FIXED_ONE) x = FIXED_ONE-1;
    181     int  idx = FIXED_FRAC(x) >> (FIXED_BITS - PALETTE_BITS);
    182     return palette[idx & (PALETTE_SIZE-1)];
    183 }
    184 
    185 /* Angles expressed as fixed point radians */
    186 
    187 static void init_tables(void)
    188 {
    189     init_palette();
    190     init_angles();
    191 }
    192 
    193 static void fill_plasma(ANativeWindow_Buffer* buffer, double  t)
    194 {
    195     Fixed yt1 = FIXED_FROM_FLOAT(t/1230.);
    196     Fixed yt2 = yt1;
    197     Fixed xt10 = FIXED_FROM_FLOAT(t/3000.);
    198     Fixed xt20 = xt10;
    199 
    200 #define  YT1_INCR   FIXED_FROM_FLOAT(1/100.)
    201 #define  YT2_INCR   FIXED_FROM_FLOAT(1/163.)
    202 
    203     void* pixels = buffer->bits;
    204     //LOGI("width=%d height=%d stride=%d format=%d", buffer->width, buffer->height,
    205     //        buffer->stride, buffer->format);
    206 
    207     int  yy;
    208     for (yy = 0; yy < buffer->height; yy++) {
    209         uint16_t*  line = (uint16_t*)pixels;
    210         Fixed      base = fixed_sin(yt1) + fixed_sin(yt2);
    211         Fixed      xt1 = xt10;
    212         Fixed      xt2 = xt20;
    213 
    214         yt1 += YT1_INCR;
    215         yt2 += YT2_INCR;
    216 
    217 #define  XT1_INCR  FIXED_FROM_FLOAT(1/173.)
    218 #define  XT2_INCR  FIXED_FROM_FLOAT(1/242.)
    219 
    220 #if OPTIMIZE_WRITES
    221         /* optimize memory writes by generating one aligned 32-bit store
    222          * for every pair of pixels.
    223          */
    224         uint16_t*  line_end = line + buffer->width;
    225 
    226         if (line < line_end) {
    227             if (((uint32_t)(uintptr_t)line & 3) != 0) {
    228                 Fixed ii = base + fixed_sin(xt1) + fixed_sin(xt2);
    229 
    230                 xt1 += XT1_INCR;
    231                 xt2 += XT2_INCR;
    232 
    233                 line[0] = palette_from_fixed(ii >> 2);
    234                 line++;
    235             }
    236 
    237             while (line + 2 <= line_end) {
    238                 Fixed i1 = base + fixed_sin(xt1) + fixed_sin(xt2);
    239                 xt1 += XT1_INCR;
    240                 xt2 += XT2_INCR;
    241 
    242                 Fixed i2 = base + fixed_sin(xt1) + fixed_sin(xt2);
    243                 xt1 += XT1_INCR;
    244                 xt2 += XT2_INCR;
    245 
    246                 uint32_t  pixel = ((uint32_t)palette_from_fixed(i1 >> 2) << 16) |
    247                                    (uint32_t)palette_from_fixed(i2 >> 2);
    248 
    249                 ((uint32_t*)line)[0] = pixel;
    250                 line += 2;
    251             }
    252 
    253             if (line < line_end) {
    254                 Fixed ii = base + fixed_sin(xt1) + fixed_sin(xt2);
    255                 line[0] = palette_from_fixed(ii >> 2);
    256                 line++;
    257             }
    258         }
    259 #else /* !OPTIMIZE_WRITES */
    260         int xx;
    261         for (xx = 0; xx < buffer->width; xx++) {
    262 
    263             Fixed ii = base + fixed_sin(xt1) + fixed_sin(xt2);
    264 
    265             xt1 += XT1_INCR;
    266             xt2 += XT2_INCR;
    267 
    268             line[xx] = palette_from_fixed(ii / 4);
    269         }
    270 #endif /* !OPTIMIZE_WRITES */
    271 
    272         // go to next line
    273         pixels = (uint16_t*)pixels + buffer->stride;
    274     }
    275 }
    276 
    277 /* simple stats management */
    278 typedef struct {
    279     double  renderTime;
    280     double  frameTime;
    281 } FrameStats;
    282 
    283 #define  MAX_FRAME_STATS  200
    284 #define  MAX_PERIOD_MS    1500
    285 
    286 typedef struct {
    287     double  firstTime;
    288     double  lastTime;
    289     double  frameTime;
    290 
    291     int         firstFrame;
    292     int         numFrames;
    293     FrameStats  frames[ MAX_FRAME_STATS ];
    294 } Stats;
    295 
    296 static void
    297 stats_init( Stats*  s )
    298 {
    299     s->lastTime = now_ms();
    300     s->firstTime = 0.;
    301     s->firstFrame = 0;
    302     s->numFrames  = 0;
    303 }
    304 
    305 static void
    306 stats_startFrame( Stats*  s )
    307 {
    308     s->frameTime = now_ms();
    309 }
    310 
    311 static void
    312 stats_endFrame( Stats*  s )
    313 {
    314     double now = now_ms();
    315     double renderTime = now - s->frameTime;
    316     double frameTime  = now - s->lastTime;
    317     int nn;
    318 
    319     if (now - s->firstTime >= MAX_PERIOD_MS) {
    320         if (s->numFrames > 0) {
    321             double minRender, maxRender, avgRender;
    322             double minFrame, maxFrame, avgFrame;
    323             int count;
    324 
    325             nn = s->firstFrame;
    326             minRender = maxRender = avgRender = s->frames[nn].renderTime;
    327             minFrame  = maxFrame  = avgFrame  = s->frames[nn].frameTime;
    328             for (count = s->numFrames; count > 0; count-- ) {
    329                 nn += 1;
    330                 if (nn >= MAX_FRAME_STATS)
    331                     nn -= MAX_FRAME_STATS;
    332                 double render = s->frames[nn].renderTime;
    333                 if (render < minRender) minRender = render;
    334                 if (render > maxRender) maxRender = render;
    335                 double frame = s->frames[nn].frameTime;
    336                 if (frame < minFrame) minFrame = frame;
    337                 if (frame > maxFrame) maxFrame = frame;
    338                 avgRender += render;
    339                 avgFrame  += frame;
    340             }
    341             avgRender /= s->numFrames;
    342             avgFrame  /= s->numFrames;
    343 
    344             LOGI("frame/s (avg,min,max) = (%.1f,%.1f,%.1f) "
    345                  "render time ms (avg,min,max) = (%.1f,%.1f,%.1f)\n",
    346                  1000./avgFrame, 1000./maxFrame, 1000./minFrame,
    347                  avgRender, minRender, maxRender);
    348         }
    349         s->numFrames  = 0;
    350         s->firstFrame = 0;
    351         s->firstTime  = now;
    352     }
    353 
    354     nn = s->firstFrame + s->numFrames;
    355     if (nn >= MAX_FRAME_STATS)
    356         nn -= MAX_FRAME_STATS;
    357 
    358     s->frames[nn].renderTime = renderTime;
    359     s->frames[nn].frameTime  = frameTime;
    360 
    361     if (s->numFrames < MAX_FRAME_STATS) {
    362         s->numFrames += 1;
    363     } else {
    364         s->firstFrame += 1;
    365         if (s->firstFrame >= MAX_FRAME_STATS)
    366             s->firstFrame -= MAX_FRAME_STATS;
    367     }
    368 
    369     s->lastTime = now;
    370 }
    371 
    372 // ----------------------------------------------------------------------
    373 
    374 struct engine {
    375     struct android_app* app;
    376 
    377     Stats stats;
    378 
    379     int animating;
    380 };
    381 
    382 static void engine_draw_frame(struct engine* engine) {
    383     if (engine->app->window == NULL) {
    384         // No window.
    385         return;
    386     }
    387 
    388     ANativeWindow_Buffer buffer;
    389     if (ANativeWindow_lock(engine->app->window, &buffer, NULL) < 0) {
    390         LOGW("Unable to lock window buffer");
    391         return;
    392     }
    393 
    394     stats_startFrame(&engine->stats);
    395 
    396     struct timespec t;
    397     t.tv_sec = t.tv_nsec = 0;
    398     clock_gettime(CLOCK_MONOTONIC, &t);
    399     int64_t time_ms = (((int64_t)t.tv_sec)*1000000000LL + t.tv_nsec)/1000000;
    400 
    401     /* Now fill the values with a nice little plasma */
    402     fill_plasma(&buffer, time_ms);
    403 
    404     ANativeWindow_unlockAndPost(engine->app->window);
    405 
    406     stats_endFrame(&engine->stats);
    407 }
    408 
    409 static void engine_term_display(struct engine* engine) {
    410     engine->animating = 0;
    411 }
    412 
    413 static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
    414     struct engine* engine = (struct engine*)app->userData;
    415     if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
    416         engine->animating = 1;
    417         return 1;
    418     } else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) {
    419         LOGI("Key event: action=%d keyCode=%d metaState=0x%x",
    420                 AKeyEvent_getAction(event),
    421                 AKeyEvent_getKeyCode(event),
    422                 AKeyEvent_getMetaState(event));
    423     }
    424 
    425     return 0;
    426 }
    427 
    428 static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
    429     struct engine* engine = (struct engine*)app->userData;
    430     switch (cmd) {
    431         case APP_CMD_INIT_WINDOW:
    432             if (engine->app->window != NULL) {
    433                 engine_draw_frame(engine);
    434             }
    435             break;
    436         case APP_CMD_TERM_WINDOW:
    437             engine_term_display(engine);
    438             break;
    439         case APP_CMD_LOST_FOCUS:
    440             engine->animating = 0;
    441             engine_draw_frame(engine);
    442             break;
    443     }
    444 }
    445 
    446 void android_main(struct android_app* state) {
    447     static int init;
    448 
    449     struct engine engine;
    450 
    451     // Make sure glue isn't stripped.
    452     app_dummy();
    453 
    454     memset(&engine, 0, sizeof(engine));
    455     state->userData = &engine;
    456     state->onAppCmd = engine_handle_cmd;
    457     state->onInputEvent = engine_handle_input;
    458     engine.app = state;
    459 
    460     if (!init) {
    461         init_tables();
    462         init = 1;
    463     }
    464 
    465     stats_init(&engine.stats);
    466 
    467     // loop waiting for stuff to do.
    468 
    469     while (1) {
    470         // Read all pending events.
    471         int ident;
    472         int events;
    473         struct android_poll_source* source;
    474 
    475         // If not animating, we will block forever waiting for events.
    476         // If animating, we loop until all events are read, then continue
    477         // to draw the next frame of animation.
    478         while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
    479                 (void**)&source)) >= 0) {
    480 
    481             // Process this event.
    482             if (source != NULL) {
    483                 source->process(state, source);
    484             }
    485 
    486             // Check if we are exiting.
    487             if (state->destroyRequested != 0) {
    488                 LOGI("Engine thread destroy requested!");
    489                 engine_term_display(&engine);
    490                 return;
    491             }
    492         }
    493 
    494         if (engine.animating) {
    495             engine_draw_frame(&engine);
    496         }
    497     }
    498 }
    499