Native RenderScript APIs

Your RenderScript code has access to a limited set of APIs as it cannot simply call APIs from the NDK or C library. The RenderScript APIs are defined in six header files, located in the SDK's platform/android-xx/renderscript/include (where xx is the API level, for example, 13):

  • rs_types.rsh
  • rs_core.rsh
  • rs_cl.rsh
  • rs_math.rsh
  • rs_graphics.rsh
  • rs_time.rsh

In Ice Cream Sandwich, the RenderScript APIs are defined in 12 header files. In addition to the six header files above, the following six files were added:

  • rs_allocation.rsh
  • rs_atomic.rsh
  • rs_debug.rsh
  • rs_matrix.rsh
  • rs_object.rsh
  • rs_quaternion.rsh

Again, as online documentation for RenderScript is currently quite scant, it is recommended you review these files. One of the big differences between Honeycomb and Ice Cream Sandwich is the addition of comments in these header files. You should therefore refer to the Android 4.0 RenderScript header files whenever possible since you will find more information in those than in the Honeycomb header files.

rs_types.rsh

  • This header file defines the basic types used in RenderScript (in addition to the C99 standard types char, short, int, long, and float):
  • int8_t
  • int16_t
  • int32_t
  • int64_t
  • uint8_t
  • uint16_t
  • uint32_t
  • uint64_t
  • uchar (defined as uint8_t)
  • ushort (defined as uint16_t)
  • uint (defined as uint32_t)
  • ulong (defined as uint64_t)

In addition to these basic types, this file defines vector types:

  • float2
  • float3
  • float4
  • double2 (Android 4.0 and above)
  • double3 (Android 4.0 and above)
  • double4 (Android 4.0 and above)
  • char2
  • char3
  • char4
  • uchar2
  • uchar3
  • uchar4
  • short2
  • short3
  • short4
  • ushort2
  • ushort3
  • ushort4
  • int2
  • int3
  • int4
  • uint2
  • uint3
  • uint4

Since a 3D framework would not be complete without matrices, several matrix types are also defined:

  • rs_matrix2x2 (square matrix of order 2)
  • rs_matrix3x3 (square matrix of order 3)
  • rs_matrix4x4 (square matrix of order 4)

NOTE: While vector types are defined for both floating-point and integer vectors (for example, float2, ushort3, and int4), matrix types use float only.

Honeycomb MR1 (API level 12) introduced the quaternion type rs_quaternion (defined as float4). Additional APIs were also introduced to manipulate this new type.

As you can see, the number of types is relatively high, however each of these types can be seen as a scalar, a vector, or a matrix.

The following types are also defined in rs_types.rsh and are opaque handles to their Java counterparts:

  • rs_element
  • rs_type
  • rs_allocation
  • rs_sampler
  • rs_script
  • rs_mesh
  • rs_program_fragment
  • rs_program_vertex
  • rs_program_raster
  • rs_program_store
  • rs_font

All these types are also exposed in the Java layer in the android.renderscript package:

  • Byte2
  • Byte3
  • Byte4
  • Double2 (Android 4.0 and above)
  • Double3 (Android 4.0 and above)
  • Double4 (Android 4.0 and above)
  • Float2
  • Float3
  • Float4
  • Int2
  • Int3
  • Int4
  • Long2
  • Long3
  • Long4
  • Matrix2f
  • Matrix3f
  • Matrix4f
  • Short2
  • Short3
  • Short4
  • Element
  • Type
  • Allocation
  • Sampler
  • Script
  • Mesh
  • ProgramFragment
  • ProgramVertex
  • ProgramRaster
  • ProgramStore
  • Font

rs_core.rsh

