Search code examples
androidperformancec99renderscriptandroid-renderscript

Is it possible to access more Elements in RenderScript kernel? [Android]


I want to access more Elements from one Allocation in RenderScript. Let's take the example code from Google:

uchar4 __attribute__((kernel)) invert(uchar4 in, uint32_t x, uint32_t y) {
  uchar4 out = in;
  out.r = 255 - in.r;
  out.g = 255 - in.g;
  out.b = 255 - in.b;
  return out;
}

It takes one uchar4 in, who is one Element of the Allocation. Is it possible to access and manipolate more than one Element? Like unrolling a loop with, for example, 8 pixels from a Bitmap.

Thank you.


Solution

  • The kernel you wrote just allows to manipulate the current pixel (x,y) based on current pixel data. In order to access neighbour pixels you need to define the in-allocation as a global allocation and then access neighbours by rsGetElementAt_uchar4(). Just for Illustration see below example.

    rs_allocation in;
    
    uchar4 __attribute__((kernel)) doCalc(uint32_t x, uint32_t y) {
      uchar4 out;
    
      uchar4 same= rsGetElementAt_uchar4(in, x,y);
      uchar4 top= rsGetElementAt_uchar4(in, x,y-1);
      uchar4 left= rsGetElementAt_uchar4(in, x-1,y);
      uchar4 right= rsGetElementAt_uchar4(in, x+1,y);
      // (...)
    
     out.r= // do whatever you want with same.r, top.r, left.r etc
     out.g= // do whatever you want with same.g, top.g, left.g etc
     out.b=...
     out.a=255;
    
     return out;
    
    }