This header file defines the following functions in Honeycomb:

  • rsDebug
  • rsPackColorTo8888
  • rsUnpackColor8888
  • rsMatrixSet
  • rsMatrixGet
  • rsMatrixLoadIdentity
  • rsMatrixLoad
  • rsMatrixLoadRotate
  • rsMatrixLoadScale
  • rsMatrixLoadTranslate
  • rsMatrixLoadMultiply
  • rsMatrixMultiply
  • rsMatrixRotate
  • rsMatrixScale
  • rsMatrixTranslate
  • rsMatrixLoadOrtho
  • rsMatrixLoadFrustum
  • rsMatrixLoadPerspective
  • rsMatrixInverse
  • rsMatrixInverseTranspose
  • rsMatrixTranspose
  • rsClamp

The matrix functions were moved to a dedicated header file in Android 4.0: rs_matrix.rsh.

As the quaternion type was introduced in Honeycomb MR1 (Android 3.1), new functions were also added to rs_core.rsh:

  • rsQuaternionSet
  • rsQuaternionMultiply
  • rsQuaternionAdd
  • rsQuaternionLoadRotateUnit
  • rsQuaternionLoadRotate
  • rsQuaternionConjugate
  • rsQuaternionDot
  • rsQuaternionNormalize
  • rsQuaternionSlerp
  • rsQuaternionGetMatrixUnit

This header file went through a metamorphosis in Android 4.0. As a matter of fact, the Honeycomb version of this file was a little bit all over the place, containing matrix, quaternion, debugging, and some math functions. The file was dramatically reorganized in Android 4.0 to define only the following functions:

  • rsSendToClient
  • rsSendToClientBlocking
  • rsForEach

The matrix, quaternion, and debugging functions were moved to their new respective files (rs_matrix.rsh, rs_quaternion.rsh, and rs_debug.rsh) while the math functions were naturally moved to rs_math.rsh. Since header files are automatically included, the fact that functions were moved from one header file to another should not affect your script.

rs_cl.rsh

This header file is actually somewhat hard to read as it uses many macros to define functions. It contains the main “compute” APIs, and if you played hooky instead of attending math classes, you are in for a shock.

This header file defines the following math functions:

  • acos        arc cosine
  • acosh    inverse hyperbolic cosine
  • acospi    acos(x) / pi
  • asin        arc sine
  • asinh        inverse hyperbolic sine
  • asinpi    asin(x) / pi
  • atan        arc tangent
  • atan2        arc tangent with 2 parameters
  • atanh        hyperbolic arc tangent
  • atanpi    atan(x) / pi
  • atan2pi    atan2(x,y) / pi
  • cbrt        cubic root
  • ceil        round up value
  • copysign    x with its sign changed to sign of y
  • cos        cosine
  • cosh        hyperbolic cosine
  • cospi        cos(pi * x)
  • erf        error function encountered in integrating the normal distribution
  • erfc        complimentary error function
  • exp        ex
  • exp2        2x
  • exp10    10x
  • expm1    ex – 1.0
  • fabs        absolute value of floating-point value
  • fdim        positive difference between x and y
  • floor        largest integer less than or equal to x
  • fma        (x * y) + z, rounded
  • fmax        maximum of 2 floating-point values
  • fmin        minimum of 2 floating-point values
  • fmod        modulus
  • fract        fractional value in x (floor(x) also returned)
  • frexp        extract mantissa and exponent
  • hypot    square root of x2 + y2
  • ilogb        exponent as integer value
  • ldexp        x * 2y
  • lgamma    natural logarithm of the absolute value of the gamma
  • log        natural logarithm (base e)
  • log10        common logarithm (base 10)
  • log2        logarithm base 2
  • log1p        natural logarithm of 1+x
  • logb        exponent of x, which is the integral part of logr|x|
  • mad        approximation of (x * y) + z (when speed is preferred over accuracy)
  • modf        decompose floating-point number into integral and fractional parts
  • nextafter    next representable floating-point value following x in the direction of y
  • pow        xy
  • pown        xy (y is integer)
  • powr        xy (x greater than or equal to zero)
  • remainder    remainder
  • remquo    remainder and quotient
  • rint        round to nearest integer (in floating-point format)
  • rootn        x1/y
  • round    nearest integer value (in floating-point format)
  • sqrt        square root
  • rsqrt        reciprocal of square root (i.e. 1.0 / sqrt(x))
  • sin        sine
  • sincos    sine and cosine
  • sinh        hyperbolic sine
  • sinpi        sin(pi * x)
  • tan        tangent
  • tanh        hyperbolic tangent
  • tanpi        tan(pi * x)
  • tgamma    gamma function
  • trunc        truncate floating-point value

It also defines these few integer functions:

  • abs        absolute value
  • clz        number of leading 0-bits
  • min        minimum of two integers
  • max        maximum of two integers

Some other common functions are also defined:

  • clamp    clamp amount to range given by low and high
  • degrees    convert radians to degrees
  • mix        start + (stopstart)*amount (linear blend)
  • radians    convert degrees to radians
  • step        0.0 if v is less than edge, else 1.0
  • smoothstep    0.0 if v ≤ edge0, 1.0 if v ≥ edge1, else smooth Hermite interpolation
  • sign        sign (-1.0, -0.0, +0.0 or 1.0)

Last but not least, this header file defines some geometric functions:

  • cross        cross product
  • dot        dot product
  • length    vector length
  • distance    distance between 2 points
  • normalize    normalize vector (length will be 1.0)

If you are familiar with OpenCL, you should recognize these APIs. As a matter of fact, the Honeycomb rs_cl.rsh header file itself refers to the OpenCL documentation as it contains comments referring to sections 6.11.2, 6.11.3, 6.11.4, and 6.11.5, which are the sections in the OpenCL 1.1 specifications covering the math, integer, common, and geometric functions respectively. Listing 9–18 shows these comments from rs_cl.rsh. You can also refer to the OpenCL documentation for more information, which is freely available on the Khronos website (www.khronos.org/opencl).

Listing 9–18. Comments Referring To OpenCL In rs_cl.rsh

#ifndef __RS_CL_RSH__
#define __RS_CL_RSH__

...

// Float ops, 6.11.2

...
extern float __attribute__((overloadable)) trunc(float);
FN_FUNC_FN(trunc)

// Int ops (partial), 6.11.3

...
IN_FUNC_IN_IN_BODY(max, (v1 > v2 ? v1 : v2))
FN_FUNC_FN_F(max)

// 6.11.4

_RS_RUNTIME float __attribute__((overloadable)) clamp(float amount, float low, float high);
...

// 6.11.5
_RS_RUNTIME float3 __attribute__((overloadable)) cross(float3 lhs, float3 rhs);

...

#endif

This header file also defines some conversion functions such as convert_int3, which converts a vector of three elements to a vector of three integers.

rs_math.rsh

This header file defines the following functions in Honeycomb:

  • rsSetObject
  • rsClearObject
  • rsIsObject
  • rsGetAllocation
  • rsAllocationGetDimX
  • rsAllocationGetDimY
  • rsAllocationGetDimZ
  • rsAllocationGetDimLOD
  • rsAllocationGetDimFaces
  • rsGetElementAt
  • rsRand
  • rsFrac
  • rsSendToClient
  • rsSendToClientBlocking
  • rsForEach

As we saw earlier, rsForEach() is one of the most important functions.

The rsSendToClient() and rsSendToClientBlocking() functions (moved to rs_core.rsh in Android 4.0) are worth mentioning as they allow a script to send data to the Java layer. For the Java layer to be able to receive data, your application will have to register a message handler, as shown in Listing 9–19.

Listing 9–19. Message Handler

    RenderScript rs = RenderScript.create(this); // needs a Context as parameter
    
    rs.setMessageHandler(new RenderScript.RSMessageHandler() {

        @Override
        public void run() {
            super.run();
            Log.d(TAG, String.valueOf(this.mID) + " " + mData + ", length:" + mLength);
        }
    });

The handler's mID, mData, and mLength fields will contain the information passed by the script. If your script sends data to the Java layer but no handler is registered, an exception will be thrown.

In Android 4.0, the rs_math.rsh was also modified to focus exclusively on mathematical functions:

  • rsRand
  • rsFrac
  • rsClamp
  • rsExtractFrustumPlanes (new in Android 4.0)
  • rsIsSphereInFrustum (new in Android 4.0)
  • rsPackColorTo8888
  • rsUnpackColor8888

The allocation functions were moved to a new file, rs_allocation.rsh, which, in addition to the functions introduced in Honeycomb, defines the following two new functions:

  • rsAllocationCopy1DRange
  • rsAllocationCopy2DRange

The object functions were also moved to a new header file: rs_object.rsh.

rs_graphics.rsh

This header files defines the following functions:

  • rsgBindProgramFragment
  • rsgBindProgramStore
  • rsgBindProgramVertex
  • rsgBindProgramRaster
  • rsgBindSampler
  • rsgBindTexture
  • rsgProgramVertexLoadProjectionMatrix
  • rsgProgramVertexLoadModelMatrix
  • rsgProgramVertexLoadTextureMatrix
  • rsgProgramVertexGetProjectionMatrix
  • rsgProgramFragmentConstantColor
  • rsgGetWidth
  • rsgGetHeight
  • rsgAllocationsSyncAll (new overloaded function added in Android 4.0)
  • rsgDrawRect
  • rsgDrawQuad
  • rsgDrawQuadTexCoords
  • rsgDrawSpriteScreenspace
  • rsgDrawMesh
  • rsgClearColor
  • rsgClearDepth
  • rsgDrawText
  • rsgBindFont
  • rsgFontColor
  • rsgMeasureText
  • rsgMeshComputeBoundingBox

In Android 4.0 the following functions were added to rs_graphics.rsh:

  • rsgBindColorTarget
  • rsgClearColorTarget
  • rsgBindDepthTarget
  • rsgClearDepthTarget
  • rsgClearAllRenderTargets
  • rsgFinish

Since the focus of this chapter is not on making you an expert in 3D rendering, we won't review these functions in detail. If you are already familiar with OpenGL, then you should easily be able to use these functions. If you are not, then it is recommended you first get familiar with 3D terms like fragment, vertex, and mesh before you dive into RenderScript.

rs_time.rsh

This file defines the following:

  • rsTime
  • rsLocalTime
  • rsUptimeMillis
  • rsUptimeNanos
  • rsGetDt

Of particular interest is the rsGetDt() function, which returns the number of seconds (as a floating-point value) since it was last called. Listing 9–20 shows how this would typically be used in a script.

Listing 9–20. Calling rsGetDt()

#pragma version(1)
#pragma rs java_package_name(com.yourpackagehere)

typedef struct __attribute__((packed, aligned(4))) MyObject {
    float x;
    float other_property;
} MyObject_t;
MyObject_t *object; // Java layer would have to call bind_object

int root() {
    float dt = rsGetDt();
    float dx = dt * 10.f; // 10 pixels per second

    object->x += dx; // new x position of object

    // do something else here, for example to draw the object

    return 20;
}

NOTE: While the root() function returns 20 (that is, 20 milliseconds between frames, or 50 frames per second), the frame rate is not guaranteed. This is why your code should use rsGetDt() instead of assuming the duration between two frames is the value root() returns.

rs_atomic.rsh

New in Android 4.0, this file defines functions that were not defined in Honeycomb:

  • rsAtomicInc
  • rsAtomicDec
  • rsAtomicAdd
  • rsAtomicSub
  • rsAtomicAnd
  • rsAtomicOr
  • rsAtomicXor
  • rsAtomicMin
  • rsAtomicMax
  • rsAtomicCas

As their names indicate, these functions perform various operations atomically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.195.56