diff options
author | Scott Main <smain@google.com> | 2012-06-21 17:14:39 -0700 |
---|---|---|
committer | Scott Main <smain@google.com> | 2012-06-21 21:27:30 -0700 |
commit | 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a (patch) | |
tree | 52605cd25e01763596477956963fabcd087054b0 /docs/html/guide/topics/graphics | |
parent | a2860267cad115659018d636bf9203a644c680a7 (diff) | |
download | frameworks_base-50e990c64fa23ce94efa76b9e72df7f8ec3cee6a.zip frameworks_base-50e990c64fa23ce94efa76b9e72df7f8ec3cee6a.tar.gz frameworks_base-50e990c64fa23ce94efa76b9e72df7f8ec3cee6a.tar.bz2 |
Massive clobber of all HTML files in developer docs for new site design
Change-Id: Idc55a0b368c1d2c1e7d4999601b739dd57f08eb3
Diffstat (limited to 'docs/html/guide/topics/graphics')
-rw-r--r-- | docs/html/guide/topics/graphics/2d-graphics.jd | 2 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/animation.jd | 64 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/index.jd | 90 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/opengl.jd | 52 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/overview.jd | 73 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/prop-animation.jd | 25 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/renderscript/compute.jd | 253 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/renderscript/graphics.jd | 994 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/renderscript/index.jd | 804 | ||||
-rw-r--r-- | docs/html/guide/topics/graphics/renderscript/reference.jd | 18 |
10 files changed, 2255 insertions, 120 deletions
diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd index 5cf1a59..d842cb9 100644 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -476,7 +476,7 @@ allowed. do. </p> -<p>The <a href="{@docRoot}guide/developing/tools/draw9patch.html">Draw 9-patch</a> tool offers +<p>The <a href="{@docRoot}tools/help/draw9patch.html">Draw 9-patch</a> tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It even raises warnings if the region you've defined for the stretchable area is at risk of producing drawing artifacts as a result of the pixel replication. diff --git a/docs/html/guide/topics/graphics/animation.jd b/docs/html/guide/topics/graphics/animation.jd deleted file mode 100644 index 561369d..0000000 --- a/docs/html/guide/topics/graphics/animation.jd +++ /dev/null @@ -1,64 +0,0 @@ -page.title=Animation -@jd:body - - <div id="qv-wrapper"> - <div id="qv"> - - <h2>See also</h2> - <ol> - <li><a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property -Animation</a></li> - <li><a href="{@docRoot}guide/topics/graphics/view-animation.html">View Animation</a></li> - <li><a href="{@docRoot}guide/topics/graphics/drawable-animation.html">Drawable Animation</a></li> - <ol> - </div> - </div> - - <p>The Android framework provides two animation systems: property animation - (introduced in Android 3.0) and view animation. Both animation systems are viable options, - but the property animation system, in general, is the preferred method to use, because it - is more flexible and offers more features. In addition to these two systems, you can utilize Drawable -animation, which allows you to load drawable resources and display them one frame after -another.</p> - - <p>The view animation system provides the capability to only animate {@link android.view.View} -objects, so if you wanted to animate non-{@link android.view.View} objects, you have to implement -your own code to do so. The view animation system is also constrained in the fact that it only -exposes a few aspects of a {@link android.view.View} object to animate, such as the scaling and -rotation of a View but not the background color, for instance.</p> - - <p>Another disadvantage of the view animation system is that it only modified where the - View was drawn, and not the actual View itself. For instance, if you animated a button to move - across the screen, the button draws correctly, but the actual location where you can click the - button does not change, so you have to implement your own logic to handle this.</p> - - <p>With the property animation system, these constraints are completely removed, and you can animate - any property of any object (Views and non-Views) and the object itself is actually modified. - The property animation system is also more robust in the way it carries out animation. At - a high level, you assign animators to the properties that you want to animate, such as color, - position, or size and can define aspects of the animation such as interpolation and - synchronization of multiple animators.</p> - - <p>The view animation system, however, takes less time to setup and requires less code to write. - If view animation accomplishes everything that you need to do, or if your existing code already - works the way you want, there is no need to use the property animation system. It also might - make sense to use both animation systems for different situations if the use case arises.</p> - -<dl> -<dt><strong><a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property -Animation</a></strong></dt> -<dd>Introduced in Android 3.0 (API level 11), the property animation system lets you -animate properties of any object, including ones that are not rendered to the screen. The system is -extensible and lets you animate properties of custom types as well.</dd> - -<dt><strong><a href="{@docRoot}guide/topics/graphics/view-animation.html">View -Animation</a></strong></dt> -<dd>View Animation is the older system and can only be used for Views. It is relatively easy to -setup and offers enough capabilities to meet many application's needs.</dd> -</dl> - -<dt><strong><a href="{@docRoot}guide/topics/graphics/drawable-animation.html">Drawable -Animation</a></strong></dt> -<dd>Drawable animation involves displaying {@link android.graphics.drawable.Drawable} resources one -after another, like a roll of film. This method of animation is useful if you want to animate -things that are easier to represent with Drawable resources, such as a progression of bitmaps.</dd> diff --git a/docs/html/guide/topics/graphics/index.jd b/docs/html/guide/topics/graphics/index.jd index ab623c2..17f6309 100644 --- a/docs/html/guide/topics/graphics/index.jd +++ b/docs/html/guide/topics/graphics/index.jd @@ -1,51 +1,49 @@ -page.title=Graphics -@jd:body - -<div id="qv-wrapper"> - <div id="qv"> - <h2>Topics</h2> - <ol> - <li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a></li> - <li><a href="{@docRoot}guide/topics/graphics/hardware-accel.html">Hardware Acceleration</a></li> - <li><a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a></li> - </ol> - </div> -</div> - -<p>When writing an application, it's important to consider exactly what your graphical demands will be. -Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations -for a rather static application should be implemented much differently than graphics and animations -for an interactive game. Here, we'll discuss a few of the options you have for drawing graphics -on Android and which tasks they're best suited for. -</p> +page.title=Animation and Graphics +page.landing=true +page.landing.intro=Make your apps look and perform their best using Android's powerful graphics features such as OpenGL, hardware acceleration, and built-in UI animations. +page.landing.image= -<dl> -<dt><strong><a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and -Drawables</a></strong></dt> -<dd>Android provides a set of {@link android.view.View} widgets that provide general functionality -for a wide array of user interfaces. You can also extend these widgets to modify the way they -look or behave. In addition, you can do your own custom 2D rendering using the various drawing -methods contained in the {@link android.graphics.Canvas} class or create {@link -android.graphics.drawable.Drawable} objects for things such as textured buttons or frame-by-frame -animations.</dd> +@jd:body -<dt><strong><a href="{@docRoot}guide/topics/graphics/hardware-accel.html">Hardware -Acceleration</a></strong></dt> -<dd>Beginning in Android 3.0, you can hardware accelerate the majority of -the drawing done by the Canvas APIs to further increase their performance.</dd> +<div class="landing-docs"> -<dt><strong><a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a></strong></dt> -<dd>Android supports OpenGL ES 1.0 and 2.0, with Android framework APIs as well as natively -with the Native Development Kit (NDK). Using the framework APIs is desireable when you want to add a -few graphical enhancements to your application that are not supported with the Canvas APIs, or if -you desire platform independence and don't demand high performance. There is a performance hit in -using the framework APIs compared to the NDK, so for many graphic intensive applications such as -games, using the NDK is beneficial (It is important to note though that you can still get adequate -performance using the framework APIs. For example, the Google Body app is developed entirely -using the framework APIs). OpenGL with the NDK is also useful if you have a lot of native -code that you want to port over to Android. For more information about using the NDK, read the -docs in the <code>docs/</code> directory of the <a href="{@docRoot}sdk/ndk/index.html">NDK -download.</a></dd> -</dl> + <div class="col-6"> + <h3>Blog Articles</h3> + <a +href="http://android-developers.blogspot.com/2011/11/android-40-graphics-and-animations.html"> + <h4>Android 4.0 Graphics and Animations</h4> + <p>Earlier this year, Android 3.0 launched with a new 2D rendering pipeline designed to +support hardware acceleration on tablets. With this new pipeline, all drawing operations performed +by the UI toolkit are carried out using the GPU. You’ll be happy to hear that Android 4.0, Ice Cream +Sandwich, brings an improved version of the hardware-accelerated 2D rendering pipeline.</p> + </a> + + <a +href="http://android-developers.blogspot.com/2011/05/introducing-viewpropertyanimator.html"> + <h4>Introducing ViewPropertyAnimator</h4> + <p>This new animation system makes it easy to animate any kind of property on any object, +including the new properties added to the View class in 3.0. In the 3.1 release, we added a small +utility class that makes animating these properties even easier.</p> + </a> + + <a +href="http://android-developers.blogspot.com/2011/03/android-30-hardware-acceleration.html"> + <h4>Android 3.0 Hardware Acceleration</h4> + <p>Hardware accelerated graphics is nothing new to the Android platform, it has always been +used for windows composition or OpenGL games for instance, but with this new rendering pipeline +applications can benefit from an extra boost in performance.</p> + </a> + </div> + <div class="col-6"> + <h3>Training</h3> + <a href="{@docRoot}training/displaying-bitmaps/index.html"> + <h4>Displaying Bitmaps Efficiently</h4> + <p>This class covers some common techniques for processing and loading Bitmap objects in a way +that keeps your user interface (UI) components responsive and avoids exceeding your application +memory limit.</p> + </a> + + </div> +</div>
\ No newline at end of file diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd index a786d42..a9fedb7 100644 --- a/docs/html/guide/topics/graphics/opengl.jd +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -20,6 +20,7 @@ parent.link=index.html <li><a href="#proj-es1">Projection and camera in ES 2.0</a></li> </ol> </li> + <li><a href="#faces-winding">Shape Faces and Winding</li> <li><a href="#compatibility">OpenGL Versions and Device Compatibility</a> <ol> <li><a href="#textures">Texture compression support</a></li> @@ -33,11 +34,6 @@ parent.link=index.html <li>{@link android.opengl.GLSurfaceView}</li> <li>{@link android.opengl.GLSurfaceView.Renderer}</li> </ol> - <h2>Related tutorials</h2> - <ol> - <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL ES 1.0</a></li> - <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL ES 2.0</a></li> - </ol> <h2>Related samples</h2> <ol> <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceViewActivity.html">GLSurfaceViewActivity</a></li> @@ -48,8 +44,8 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics </ol> <h2>See also</h2> <ol> - <li><a href="{@docRoot}resources/articles/glsurfaceview.html">Introducing -GLSurfaceView</a></li> + <li><a href="{@docRoot}training/graphics/opengl/index.html"> + Displaying Graphics with OpenGL ES</a></li> <li><a href="http://www.khronos.org/opengles/">OpenGL ES</a></li> <li><a href="http://www.khronos.org/opengles/1_X/">OpenGL ES 1.x Specification</a></li> <li><a href="http://www.khronos.org/opengles/2_X/">OpenGL ES 2.x specification</a></li> @@ -73,7 +69,7 @@ OpenGL ES 2.0 API specification.</p> <p>Android supports OpenGL both through its framework API and the Native Development Kit (NDK). This topic focuses on the Android framework interfaces. For more information about the -NDK, see the <a href="{@docRoot}sdk/ndk/index.html">Android NDK</a>. +NDK, see the <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>. <p>There are two foundational classes in the Android framework that let you create and manipulate graphics with the OpenGL ES API: {@link android.opengl.GLSurfaceView} and {@link @@ -389,6 +385,43 @@ objects to be rendered by OpenGL. href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#projection-and-views">OpenGL ES 2.0 tutorial</a>.</p> +<h2 id="faces-winding">Shape Faces and Winding</h2> + +<p>In OpenGL, the face of a shape is a surface defined by three or more points in three-dimensional +space. A set of three or more three-dimensional points (called vertices in OpenGL) have a front face +and a back face. How do you know which face is front and which is the back? Good question. The +answer has to do with winding, or, the direction in which you define the points of a shape.</p> + +<img src="{@docRoot}images/opengl/ccw-winding.png"> +<p class="img-caption"> + <strong>Figure 1.</strong> Illustration of a coordinate list which translates into a +counterclockwise drawing order.</p> + +<p>In this example, the points of the triangle are defined in an order such that they are drawn in a +counterclockwise direction. The order in which these coordinates are drawn defines the winding +direction for the shape. By default, in OpenGL, the face which is drawn counterclockwise is the +front face. The triangle shown in Figure 1 is defined so that you are looking at the front face of +the shape (as interpreted by OpenGL) and the other side is the back face.</p> + +<p>Why is it important to know which face of a shape is the front face? The answer has to do with a +commonly used feature of OpenGL, called face culling. Face culling is an option for the OpenGL +environment which allows the rendering pipeline to ignore (not calculate or draw) the back face of a +shape, saving time, memory and processing cycles:</p> + +<pre> +// enable face culling feature +gl.glEnable(GL10.GL_CULL_FACE); +// specify which faces to not draw +gl.glCullFace(GL10.GL_BACK); +</pre> + +<p>If you try to use the face culling feature without knowing which sides of your shapes are the +front and back, your OpenGL graphics are going to look a bit thin, or possibly not show up at all. +So, always define the coordinates of your OpenGL shapes in a counterclockwise drawing order.</p> + +<p class="note"><strong>Note:</strong> It is possible to set an OpenGL environment to treat the +clockwise face as the front face, but doing so requires more code and is likely to confuse +experienced OpenGL developers when you ask them for help. So don’t do that.</p> <h2 id="compatibility">OpenGL Versions and Device Compatibility</h2> @@ -410,7 +443,8 @@ texture compression, see the <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/CompressedTextureActivity.html" >CompressedTextureActivity</a> code sample.</p> -<p>To check if the ETC1 format is supported on a device, call the {@link +<p>The ETC format is supported by most Android devices, but it not guarranteed to be available. To +check if the ETC1 format is supported on a device, call the {@link android.opengl.ETC1Util#isETC1Supported() ETC1Util.isETC1Supported()} method.</p> <p class="note"><b>Note:</b> The ETC1 texture compression format does not support textures with an diff --git a/docs/html/guide/topics/graphics/overview.jd b/docs/html/guide/topics/graphics/overview.jd new file mode 100644 index 0000000..a53cd3f --- /dev/null +++ b/docs/html/guide/topics/graphics/overview.jd @@ -0,0 +1,73 @@ +page.title=Animation and Graphics Overview +@jd:body + + <p>Android provides a variety of powerful APIs for applying animation to UI elements and drawing custom + 2D and 3D graphics. The sections below provide an overview of the APIs and system capabilities available + and help you decide with approach is best for your needs.</p> + + <h3 id="animation">Animation</h3> + + <p>The Android framework provides two animation systems: property animation + (introduced in Android 3.0) and view animation. Both animation systems are viable options, + but the property animation system, in general, is the preferred method to use, because it + is more flexible and offers more features. In addition to these two systems, you can utilize Drawable + animation, which allows you to load drawable resources and display them one frame after + another.</p> + +<dl> +<dt><strong><a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property +Animation</a></strong></dt> +<dd>Introduced in Android 3.0 (API level 11), the property animation system lets you +animate properties of any object, including ones that are not rendered to the screen. The system is +extensible and lets you animate properties of custom types as well.</dd> + +<dt><strong><a href="{@docRoot}guide/topics/graphics/view-animation.html">View +Animation</a></strong></dt> +<dd>View Animation is the older system and can only be used for Views. It is relatively easy to +setup and offers enough capabilities to meet many application's needs.</dd> +</dl> + +<dt><strong><a href="{@docRoot}guide/topics/graphics/drawable-animation.html">Drawable +Animation</a></strong></dt> +<dd>Drawable animation involves displaying {@link android.graphics.drawable.Drawable} resources one +after another, like a roll of film. This method of animation is useful if you want to animate +things that are easier to represent with Drawable resources, such as a progression of bitmaps.</dd> + +<h3 id="graphics">2D and 3D Graphics</h3> + +<p>When writing an application, it's important to consider exactly what your graphical demands will be. +Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations +for a rather static application should be implemented much differently than graphics and animations +for an interactive game. Here, we'll discuss a few of the options you have for drawing graphics +on Android and which tasks they're best suited for. +</p> + +<dl> +<dt><strong><a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and +Drawables</a></strong></dt> +<dd>Android provides a set of {@link android.view.View} widgets that provide general functionality +for a wide array of user interfaces. You can also extend these widgets to modify the way they +look or behave. In addition, you can do your own custom 2D rendering using the various drawing +methods contained in the {@link android.graphics.Canvas} class or create {@link +android.graphics.drawable.Drawable} objects for things such as textured buttons or frame-by-frame +animations.</dd> + +<dt><strong><a href="{@docRoot}guide/topics/graphics/hardware-accel.html">Hardware +Acceleration</a></strong></dt> +<dd>Beginning in Android 3.0, you can hardware accelerate the majority of +the drawing done by the Canvas APIs to further increase their performance.</dd> + +<dt><strong><a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a></strong></dt> +<dd>Android supports OpenGL ES 1.0 and 2.0, with Android framework APIs as well as natively +with the Native Development Kit (NDK). Using the framework APIs is desireable when you want to add a +few graphical enhancements to your application that are not supported with the Canvas APIs, or if +you desire platform independence and don't demand high performance. There is a performance hit in +using the framework APIs compared to the NDK, so for many graphic intensive applications such as +games, using the NDK is beneficial (It is important to note though that you can still get adequate +performance using the framework APIs. For example, the Google Body app is developed entirely +using the framework APIs). OpenGL with the NDK is also useful if you have a lot of native +code that you want to port over to Android. For more information about using the NDK, read the +docs in the <code>docs/</code> directory of the <a href="{@docRoot}tools/sdk/ndk/index.html">NDK +download.</a></dd> +</dl> + diff --git a/docs/html/guide/topics/graphics/prop-animation.jd b/docs/html/guide/topics/graphics/prop-animation.jd index be24788..b733624 100644 --- a/docs/html/guide/topics/graphics/prop-animation.jd +++ b/docs/html/guide/topics/graphics/prop-animation.jd @@ -166,6 +166,31 @@ parent.link=animation.html "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos</a> sample project provides many examples on how to use the property animation system.</p> + + <h2 id="property-vs-view">How Property Animation Differs from View Animation</h2> + + <p>The view animation system provides the capability to only animate {@link android.view.View} + objects, so if you wanted to animate non-{@link android.view.View} objects, you have to implement + your own code to do so. The view animation system is also constrained in the fact that it only + exposes a few aspects of a {@link android.view.View} object to animate, such as the scaling and + rotation of a View but not the background color, for instance.</p> + + <p>Another disadvantage of the view animation system is that it only modified where the + View was drawn, and not the actual View itself. For instance, if you animated a button to move + across the screen, the button draws correctly, but the actual location where you can click the + button does not change, so you have to implement your own logic to handle this.</p> + + <p>With the property animation system, these constraints are completely removed, and you can animate + any property of any object (Views and non-Views) and the object itself is actually modified. + The property animation system is also more robust in the way it carries out animation. At + a high level, you assign animators to the properties that you want to animate, such as color, + position, or size and can define aspects of the animation such as interpolation and + synchronization of multiple animators.</p> + + <p>The view animation system, however, takes less time to setup and requires less code to write. + If view animation accomplishes everything that you need to do, or if your existing code already + works the way you want, there is no need to use the property animation system. It also might + make sense to use both animation systems for different situations if the use case arises.</p> <h2>API Overview</h2> diff --git a/docs/html/guide/topics/graphics/renderscript/compute.jd b/docs/html/guide/topics/graphics/renderscript/compute.jd new file mode 100644 index 0000000..e827f00 --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/compute.jd @@ -0,0 +1,253 @@ +page.title=Compute +parent.title=Renderscript +parent.link=index.html + +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#creating">Creating a Compute Renderscript</a> + + <ol> + <li><a href="#creating-renderscript">Creating the Renderscript file</a></li> + + <li><a href="#calling">Calling the Renderscript code</a></li> + </ol> + </li> + </ol> + + <h2>Related Samples</h2> + + <ol> + <li><a href="{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">Hello + Compute</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a></li> + </ol> + </div> +</div> + +<p>Renderscript exposes a set of compute APIs that you can use to do intensive computational +operations. You can use the compute APIs in the context of a graphics Renderscript such as +calculating the positions of many objects in a scene. You can also create standalone compute +Renderscripts such as one that does image processing for a photo editor application.</p> + +<p>Compute Renderscripts scale to the amount of +processing cores available on the device. This is enabled through a function named +<code>rsForEach()</code> (or the <code>forEach_root()</code> method at the Android framework level). +that automatically partitions work across available processing cores on the device. +For now, compute Renderscripts can only take advantage of CPU +cores, but in the future, they can potentially run on other types of processors such as GPUs and +DSPs.</p> + +<h2 id="creating-renderscript">Creating a Compute Renderscript</h2> + +<p>Implementing a compute Renderscript creating a <code>.rs</code> file that contains +your Renderscript code and calling it at the Android framework level with the +<code>forEach_root()</code> or at the Renderscript runtime level with the +<code>rsForEach()</code> function. The following diagram describes how a typical compute +Renderscript is set up:</p><img src="{@docRoot}images/rs_compute.png"> + +<p class="img-caption"><strong>Figure 1.</strong> Compute Renderscript overview</p> + +<p>The following sections describe how to create a simple compute Renderscript and use it in an +Android application. This example uses the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute Renderscript +sample</a> that is provided in the SDK as a guide (some code has been modified from its original +form for simplicity).</p> + +<h3 id="creating-renderscript">Creating the Renderscript file</h3> + +<p>Your Renderscript code resides in <code>.rs</code> and <code>.rsh</code> files in the +<code><project_root>/src/</code> directory. This code contains the compute logic +and declares all necessary variables and pointers. +Every compute <code>.rs</code> file generally contains the following items:</p> + +<ul> + <li>A pragma declaration (<code>#pragma rs java_package_name(<em>package.name</em>)</code>) + that declares the package name of the <code>.java</code> reflection of this Renderscript.</li> + + <li>A pragma declaration (<code>#pragma version(1)</code>) that declares the version of + Renderscript that you are using (1 is the only value for now).</li> + + <li>A <code>root()</code> function that is the main worker function. The root function is + called by the <code>rsForEach</code> function, which allows the Renderscript code to be called and + executed on multiple cores if they are available. The <code>root()</code> function must return + <code>void</code> and accept the following arguments: + + <ul> + <li>Pointers to memory allocations that are used for the input and output of the compute + Renderscript. Both of these pointers are required for Android 3.2 (API level 13) platform + versions or older. Android 4.0 (API level 14) and later requires one or both of these + allocations.</li> + </ul> + + <p>The following arguments are optional, but both must be supplied if you choose to use + them:</p> + + <ul> + <li>A pointer for user-defined data that the Renderscript might need to carry out + computations in addition to the necessary allocations. This can be a pointer to a simple + primitive or a more complex struct.</li> + + <li>The size of the user-defined data.</li> + </ul> + </li> + + <li>An optional <code>init()</code> function. This allows you to do any initialization + before the <code>root()</code> function runs, such as initializing variables. This + function runs once and is called automatically when the Renderscript starts, before anything + else in your Renderscript.</li> + + <li>Any variables, pointers, and structures that you wish to use in your Renderscript code (can + be declared in <code>.rsh</code> files if desired)</li> +</ul> + +<p>The following code shows how the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/src/com/example/android/rs/hellocompute/mono.html"> +mono.rs</a> file is implemented:</p> +<pre> +#pragma version(1) +#pragma rs java_package_name(com.example.android.rs.hellocompute) + +//multipliers to convert a RGB colors to black and white +const static float3 gMonoMult = {0.299f, 0.587f, 0.114f}; + +void root(const uchar4 *v_in, uchar4 *v_out) { + //unpack a color to a float4 + float4 f4 = rsUnpackColor8888(*v_in); + //take the dot product of the color and the multiplier + float3 mono = dot(f4.rgb, gMonoMult); + //repack the float to a color + *v_out = rsPackColorTo8888(mono); +} +</pre> + +<h3 id="calling">Calling the Renderscript code</h3> + +<p>You can do Renderscript to Renderscript calls with <code>rsForEach</code> in situations +such as when a graphics Renderscript needs to do a lot of computational operations. The Renderscript +<a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a> sample shows how +this is setup. The <a href= +"resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">balls.rs</a> +graphics Renderscript calls the <a href= +"resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">balls_physics.rs</a> +compute Renderscript to calculate the location of the balls that are rendered to the screen.</p> + +<p>Another way to use a compute Renderscript is to call it from your Android framework code by +creating a Renderscript object by instantiating the (<code>ScriptC_<em>script_name</em></code>) +class. This class contains a method, <code>forEach_root()</code>, that lets you invoke +<code>rsForEach</code>. You give it the same parameters that you would if you were invoking it +at the Renderscript runtime level. This technique allows your Android application to offload +intensive mathematical calculations to Renderscript. See the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute</a> sample to see +how a simple Android application can utilize a compute Renderscript.</p> + +<p>To call a compute Renderscript at the Android framework level:</p> + +<ol> + <li>Allocate memory that is needed by the compute Renderscript in your Android framework code. + You need an input and output {@link android.renderscript.Allocation} for Android 3.2 (API level + 13) platform versions and older. The Android 4.0 (API level 14) platform version requires only + one or both {@link android.renderscript.Allocation}s.</li> + + <li>Create an instance of the <code>ScriptC_<em>script_name</em></code> class.</li> + + <li>Call <code>forEach_root()</code>, passing in the allocations, the + Renderscript, and any optional user-defined data. The output allocation will contain the output + of the compute Renderscript.</li> +</ol> + +<p>In the following example, taken from the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute</a> sample, processes +a bitmap and outputs a black and white version of it. The +<code>createScript()</code> method carries out the steps described previously. This method the compute +Renderscript, <code>mono.rs</code>, passing in memory allocations that store the bitmap to be processed +as well as the eventual output bitmap. It then displays the processed bitmap onto the screen:</p> +<pre> +package com.example.android.rs.hellocompute; + +import android.app.Activity; +import android.os.Bundle; +import android.graphics.BitmapFactory; +import android.graphics.Bitmap; +import android.renderscript.RenderScript; +import android.renderscript.Allocation; +import android.widget.ImageView; + +public class HelloCompute extends Activity { + private Bitmap mBitmapIn; + private Bitmap mBitmapOut; + + private RenderScript mRS; + private Allocation mInAllocation; + private Allocation mOutAllocation; + private ScriptC_mono mScript; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + mBitmapIn = loadBitmap(R.drawable.data); + mBitmapOut = Bitmap.createBitmap(mBitmapIn.getWidth(), mBitmapIn.getHeight(), + mBitmapIn.getConfig()); + + ImageView in = (ImageView) findViewById(R.id.displayin); + in.setImageBitmap(mBitmapIn); + + ImageView out = (ImageView) findViewById(R.id.displayout); + out.setImageBitmap(mBitmapOut); + + createScript(); + } + private void createScript() { + mRS = RenderScript.create(this); + mInAllocation = Allocation.createFromBitmap(mRS, mBitmapIn, + Allocation.MipmapControl.MIPMAP_NONE, + Allocation.USAGE_SCRIPT); + mOutAllocation = Allocation.createTyped(mRS, mInAllocation.getType()); + mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono); + mScript.forEach_root(mInAllocation, mOutAllocation); + mOutAllocation.copyTo(mBitmapOut); + } + + private Bitmap loadBitmap(int resource) { + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPreferredConfig = Bitmap.Config.ARGB_8888; + return BitmapFactory.decodeResource(getResources(), resource, options); + } +} +</pre> + +<p>To call a compute Renderscript from another Renderscript file:</p> +<ol> + <li>Allocate memory that is needed by the compute Renderscript in your Android framework code. + You need an input and output {@link android.renderscript.Allocation} for Android 3.2 (API level + 13) platform versions and older. The Android 4.0 (API level 14) platform version requires only + one or both {@link android.renderscript.Allocation}s.</li> + + <li>Call <code>rsForEach()</code>, passing in the allocations and any optional user-defined data. + The output allocation will contain the output of the compute Renderscript.</li> +</ol> +<p>The following example, taken from the <a href= +"{@docRoot}resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">Renderscript +Balls sample</a>, demonstrates how to do make a script to script call:</p> +<pre> +rs_script script; +rs_allocation in_allocation; +rs_allocation out_allocation; +UserData_t data; +... +rsForEach(script, in_allocation, out_allocation, &data, sizeof(data)); +</pre> + +<p>In this example, assume that the script and memory allocations have already been +allocated and bound at the Android framework level and that <code>UserData_t</code> is a struct +declared previously. Passing a pointer to a struct and the size of the struct to <code>rsForEach</code> +is optional, but useful if your compute Renderscript requires additional information other than +the necessary memory allocations.</p> diff --git a/docs/html/guide/topics/graphics/renderscript/graphics.jd b/docs/html/guide/topics/graphics/renderscript/graphics.jd new file mode 100644 index 0000000..58676ea --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/graphics.jd @@ -0,0 +1,994 @@ +page.title=Graphics +parent.title=Renderscript +parent.link=index.html + +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#creating-graphics-rs">Creating a Graphics Renderscript</a> + <ol> + <li><a href="#creating-native">Creating the Renderscript file</a></li> + <li><a href="#creating-entry">Creating the Renderscript entry point class</a></li> + <li><a href="#creating-view">Creating the view class</a></li> + <li><a href="#creating-activity">Creating the activity class</a></li> + </ol> + </li> + <li> + <a href="#drawing">Drawing</a> + <ol> + <li><a href="#drawing-rsg">Simple drawing</a></li> + <li><a href="#drawing-mesh">Drawing with a mesh</a></li> + </ol> + </li> + <li> + <a href="#shaders">Shaders</a> + <ol> + <li><a href="#shader-bindings">Shader bindings</a></li> + <li><a href="#shader-sampler">Defining a sampler</a></li> + </ol> + </li> + <li> + <a href="#fbo">Rendering to a Framebuffer Object</a> + </li> + </ol> + + <h2>Related Samples</h2> + + <ol> + <li><a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/FountainFbo/index.html">FountainFbo</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/HelloWorld/index.html">Hello +World</a></li> + + <li><a +href="{@docRoot}resources/samples/RenderScript/MiscSamples/index.html">Misc Samples</a></li> + </ol> + </div> + </div> + + <p>Renderscript provides a number of graphics APIs for rendering, both at the Android + framework level as well as at the Renderscript runtime level. For instance, the Android framework APIs let you + create meshes and define shaders to customize the graphical rendering pipeline. The native + Renderscript graphics APIs let you draw the actual meshes to render your scene. You need to + be familiar with both APIs to appropriately render graphics on an Android-powered device.</p> + + <h2 id="creating-graphics-rs">Creating a Graphics Renderscript</h2> + + <p>Renderscript applications require various layers of code, so it is useful to create the following + files to help keep your application organized:</p> + + <dl> + <dt>The Renderscript <code>.rs</code> file</dt> + + <dd>This file contains the logic to do the graphics rendering.</dd> + + <dt>The Renderscript entry point <code>.java</code> class</dt> + + <dd>This class allows the view class to interact with the code defined in the <code>.rs</code> + file. This class contains a Renderscript object (instance of + <code>ScriptC_<em>renderscript_file</em></code>), which allows your Android framework code to + call the Renderscript code. In general, this class does much of the setup for Renderscript + such as shader and mesh building and memory allocation and binding. The SDK samples follow the + convention of naming this file ActivityRS.java, + where Activity is the name of your main activity class.</dd> + + <dt>The view <code>.java</code> class</dt> + + <dd>This class extends {@link android.renderscript.RSSurfaceView} or {@link + android.renderscript.RSTextureView} to provide a surface to render on. A {@link + android.renderscript.RSSurfaceView} consumes a whole window, but a {@link + android.renderscript.RSTextureView} allows you to draw Renderscript graphics inside of a + view and add it to a {@link android.view.ViewGroup} alongside + other views. In this class, you create a {@link android.renderscript.RenderScriptGL} context object + with a call to {@link android.renderscript.RSSurfaceView#createRenderScriptGL + RSSurfaceView.createRenderscriptGL()} or {@link android.renderscript.RSTextureView#createRenderScriptGL + RSTextureView.createRenderscriptGL()}. The {@link android.renderscript.RenderScriptGL} context object + contains information about the current rendering state of Renderscript such as the vertex and + fragment shaders. You pass this context object to the Renderscript entry point class, so that + class can modify the rendering context if needed and bind the Renderscript code to the context. Once bound, + the view class can use the Renderscript code to display graphics. + The view class should also implement callbacks for events inherited from {@link + android.view.View}, such as {@link android.view.View#onTouchEvent onTouchEvent()} and {@link + android.view.View#onKeyDown onKeyDown()} if you want to detect these types of user interactions. + The SDK samples follow the convention of naming this file ActivityView.java, + where Activity is the name of your main activity class</dd> + + <dt>The activity <code>.java</code> class</dt> + + <dd>This class is the main activity class and sets your {@link android.renderscript.RSSurfaceView} as the main content + view for this activity or uses the {@link android.renderscript.RSTextureView} alongside other views.</dd> + </dl> + <p>Figure 1 describes how these classes interact with one another in a graphics Renderscript:</p> + + <img src="{@docRoot}images/rs_graphics.png"> + <p class="img-caption"><strong>Figure 1.</strong> Graphics Renderscript overview</p> + + + <p>The following sections describe how to create an application that uses a graphics Renderscript by using + the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Renderscript Fountain + sample</a> that is provided in the SDK as a guide (some code has been modified from its original + form for simplicity).</p> + + <h3 id="creating-native">Creating the Renderscript file</h3> + + <p>Your Renderscript code resides in <code>.rs</code> and <code>.rsh</code> (headers) files in the + <code><project_root>/src/</code> directory. This code contains the logic to render your + graphics and declares all other necessary items such as variables, structs, + and pointers. Every graphics <code>.rs</code> file generally contains the following items:</p> + + <ul> + <li>A pragma declaration (<code>#pragma rs java_package_name(<em>package.name</em>)</code>) that declares + the package name of the <code>.java</code> reflection of this Renderscript.</li> + + <li>A pragma declaration (<code>#pragma version(1)</code>) that declares the version of Renderscript that + you are using (1 is the only value for now).</li> + + <li>A <code>#include "rs_graphics.rsh"</code> declaration.</li> + + <li>A <code>root()</code> function. This is the main worker function for your Renderscript and + calls Renderscript graphics functions to render scenes. This function is called every time a + frame refresh occurs, which is specified as its return value. A <code>0</code> (zero) specified for + the return value says to only render the frame when a property of the scene that you are + rendering changes. A non-zero positive integer specifies the refresh rate of the frame in + milliseconds. + + <p class="note"><strong>Note:</strong> The Renderscript runtime makes its best effort to + refresh the frame at the specified rate. For example, if you are creating a live wallpaper + and set the return value to 20, the Renderscript runtime renders the wallpaper at 50fps if it has just + enough or more resources to do so. It renders as fast as it can if not enough resources + are available.</p> + + <p>For more information on using the Renderscript graphics functions, see the <a href= + "#drawing">Drawing</a> section.</p> + </li> + + <li>An <code>init()</code> function. This allows you to do initialization of your + Renderscript before the <code>root()</code> function runs, such as assigning values to variables. This + function runs once and is called automatically when the Renderscript starts, before anything + else in your Renderscript. Creating this function is optional.</li> + + <li>Any variables, pointers, and structures that you wish to use in your Renderscript code (can + be declared in <code>.rsh</code> files if desired)</li> + </ul> + + <p>The following code shows how the <code>fountain.rs</code> file is implemented:</p> + <pre> +#pragma version(1) + +// Tell which java package name the reflected files should belong to +#pragma rs java_package_name(com.example.android.rs.fountain) + +//declare shader binding +#pragma stateFragment(parent) + +// header with graphics APIs, must include explicitly +#include "rs_graphics.rsh" + +static int newPart = 0; + +// the mesh to render +rs_mesh partMesh; + +// the point representing where a particle is rendered +typedef struct __attribute__((packed, aligned(4))) Point { + float2 delta; + float2 position; + uchar4 color; +} Point_t; +Point_t *point; + +// main worker function that renders particles onto the screen +int root() { + float dt = min(rsGetDt(), 0.1f); + rsgClearColor(0.f, 0.f, 0.f, 1.f); + const float height = rsgGetHeight(); + const int size = rsAllocationGetDimX(rsGetAllocation(point)); + float dy2 = dt * (10.f); + Point_t * p = point; + for (int ct=0; ct < size; ct++) { + p->delta.y += dy2; + p->position += p->delta; + if ((p->position.y > height) && (p->delta.y > 0)) { + p->delta.y *= -0.3f; + } + p++; + } + + rsgDrawMesh(partMesh); + return 1; +} + +// adds particles to the screen to render +static float4 partColor[10]; +void addParticles(int rate, float x, float y, int index, bool newColor) +{ + if (newColor) { + partColor[index].x = rsRand(0.5f, 1.0f); + partColor[index].y = rsRand(1.0f); + partColor[index].z = rsRand(1.0f); + } + float rMax = ((float)rate) * 0.02f; + int size = rsAllocationGetDimX(rsGetAllocation(point)); + uchar4 c = rsPackColorTo8888(partColor[index]); + + Point_t * np = &point[newPart]; + float2 p = {x, y}; + while (rate--) { + float angle = rsRand(3.14f * 2.f); + float len = rsRand(rMax); + np->delta.x = len * sin(angle); + np->delta.y = len * cos(angle); + np->position = p; + np->color = c; + newPart++; + np++; + if (newPart >= size) { + newPart = 0; + np = &point[newPart]; + } + } +} +</pre> + + <h3 id="creating-entry">Creating the Renderscript entry point class</h3> + + <p>When you create a Renderscript (<code>.rs</code>) file, it is helpful to create a + corresponding Android framework class that is an entry point into the <code>.rs</code> file. + The most important thing this class does is receive a {@link android.renderscript.RenderScriptGL} rendering context + object from the <a href="#creating-view">view class</a> and binds the actual Renderscript + code to the rendering context. This notifies your view class of the code that it needs + to render graphics. + </p> + + <p>In addition, this class should contain all of the things needed to set up Renderscript. + Some important things that you need to do in this class are:</p> + + <ul> + <li>Create a Renderscript object + <code>ScriptC_<em>rs_filename</em></code>. The Renderscript object is attached to the Renderscript bytecode, which is platform-independent and + gets compiled on the device when the Renderscript application runs. The bytecode is referenced + as a raw resource and is passed into the constructor for the Renderscript object. + For example, this is how the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a> + sample creates the Renderscript object: + <pre> + RenderScriptGL rs; //obtained from the view class + Resources res; //obtained from the view class + ... + ScriptC_fountain mScript = new ScriptC_fountain(mRS, mRes, R.raw.fountain); + </pre> + </li> + <li>Allocate any necessary memory and bind it to your Renderscript code via the Renderscript object.</li> + <li>Build any necessary meshes and bind them to the Renderscript code via the Renderscript object.</li> + <li>Create any necessary programs and bind them to the Renderscript code via the Renderscript object.</li> + </ul> + + <p>The following code shows how the <a href= + "{@docRoot}resources/samples/RenderScript/Fountain/src/com/example/android/rs/fountain/FountainRS.html"> + FountainRS</a> class is implemented:</p> + <pre> +package com.example.android.rs.fountain; + +import android.content.res.Resources; +import android.renderscript.*; +import android.util.Log; + +public class FountainRS { + public static final int PART_COUNT = 50000; + + public FountainRS() { + } + + /** + * This provides us with the Renderscript context and resources + * that allow us to create the Renderscript object + */ + private Resources mRes; + private RenderScriptGL mRS; + + // Renderscript object + private ScriptC_fountain mScript; + + // Called by the view class to initialize the Renderscript context and renderer + public void init(RenderScriptGL rs, Resources res) { + mRS = rs; + mRes = res; + + /** + * Create a shader and bind to the Renderscript context + */ + ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs); + pfb.setVaryingColor(true); + rs.bindProgramFragment(pfb.create()); + + /** + * Allocate memory for the particles to render and create the mesh to draw + */ + ScriptField_Point points = new ScriptField_Point(mRS, PART_COUNT); + Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS); + smb.addVertexAllocation(points.getAllocation()); + smb.addIndexSetType(Mesh.Primitive.POINT); + Mesh sm = smb.create(); + + /** + * Create and bind the Renderscript object to the Renderscript context + */ + mScript = new ScriptC_fountain(mRS, mRes, R.raw.fountain); + mScript.set_partMesh(sm); + mScript.bind_point(points); + mRS.bindRootScript(mScript); + } + + boolean holdingColor[] = new boolean[10]; + + /** + * Calls Renderscript functions (invoke_addParticles) + * via the Renderscript object to add particles to render + * based on where a user touches the screen. + */ + public void newTouchPosition(float x, float y, float pressure, int id) { + if (id >= holdingColor.length) { + return; + } + int rate = (int)(pressure * pressure * 500.f); + if (rate > 500) { + rate = 500; + } + if (rate > 0) { + mScript.invoke_addParticles(rate, x, y, id, !holdingColor[id]); + holdingColor[id] = true; + } else { + holdingColor[id] = false; + } + + } +} +</pre> + + + <h3 id="creating-view">Creating the view class</h3> + + + <p>To display graphics, you need a view to render on. Create a class that extends {@link + android.renderscript.RSSurfaceView} or {@link android.renderscript.RSTextureView}. This class + allows you to create a {@link android.renderscript.RenderScriptGL} context object by calling and + pass it to the Rendscript entry point class to bind the two. Once bound, the content is aware + of the code that it needs to use to render graphics with. If your Renderscript code + depends on any type of information that the view is aware of, such as touches from the user, + you can also use this class to relay that information to the Renderscript entry point class. + The following code shows how the <code>FountainView</code> class is implemented:</p> + <pre> +package com.example.android.rs.fountain; + +import android.renderscript.RSTextureView; +import android.renderscript.RenderScriptGL; +import android.content.Context; +import android.view.MotionEvent; + +public class FountainView extends RSTextureView { + + public FountainView(Context context) { + super(context); + } + // Renderscript context + private RenderScriptGL mRS; + // Renderscript entry point object that calls Renderscript code + private FountainRS mRender; + + /** + * Create Renderscript context and initialize Renderscript entry point + */ + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + android.util.Log.e("rs", "onAttachedToWindow"); + if (mRS == null) { + RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig(); + mRS = createRenderScriptGL(sc); + mRender = new FountainRS(); + mRender.init(mRS, getResources()); + } + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + android.util.Log.e("rs", "onDetachedFromWindow"); + if (mRS != null) { + mRS = null; + destroyRenderScriptGL(); + } + } + + + /** + * Use callbacks to relay data to Renderscript entry point class + */ + @Override + public boolean onTouchEvent(MotionEvent ev) + { + int act = ev.getActionMasked(); + if (act == ev.ACTION_UP) { + mRender.newTouchPosition(0, 0, 0, ev.getPointerId(0)); + return false; + } else if (act == MotionEvent.ACTION_POINTER_UP) { + // only one pointer going up, we can get the index like this + int pointerIndex = ev.getActionIndex(); + int pointerId = ev.getPointerId(pointerIndex); + mRender.newTouchPosition(0, 0, 0, pointerId); + } + int count = ev.getHistorySize(); + int pcount = ev.getPointerCount(); + + for (int p=0; p < pcount; p++) { + int id = ev.getPointerId(p); + mRender.newTouchPosition(ev.getX(p), + ev.getY(p), + ev.getPressure(p), + id); + + for (int i=0; i < count; i++) { + mRender.newTouchPosition(ev.getHistoricalX(p, i), + ev.getHistoricalY(p, i), + ev.getHistoricalPressure(p, i), + id); + } + } + return true; + } +} +</pre> + + <h3 id="creating-activity">Creating the activity class</h3> + + <p>Applications that use Renderscript still behave like normal Android applications, so you + need an activity class that handles activity lifecycle callback events appropriately. The activity class + also sets your {@link android.renderscript.RSSurfaceView} view class to be the main content view of the + activity or uses your {@link android.renderscript.RSTextureView} + in a {@link android.view.ViewGroup} alongside other views.</p> + + <p>The following code shows how the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a> + sample declares its activity class:</p> + <pre> +package com.example.android.rs.fountain; + +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; + +public class Fountain extends Activity { + + private static final String LOG_TAG = "libRS_jni"; + private static final boolean DEBUG = false; + private static final boolean LOG_ENABLED = false; + + private FountainView mView; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // Create our Preview view and set it as + // the content of our activity + mView = new FountainView(this); + setContentView(mView); + } + + @Override + protected void onResume() { + Log.e("rs", "onResume"); + + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onResume(); + mView.resume(); + } + + @Override + protected void onPause() { + Log.e("rs", "onPause"); + + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onPause(); + mView.pause(); + + } + + static void log(String message) { + if (LOG_ENABLED) { + Log.v(LOG_TAG, message); + } + } +} +</pre> + +<p>Now that you have an idea of what is involved in a Renderscript graphics application, you can +start building your own. It might be easiest to begin with one of the +<a href="{@docRoot}resources/samples/RenderScript/index.html">Renderscript samples</a> as a starting +point if this is your first time using Renderscript.</p> + + <h2 id="drawing">Drawing</h2> + <p>The following sections describe how to use the graphics functions to draw with Renderscript.</p> + + <h3 id="drawing-rsg">Simple drawing</h3> + + <p>The native Renderscript APIs provide a few convenient functions to easily draw a polygon or text to + the screen. You call these in your <code>root()</code> function to have them render to the {@link + android.renderscript.RSSurfaceView} or {@link android.renderscript.RSTextureView}. These functions are + available for simple drawing and should not be used for complex graphics rendering:</p> + + <ul> + <li><code>rsgDrawRect()</code>: Sets up a mesh and draws a rectangle to the screen. It uses the + top left vertex and bottom right vertex of the rectangle to draw.</li> + + <li><code>rsgDrawQuad()</code>: Sets up a mesh and draws a quadrilateral to the screen.</li> + + <li><code>rsgDrawQuadTexCoords()</code>: Sets up a mesh and draws a quadrilateral to the screen + using the provided coordinates of a texture.</li> + + <li><code>rsgDrawText()</code>: Draws specified text to the screen. Use <code>rsgFontColor()</code> + to set the color of the text.</li> + </ul> + + <h3 id="drawing-mesh">Drawing with a mesh</h3> + + <p>When you want to render complex scenes to the screen, instantiate a {@link + android.renderscript.Mesh} and draw it with <code>rsgDrawMesh()</code>. A {@link + android.renderscript.Mesh} is a collection of allocations that represent vertex data (positions, + normals, texture coordinates) and index data that provides information on how to draw triangles + and lines with the provided vertex data. You can build a Mesh in three different ways:</p> + + <ul> + <li>Build the mesh with the {@link android.renderscript.Mesh.TriangleMeshBuilder} class, which + allows you to specify a set of vertices and indices for each triangle that you want to draw.</li> + + <li>Build the mesh using an {@link android.renderscript.Allocation} or a set of {@link + android.renderscript.Allocation}s with the {@link android.renderscript.Mesh.AllocationBuilder} + class. This approach allows you to build a mesh with vertices already stored in memory, which allows you + to specify the vertices in Renderscript or Android framework code.</li> + + <li>Build the mesh with the {@link android.renderscript.Mesh.Builder} class. You should use + this convenience method when you know the data types you want to use to build your mesh, but + don't want to make separate memory allocations like with {@link + android.renderscript.Mesh.AllocationBuilder}. You can specify the types that you want and this + mesh builder automatically creates the memory allocations for you.</li> + </ul> + + <p>To create a mesh using the {@link android.renderscript.Mesh.TriangleMeshBuilder}, you need to + supply it with a set of vertices and the indices for the vertices that comprise the triangle. For + example, the following code specifies three vertices, which are added to an internal array, + indexed in the order they were added. The call to {@link + android.renderscript.Mesh.TriangleMeshBuilder#addTriangle addTriangle()} draws the triangle with + vertex 0, 1, and 2 (the vertices are drawn counter-clockwise).</p> + <pre> +int float2VtxSize = 2; +Mesh.TriangleMeshBuilder triangles = new Mesh.TriangleMeshBuilder(renderscriptGL, +float2VtxSize, Mesh.TriangleMeshBuilder.COLOR); +triangles.addVertex(300.f, 300.f); +triangles.addVertex(150.f, 450.f); +triangles.addVertex(450.f, 450.f); +triangles.addTriangle(0 , 1, 2); +Mesh smP = triangle.create(true); +script.set_mesh(smP); +</pre> + + <p>To draw a mesh using the {@link android.renderscript.Mesh.AllocationBuilder}, you need to + supply it with one or more allocations that contain the vertex data:</p> + <pre> +Allocation vertices; + +... +Mesh.AllocationBuilder triangle = new Mesh.AllocationBuilder(mRS); +smb.addVertexAllocation(vertices.getAllocation()); +smb.addIndexSetType(Mesh.Primitive.TRIANGLE); +Mesh smP = smb.create(); +script.set_mesh(smP); +</pre> + + <p>In your Renderscript code, draw the built mesh to the screen:</p> + <pre> +rs_mesh mesh; +... + +int root(){ +... +rsgDrawMesh(mesh); +... +return 0; //specify a non zero, positive integer to specify the frame refresh. + //0 refreshes the frame only when the mesh changes. +} +</pre> + + <h2 id="shader">Programs</h2> + + <p>You can attach four program objects to the {@link android.renderscript.RenderScriptGL} context + to customize the rendering pipeline. For example, you can create vertex and fragment shaders in + GLSL or build a raster program object that controls culling. The four programs mirror a + traditional graphical rendering pipeline:</p> + + <table> + <tr> + <th>Android Object Type</th> + + <th>Renderscript Native Type</th> + + <th>Description</th> + </tr> + + <tr> + <td>{@link android.renderscript.ProgramVertex}</td> + + <td>rs_program_vertex</td> + + <td> + <p>The Renderscript vertex program, also known as a vertex shader, describes the stage in + the graphics pipeline responsible for manipulating geometric data in a user-defined way. + The object is constructed by providing Renderscript with the following data:</p> + + <ul> + <li>An {@link android.renderscript.Element} describing its varying inputs or attributes</li> + + <li>GLSL shader string that defines the body of the program</li> + + <li>a {@link android.renderscript.Type} that describes the layout of an + Allocation containing constant or uniform inputs</li> + </ul> + + <p>Once the program is created, bind it to the {@link android.renderscript.RenderScriptGL} + graphics context by calling {@link android.renderscript.RenderScriptGL#bindProgramVertex + bindProgramVertex()}. It is then used for all subsequent draw calls until you bind a new + program. If the program has constant inputs, the user needs to bind an allocation + containing those inputs. The allocation's type must match the one provided during creation. + </p> + + <p>The Renderscript runtime then does all the necessary plumbing to send those constants to + the graphics hardware. Varying inputs to the shader, such as position, normal, and texture + coordinates are matched by name between the input {@link android.renderscript.Element} + and the mesh object that is being drawn. The signatures don't have to be exact or in any + strict order. As long as the input name in the shader matches a channel name and size + available on the mesh, the Renderscript runtime handles connecting the two. Unlike OpenGL + there is no need to link the vertex and fragment programs.</p> + + <p>To bind shader constants to the program, declare a <code>struct</code> that contains the necessary + shader constants in your Renderscript code. This <code>struct</code> is generated into a + reflected class that you can use as a constant input element during the program's creation. + It is an easy way to create an instance of this <code>struct</code> as an allocation. You would then + bind this {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the <code>struct</code> to the hardware + when necessary. To update shader constants, you change the values in the + {@link android.renderscript.Allocation} and notify the Renderscript + code of the change.</p> + + <p>The {@link android.renderscript.ProgramVertexFixedFunction.Builder} class also + lets you build a simple vertex shader without writing GLSL code. + </p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.ProgramFragment}</td> + + <td>rs_program_fragment</td> + + <td> + <p>The Renderscript fragment program, also known as a fragment shader, is responsible for + manipulating pixel data in a user-defined way. It's constructed from a GLSL shader string + containing the program body, texture inputs, and a {@link android.renderscript.Type} + object that describes the constants + used by the program. Like the vertex programs, when an {@link android.renderscript.Allocation} + with constant input + values is bound to the shader, its values are sent to the graphics program automatically. + Note that the values inside the {@link android.renderscript.Allocation} are not explicitly tracked. + If they change between two draw calls using the same program object, notify the runtime of that change by + calling <code>rsgAllocationSyncAll()</code>, so it can send the new values to hardware. Communication + between the vertex and fragment programs is handled internally in the GLSL code. For + example, if the fragment program is expecting a varying input called <code>varTex0</code>, the GLSL code + inside the program vertex must provide it.</p> + + <p>To bind shader constructs to the program, declare a <code>struct</code> that contains the necessary + shader constants in your Renderscript code. This <code>struct</code> is generated into a + reflected class that you can use as a constant input element during the program's creation. + It is an easy way to create an instance of this <code>struct</code> as an allocation. You would then + bind this {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the <code>struct</code> to the hardware + when necessary. To update shader constants, you change the values in the + {@link android.renderscript.Allocation} and notify the Renderscript + code of the change.</p> + + <p>The {@link android.renderscript.ProgramFragmentFixedFunction.Builder} class also + lets you build a simple fragment shader without writing GLSL code. + </p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.ProgramStore}</td> + + <td>rs_program_store</td> + + <td>The Renderscript store program contains a set of parameters that control how the graphics + hardware writes to the framebuffer. It could be used to enable and disable depth writes and + testing, setup various blending modes for effects like transparency and define write masks + for color components.</td> + </tr> + + <tr> + <td>{@link android.renderscript.ProgramRaster}</td> + + <td>rs_program_raster</td> + + <td>The Renderscript raster program is primarily used to specify whether point sprites are enabled and to + control the culling mode. By default back faces are culled.</td> + </tr> + </table> + + <p>The following example defines a vertex shader in GLSL and binds it to a Renderscript context object:</p> + <pre> + private RenderScriptGL glRenderer; //rendering context + private ScriptField_Point mPoints; //vertices + private ScriptField_VpConsts mVpConsts; //shader constants + + ... + + ProgramVertex.Builder sb = new ProgramVertex.Builder(glRenderer); + String t = "varying vec4 varColor;\n" + + "void main() {\n" + + " vec4 pos = vec4(0.0, 0.0, 0.0, 1.0);\n" + + " pos.xy = ATTRIB_position;\n" + + " gl_Position = UNI_MVP * pos;\n" + + " varColor = vec4(1.0, 1.0, 1.0, 1.0);\n" + + " gl_PointSize = ATTRIB_size;\n" + + "}\n"; + sb.setShader(t); + sb.addConstant(mVpConsts.getType()); + sb.addInput(mPoints.getElement()); + ProgramVertex pvs = sb.create(); + pvs.bindConstants(mVpConsts.getAllocation(), 0); + glRenderer.bindProgramVertex(pvs); +</pre> + + + <p>The <a href= + "{@docRoot}resources/samples/RenderScript/MiscSamples/src/com/example/android/rs/miscsamples/RsRenderStatesRS.html"> + RsRenderStatesRS</a> sample has many examples on how to create a shader without writing GLSL.</p> + + <h3 id="shader-bindings">Program bindings</h3> + + <p>You can also declare four pragmas that control default program bindings to the {@link + android.renderscript.RenderScriptGL} context when the script is executing:</p> + + <ul> + <li><code>stateVertex</code></li> + + <li><code>stateFragment</code></li> + + <li><code>stateRaster</code></li> + + <li><code>stateStore</code></li> + </ul> + + <p>The possible values for each pragma are <code>parent</code> or <code>default</code>. Using + <code>default</code> binds the shaders to the graphical context with the system defaults.</p> + + <p>Using <code>parent</code> binds the shaders in the same manner as it is bound in the calling + script. If this is the root script, the parent state is taken from the bind points that are set + by the {@link android.renderscript.RenderScriptGL} bind methods.</p> + + <p>For example, you can define this at the top of your graphics Renderscript code to have + the vertex and store programs inherent the bind properties from their parent scripts:</p> + <pre> +#pragma stateVertex(parent) +#pragma stateStore(parent) +</pre> + + <h3 id="shader-sampler">Defining a sampler</h3> + + <p>A {@link android.renderscript.Sampler} object defines how data is extracted from textures. + Samplers are bound to a {@link android.renderscript.ProgramFragment} alongside the texture + whose sampling they control. These + objects are used to specify such things as edge clamping behavior, whether mip-maps are used, and + the amount of anisotropy required. There might be situations where hardware does not support the + desired behavior of the sampler. In these cases, the Renderscript runtime attempts to provide the + closest possible approximation. For example, the user requested 16x anisotropy, but only 8x was + set because it's the best available on the hardware.</p> + + <p>The <a href= + "{@docRoot}resources/samples/RenderScript/MiscSamples/src/com/example/android/rs/miscsamples/RsRenderStatesRS.html"> + RsRenderStatesRS</a> sample has many examples on how to create a sampler and bind it to a + Fragment program.</p> + + + +<h2 id="fbo">Rendering to a Framebuffer Object</h2> + +<p>Framebuffer objects allow you to render offscreen instead of in the default onscreen +framebuffer. This approach might be useful for situations where you need to post-process a texture before +rendering it to the screen, or when you want to composite two scenes in one such as rendering a rear-view +mirror of a car. There are two buffers associated with a framebuffer object: a color buffer +and a depth buffer. The color buffer (required) contains the actual pixel data of the scene +that you are rendering, and the depth buffer (optional) contains the values necessary to figure +out what vertices are drawn depending on their z-values.</p> + +<p>In general, you need to do the following to render to a framebuffer object:</p> + +<ul> + <li>Create {@link android.renderscript.Allocation} objects for the color buffer and + depth buffer (if needed). Specify the {@link + android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} usage attribute for these + allocations to notify the Renderscript runtime to use these allocations for the framebuffer + object. For the color buffer allocation, you most likely need to declare the {@link + android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE} usage attribute + to use the color buffer as a texture, which is the most common use of the framebuffer object.</li> + + <li>Tell the Renderscript runtime to render to the framebuffer object instead of the default + framebuffer by calling <code>rsgBindColorTarget()</code> and passing it the color buffer + allocation. If applicable, call <code>rsgBindDepthTarget()</code> passing in the depth buffer + allocation as well.</li> + + <li>Render your scene normally with the <code>rsgDraw</code> functions. The scene will be + rendered into the color buffer instead of the default onscreen framebuffer.</li> + + <li>When done, tell the Renderscript runtime stop rendering to the color buffer and back + to the default framebuffer by calling <code>rsgClearAllRenderTargets()</code>.</li> + + <li>Create a fragment shader and bind a the color buffer to it as a texture.</li> + + <li>Render your scene to the default framebuffer. The texture will be used according + to the way you setup your fragment shader.</li> +</ul> + +<p>The following example shows you how to render to a framebuffer object by modifying the +<a href="{@docRoot}guide/resources/renderscript/Fountain/">Fountain</a> Renderscript sample. The end +result is the <a href="{@docRoot}guide/resources/renderscript/FountainFBO/">FountainFBO</a> sample. +The modifications render the exact same scene into a framebuffer object as it does the default +framebuffer. The framebuffer object is then rendered into the default framebuffer in a small +area at the top left corner of the screen.</p> + +<ol> + <li>Modify <code>fountain.rs</code> and add the following global variables. This creates setter + methods when this file is reflected into a <code>.java</code> file, allowing you to allocate + memory in your Android framework code and binding it to the Renderscript runtime. +<pre> +//allocation for color buffer +rs_allocation gColorBuffer; +//fragment shader for rendering without a texture (used for rendering to framebuffer object) +rs_program_fragment gProgramFragment; +//fragment shader for rendering with a texture (used for rendering to default framebuffer) +rs_program_fragment gTextureProgramFragment; +</pre> + </li> + + <li>Modify the root function of <code>fountain.rs</code> to look like the following code. The + modifications are commented: +<pre> +int root() { + float dt = min(rsGetDt(), 0.1f); + rsgClearColor(0.f, 0.f, 0.f, 1.f); + const float height = rsgGetHeight(); + const int size = rsAllocationGetDimX(rsGetAllocation(point)); + float dy2 = dt * (10.f); + Point_t * p = point; + for (int ct=0; ct < size; ct++) { + p->delta.y += dy2; + p->position += p->delta; + if ((p->position.y > height) && (p->delta.y > 0)) { + p->delta.y *= -0.3f; + } + p++; + } + //Tell Renderscript runtime to render to the frame buffer object + rsgBindColorTarget(gColorBuffer, 0); + //Begin rendering on a white background + rsgClearColor(1.f, 1.f, 1.f, 1.f); + rsgDrawMesh(partMesh); + + //When done, tell Renderscript runtime to stop rendering to framebuffer object + rsgClearAllRenderTargets(); + + //Bind a new fragment shader that declares the framebuffer object to be used as a texture + rsgBindProgramFragment(gTextureProgramFragment); + + //Bind the framebuffer object to the fragment shader at slot 0 as a texture + rsgBindTexture(gTextureProgramFragment, 0, gColorBuffer); + //Draw a quad using the framebuffer object as the texture + float startX = 10, startY = 10; + float s = 256; + rsgDrawQuadTexCoords(startX, startY, 0, 0, 1, + startX, startY + s, 0, 0, 0, + startX + s, startY + s, 0, 1, 0, + startX + s, startY, 0, 1, 1); + + //Rebind the original fragment shader to render as normal + rsgBindProgramFragment(gProgramFragment); + + //Render the main scene + rsgDrawMesh(partMesh); + + return 1; +} +</pre> + </li> + + <li>In the <code>FountainRS.java</code> file, modify the <code>init()</code> method to look + like the following code. The modifications are commented: + +<pre> +/* Add necessary members */ +private ScriptC_fountainfbo mScript; +private Allocation mColorBuffer; +private ProgramFragment mProgramFragment; +private ProgramFragment mTextureProgramFragment; + +public void init(RenderScriptGL rs, Resources res) { + mRS = rs; + mRes = res; + + ScriptField_Point points = new ScriptField_Point(mRS, PART_COUNT); + + Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS); + smb.addVertexAllocation(points.getAllocation()); + smb.addIndexSetType(Mesh.Primitive.POINT); + Mesh sm = smb.create(); + + mScript = new ScriptC_fountainfbo(mRS, mRes, R.raw.fountainfbo); + mScript.set_partMesh(sm); + mScript.bind_point(points); + + ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs); + pfb.setVaryingColor(true); + mProgramFragment = pfb.create(); + mScript.set_gProgramFragment(mProgramFragment); + + /* Second fragment shader to use a texture (framebuffer object) to draw with */ + pfb.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.REPLACE, + ProgramFragmentFixedFunction.Builder.Format.RGBA, 0); + + /* Set the fragment shader in the Renderscript runtime */ + mTextureProgramFragment = pfb.create(); + mScript.set_gTextureProgramFragment(mTextureProgramFragment); + + /* Create the allocation for the color buffer */ + Type.Builder colorBuilder = new Type.Builder(mRS, Element.RGBA_8888(mRS)); + colorBuilder.setX(256).setY(256); + mColorBuffer = Allocation.createTyped(mRS, colorBuilder.create(), + Allocation.USAGE_GRAPHICS_TEXTURE | + Allocation.USAGE_GRAPHICS_RENDER_TARGET); + + /* Set the allocation in the Renderscript runtime */ + mScript.set_gColorBuffer(mColorBuffer); + + mRS.bindRootScript(mScript); +} +</pre> + +<p class="note"><strong>Note:</strong> This sample doesn't use a depth buffer, but the following code +shows you how to declare an example depth buffer if you need to use +one for your application. The depth buffer must have the same dimensions as the color buffer: + +<pre> +Allocation mDepthBuffer; + +... + +Type.Builder b = new Type.Builder(mRS, Element.createPixel(mRS, DataType.UNSIGNED_16, + DataKind.PIXEL_DEPTH)); +b.setX(256).setY(256); +mDepthBuffer = Allocation.createTyped(mRS, b.create(), +Allocation.USAGE_GRAPHICS_RENDER_TARGET); + +</pre> +</p> +</li> + + <li>Run and use the sample. The smaller, white quad on the top-left corner is using the + framebuffer object as a texture, which renders the same scene as the main rendering.</li> +</ol> diff --git a/docs/html/guide/topics/graphics/renderscript/index.jd b/docs/html/guide/topics/graphics/renderscript/index.jd new file mode 100644 index 0000000..b2d9f84 --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/index.jd @@ -0,0 +1,804 @@ +page.title=Renderscript +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#overview">Renderscript Overview</a></li> + <li><a href="#native">Renderscript Runtime Layer</a></li> + <li><a href="#reflected">Reflected Layer</a> + <ol> + <li><a href="#func">Functions</a></li> + <li><a href="#var">Variables</a></li> + <li><a href="#pointer">Pointers</a></li> + <li><a href="#struct">Structs</a></li> + </ol> + </li> + + <li> + <a href="#mem-allocation">Memory Allocation APIs</a> + </li> + <li> + <a href="#memory">Working with Memory</a> + <ol> + <li><a href="#allocating-mem">Allocating and binding memory to the Renderscript</a></li> + + <li><a href="#read-write">Reading and writing to memory</a></li> + + </ol> + </li> + </ol> + </div> + </div> + + <p>Renderscript offers a high performance 3D graphics rendering and compute API at the native + level that you write in C (C99 standard). The main advantages of Renderscript are:</p> + <ul> + <li>Portability: Renderscript is designed to run on many types of devices with different + processor (CPU, GPU, and DSP for instance) architectures. It supports all of these architectures without + having to target each device, because the code is compiled and cached on the device + at runtime.</li> + + <li>Performance: Renderscript provides similar performance to OpenGL with the NDK and also + provides a high performance compute API that is not offered by OpenGL.</li> + + <li>Usability: Renderscript simplifies development when possible, such as eliminating JNI glue code + and simplifying mesh setup.</li> + </ul> + + <p>The main disadvantages are:</p> + + <ul> + <li>Development complexity: Renderscript introduces a new set of APIs that you have to learn. + Renderscript also allocates memory differently compared to OpenGL with the Android framework APIs. + However, these issues are not hard to understand and Renderscript offers many features that + make it easier than OpenGL to initialize rendering.</li> + + <li>Debugging visibility: Renderscript can potentially execute (planned feature for later releases) + on processors other than the main CPU (such as the GPU), so if this occurs, debugging becomes more difficult. + </li> + </ul> + + + <p>For an example of Renderscript in action, install the Renderscript sample applications that + are shipped with the SDK in <code><sdk_root>/samples/android-11/RenderScript</code>. + You can also see a typical use of Renderscript with the 3D carousel view in the Android 3.x + versions of Google Books and YouTube.</p> + + <h2 id="overview">Renderscript Overview</h2> + <p>The Renderscript runtime operates at the native level and still needs to communicate +with the Android VM, so the way a Renderscript application is setup is different from a pure VM +application. An application that uses Renderscript is still a traditional Android application that +runs in the VM, but you write Renderscript code for the parts of your program that require +it. Using Renderscript can be as simple as offloading a few math calculations or as complicated as +rendering an entire 3D game. No matter what you use it for, Renderscript remains platform +independent, so you do not have to target multiple architectures (for example, +ARM v5, ARM v7, x86).</p> + + <p>The Renderscript system adopts a control and slave architecture where the low-level Renderscript runtime + code is controlled by the higher level Android system that runs in a virtual machine (VM). The + Android VM still retains all control of memory management and binds memory that it allocates to + the Renderscript runtime, so the Renderscript code can access it. The Android framework makes +asynchronous calls to Renderscript, and the calls are placed in a message queue and processed +as soon as possible. Figure 1 shows how the Renderscript system is structured.</p> + + <img id="figure1" src="{@docRoot}images/rs_overview.png" /> + <p class="img-caption"><strong>Figure 1.</strong> Renderscript system overview</p> + + <p>When using Renderscript, there are three layers of APIs that enable communication between the + Renderscript runtime and Android framework code:</p> + + <ul> + <li>The Renderscript runtime APIs allow you to do the computation or graphics rendering + that is required by your application.</li> + + <li>The reflected layer APIs are a set of classes that are reflected from your Renderscript +runtime code. It is basically a wrapper around the Renderscript code that allows the Android +framework to interact with the Renderscript runtime. The Android build tools automatically generate the +classes for this layer during the build process. These classes eliminate the need to write JNI glue +code, like with the NDK.</li> + + <li>The Android framework APIs, which include the {@link android.renderscript} package, allow you to + build your application using traditional Android components such as activities and views. When + using Renderscript, this layer calls the reflected layer to access the Renderscript + runtime.</li> + </ul> + + <p></p> + + <h2 id="native">Renderscript Runtime Layer</h2> + + <p>Your Renderscript code is compiled and + executed in a compact and well-defined runtime layer. The Renderscript runtime APIs offer support for +intensive computation and graphics rendering that is portable and automatically scalable to the +amount of cores available on a processor. +</p> +<p class="note"><strong>Note:</strong> The standard C functions in the NDK must be + guaranteed to run on a CPU, so Renderscript cannot access these libraries, + because Renderscript is designed to run on different types of processors.</p> + +<p>You define your Renderscript code in <code>.rs</code> + and <code>.rsh</code> files in the <code>src/</code> directory of your Android project. The code + is compiled to intermediate bytecode by the + <code>llvm</code> compiler that runs as part of an Android build. When your application + runs on a device, the bytecode is then compiled (just-in-time) to machine code by another + <code>llvm</code> compiler that resides on the device. The machine code is optimized for the + device and also cached, so subsequent uses of the Renderscript enabled application does not + recompile the bytecode.</p> + + <p>Some key features of the Renderscript runtime libraries include:</p> + + <ul> + + <li>Graphics rendering functions</li> + + <li>Memory allocation request features</li> + + <li>A large collection of math functions with both scalar and vector typed overloaded versions + of many common routines. Operations such as adding, multiplying, dot product, and cross product + are available as well as atomic arithmetic and comparison functions.</li> + + <li>Conversion routines for primitive data types and vectors, matrix routines, date and time + routines, and graphics routines.</li> + + <li>Data types and structures to support the Renderscript system such as Vector types for + defining two-, three-, or four-vectors.</li> + + <li>Logging functions</li> + </ul> + + <p>See the Renderscript runtime API reference for more information on the available functions. The + Renderscript header files are automatically included for you, except for the Renderscript graphics header file, which + you can include as follows:</p> + +<pre>#include "rs_graphics.rsh"</pre> + + <h2 id="reflected">Reflected Layer</h2> + + <p>The reflected layer is a set of classes that the Android build tools generate to allow access + to the Renderscript runtime from the Android framework. This layer also provides methods +and constructors that allow you to allocate and work with memory for pointers that are defined in +your Renderscript code. The following list describes the major + components that are reflected:</p> + + <ul> + <li>Every <code>.rs</code> file that you create is generated into a class named + <code>project_root/gen/package/name/ScriptC_<em>renderscript_filename</em></code> of +type {@link android.renderscript.ScriptC}. This file is the <code>.java</code> version of your +<code>.rs</code> file, which you can call from the Android framework. This class contains the +following items reflected from the <code>.rs</code> file: + + <ul> + <li>Non-static functions</li> + + <li>Non-static, global Renderscript variables. Accessor methods are generated for each + variable, so you can read and write the Renderscript variables from the Android + framework. If a global variable is initialized at the Renderscript runtime layer, those +values are used to initialize the corresponding values in the Android framework layer. If global +variables are marked as <code>const</code>, then a <code>set</code> method is not +generated.</p></li> + + <li>Global pointers</li> + </ul> + </li> + + <li>A <code>struct</code> is reflected into its own class named + + <code>project_root/gen/package/name/ScriptField_struct_name</em></code>, which extends {@link + android.renderscript.Script.FieldBase}. This class represents an array of the + <code>struct</code>, which allows you to allocate memory for one or more instances of this + <code>struct</code>.</li> + </ul> + + +<h3 id="func">Functions</h3> +<p>Functions are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. For +example, if you declare the following function in your Renderscript code:</p> + +<pre> +void touch(float x, float y, float pressure, int id) { + if (id >= 10) { + return; + } + + touchPos[id].x = x; + touchPos[id].y = y; + touchPressure[id] = pressure; +} +</pre> + +<p>then the following code is generated:</p> + +<pre> +public void invoke_touch(float x, float y, float pressure, int id) { + FieldPacker touch_fp = new FieldPacker(16); + touch_fp.addF32(x); + touch_fp.addF32(y); + touch_fp.addF32(pressure); + touch_fp.addI32(id); + invoke(mExportFuncIdx_touch, touch_fp); +} +</pre> +<p> +Functions cannot have a return value, because the Renderscript system is designed to be +asynchronous. When your Android framework code calls into Renderscript, the call is queued and is +executed when possible. This restriction allows the Renderscript system to function without constant +interruption and increases efficiency. If functions were allowed to have return values, the call +would block until the value was returned.</p> + +<p> +If you want the Renderscript code to send a value back to the Android framework, use the +<a href="{@docRoot}reference/renderscript/rs__core_8rsh.html"><code>rsSendToClient()</code></a> +function. +</p> + +<h3 id="var">Variables</h3> + + <p>Variables of supported types are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. A set of accessor +methods are generated for each variable. For example, if you declare the following variable in +your Renderscript code:</p> + <pre>uint32_t unsignedInteger = 1;</pre> + + <p>then the following code is generated:</p> + +<pre> +private long mExportVar_unsignedInteger; +public void set_unsignedInteger(long v){ + mExportVar_unsignedInteger = v; + setVar(mExportVarIdx_unsignedInteger, v); +} + +public long get_unsignedInteger(){ + return mExportVar_unsignedInteger; +} + </pre> + + + <h3 id="struct">Structs</h3> + <p>Structs are reflected into their own classes, located in + <code><project_root>/gen/com/example/renderscript/ScriptField_struct_name</code>. This + class represents an array of the <code>struct</code> and allows you to allocate memory for a + specified number of <code>struct</code>s. For example, if you declare the following struct:</p> +<pre> +typedef struct Point { + float2 position; + float size; +} Point_t; +</pre> + +<p>then the following code is generated in <code>ScriptField_Point.java</code>: +<pre> +package com.example.android.rs.hellocompute; + +import android.renderscript.*; +import android.content.res.Resources; + + /** + * @hide + */ +public class ScriptField_Point extends android.renderscript.Script.FieldBase { + + static public class Item { + public static final int sizeof = 12; + + Float2 position; + float size; + + Item() { + position = new Float2(); + } + } + + private Item mItemArray[]; + private FieldPacker mIOBuffer; + public static Element createElement(RenderScript rs) { + Element.Builder eb = new Element.Builder(rs); + eb.add(Element.F32_2(rs), "position"); + eb.add(Element.F32(rs), "size"); + return eb.create(); + } + + public ScriptField_Point(RenderScript rs, int count) { + mItemArray = null; + mIOBuffer = null; + mElement = createElement(rs); + init(rs, count); + } + + public ScriptField_Point(RenderScript rs, int count, int usages) { + mItemArray = null; + mIOBuffer = null; + mElement = createElement(rs); + init(rs, count, usages); + } + + private void copyToArray(Item i, int index) { + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count + */); + mIOBuffer.reset(index * Item.sizeof); + mIOBuffer.addF32(i.position); + mIOBuffer.addF32(i.size); + } + + public void set(Item i, int index, boolean copyNow) { + if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */]; + mItemArray[index] = i; + if (copyNow) { + copyToArray(i, index); + mAllocation.setFromFieldPacker(index, mIOBuffer); + } + } + + public Item get(int index) { + if (mItemArray == null) return null; + return mItemArray[index]; + } + + public void set_position(int index, Float2 v, boolean copyNow) { + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); + if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */]; + if (mItemArray[index] == null) mItemArray[index] = new Item(); + mItemArray[index].position = v; + if (copyNow) { + mIOBuffer.reset(index * Item.sizeof); + mIOBuffer.addF32(v); + FieldPacker fp = new FieldPacker(8); + fp.addF32(v); + mAllocation.setFromFieldPacker(index, 0, fp); + } + } + + public void set_size(int index, float v, boolean copyNow) { + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); + if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */]; + if (mItemArray[index] == null) mItemArray[index] = new Item(); + mItemArray[index].size = v; + if (copyNow) { + mIOBuffer.reset(index * Item.sizeof + 8); + mIOBuffer.addF32(v); + FieldPacker fp = new FieldPacker(4); + fp.addF32(v); + mAllocation.setFromFieldPacker(index, 1, fp); + } + } + + public Float2 get_position(int index) { + if (mItemArray == null) return null; + return mItemArray[index].position; + } + + public float get_size(int index) { + if (mItemArray == null) return 0; + return mItemArray[index].size; + } + + public void copyAll() { + for (int ct = 0; ct < mItemArray.length; ct++) copyToArray(mItemArray[ct], ct); + mAllocation.setFromFieldPacker(0, mIOBuffer); + } + + public void resize(int newSize) { + if (mItemArray != null) { + int oldSize = mItemArray.length; + int copySize = Math.min(oldSize, newSize); + if (newSize == oldSize) return; + Item ni[] = new Item[newSize]; + System.arraycopy(mItemArray, 0, ni, 0, copySize); + mItemArray = ni; + } + mAllocation.resize(newSize); + if (mIOBuffer != null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); + } +} +</pre> + +<p>The generated code is provided to you as a convenience to allocate memory for structs requested +by the Renderscript runtime and to interact with <code>struct</code>s +in memory. Each <code>struct</code>'s class defines the following methods and constructors:</p> + + <ul> + <li>Overloaded constructors that allow you to allocate memory. The + <code>ScriptField_<em>struct_name</em>(RenderScript rs, int count)</code> constructor allows + you to define the number of structures that you want to allocate memory for with the + <code>count</code> parameter. The <code>ScriptField_<em>struct_name</em>(RenderScript rs, int + count, int usages)</code> constructor defines an extra parameter, <code>usages</code>, that + lets you specify the memory space of this memory allocation. There are four memory space + possibilities: + + <ul> + <li>{@link android.renderscript.Allocation#USAGE_SCRIPT}: Allocates in the script memory + space. This is the default memory space if you do not specify a memory space.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE}: Allocates in the + texture memory space of the GPU.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_VERTEX}: Allocates in the vertex + memory space of the GPU.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_CONSTANTS}: Allocates in the + constants memory space of the GPU that is used by the various program objects.</li> + </ul> + + <p>You can specify multiple memory spaces by using the bitwise <code>OR</code> operator. Doing so + notifies the Renderscript runtime that you intend on accessing the data in the + specified memory spaces. The following example allocates memory for a custom data type + in both the script and vertex memory spaces:</p> + <pre> + ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2, + Allocation.USAGE_SCRIPT | Allocation.USAGE_GRAPHICS_VERTEX); + </pre> + + <p>If you modify the memory in one memory space and want to push the updates to the rest of + the memory spaces, call <a href="{@docRoot}reference/renderscript/rs__graphics_8rsh.html"> + <code>rsgAllocationSyncAll()</code></a> in your Renderscript code to + synchronize the memory.</p> + </li> + + <li>A static nested class, <code>Item</code>, allows you to create an instance of the + <code>struct</code>, in the form of an object. This nested class is useful if it makes more sense to work + with the <code>struct</code> in your Android code. When you are done manipulating the object, + you can push the object to the allocated memory by calling <code>set(Item i, int index, + boolean copyNow)</code> and setting the <code>Item</code> to the desired position in +the array. The Renderscript runtime automatically has access to the newly written memory. + + <li>Accessor methods to get and set the values of each field in a struct. Each of these + accessor methods have an <code>index</code> parameter to specify the <code>struct</code> in + the array that you want to read or write to. Each setter method also has a +<code>copyNow</code> parameter that specifies whether or not to immediately sync this memory +to the Renderscript runtime. To sync any memory that has not been synced, call + <code>copyAll()</code>.</li> + + <li>The <code>createElement()</code> method creates a description of the struct in memory. This + description is used to allocate memory consisting of one or many elements.</li> + + <li><code>resize()</code> works much like a <code>realloc()</code> in C, allowing you to +expand previously allocated memory, maintaining the current values that were previously +created.</li> + + <li><code>copyAll()</code> synchronizes memory that was set on the framework level to the +Renderscript runtime. When you call a set accessor method on a member, there is an optional +<code>copyNow</code> boolean parameter that you can specify. Specifying + <code>true</code> synchronizes the memory when you call the method. If you specify false, + you can call <code>copyAll()</code> once, and it synchronizes memory for all the +properties that are not yet synchronized.</li> + </ul> + + <h3 id="pointer">Pointers</h3> + <p>Pointers are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. You +can declare pointers to a <code>struct</code> or any of the supported Renderscript types, but a +<code>struct</code> cannot contain pointers or nested arrays. For example, if you declare the +following pointers to a <code>struct</code> and <code>int32_t</code></p> + +<pre> +typedef struct Point { + float2 position; + float size; +} Point_t; + +Point_t *touchPoints; +int32_t *intPointer; +</pre> + <p>then the following code is generated in:</p> + +<pre> +private ScriptField_Point mExportVar_touchPoints; +public void bind_touchPoints(ScriptField_Point v) { + mExportVar_touchPoints = v; + if (v == null) bindAllocation(null, mExportVarIdx_touchPoints); + else bindAllocation(v.getAllocation(), mExportVarIdx_touchPoints); +} + +public ScriptField_Point get_touchPoints() { + return mExportVar_touchPoints; +} + +private Allocation mExportVar_intPointer; +public void bind_intPointer(Allocation v) { + mExportVar_intPointer = v; + if (v == null) bindAllocation(null, mExportVarIdx_intPointer); + else bindAllocation(v, mExportVarIdx_intPointer); +} + +public Allocation get_intPointer() { + return mExportVar_intPointer; +} + </pre> + +<p>A <code>get</code> method and a special method named <code>bind_<em>pointer_name</em></code> +(instead of a <code>set()</code> method) is generated. This method allows you to bind the memory +that is allocated in the Android VM to the Renderscript runtime (you cannot allocate +memory in your <code>.rs</code> file). For more information, see <a href="#memory">Working +with Allocated Memory</a>. +</p> + + + <h2 id="mem-allocation">Memory Allocation APIs</h2> + + <p>Applications that use Renderscript still run in the Android VM. The actual Renderscript code, however, runs natively and + needs access to the memory allocated in the Android VM. To accomplish this, you must + attach the memory that is allocated in the VM to the Renderscript runtime. This +process, called binding, allows the Renderscript runtime to seamlessly work with memory that it +requests but cannot explicitly allocate. The end result is essentially the same as if you had +called <code>malloc</code> in C. The added benefit is that the Android VM can carry out garbage collection as well as +share memory with the Renderscript runtime layer. Binding is only necessary for dynamically allocated memory. Statically +allocated memory is automatically created for your Renderscript code at compile time. See <a href="#figure1">Figure 1</a> +for more information on how memory allocation occurs. +</p> + + <p>To support this memory allocation system, there are a set of APIs that allow the Android VM to +allocate memory and offer similar functionality to a <code>malloc</code> call. These classes +essentially describe how memory should be allocated and also carry out the allocation. To better +understand how these classes work, it is useful to think of them in relation to a simple +<code>malloc</code> call that can look like this: </p> + + <pre>array = (int *)malloc(sizeof(int)*10);</pre> + + <p>The <code>malloc</code> call can be broken up into two parts: the size of the memory being allocated (<code>sizeof(int)</code>), + along with how many units of that memory should be allocated (10). The Android framework provides classes for these two parts as + well as a class to represent <code>malloc</code> itself.</p> + + <p>The {@link android.renderscript.Element} class represents the (<code>sizeof(int)</code>) portion + of the <code>malloc</code> call and encapsulates one cell of a memory allocation, such as a single + float value or a struct. The {@link android.renderscript.Type} class encapsulates the {@link android.renderscript.Element} + and the amount of elements to allocate (10 in our example). You can think of a {@link android.renderscript.Type} as + an array of {@link android.renderscript.Element}s. The {@link android.renderscript.Allocation} class does the actual + memory allocation based on a given {@link android.renderscript.Type} and represents the actual allocated memory.</p> + + <p>In most situations, you do not need to call these memory allocation APIs directly. The reflected layer + classes generate code to use these APIs automatically and all you need to do to allocate memory is call a + constructor that is declared in one of the reflected layer classes and then bind + the resulting memory {@link android.renderscript.Allocation} to the Renderscript. + There are some situations where you would want to use these classes directly to allocate memory on your + own, such as loading a bitmap from a resource or when you want to allocate memory for pointers to + primitive types. You can see how to do this in the + <a href="#allocating-mem">Allocating and binding memory to the Renderscript</a> section. + The following table describes the three memory management classes in more detail:</p> + + <table id="mem-mgmt-table"> + <tr> + <th>Android Object Type</th> + + <th>Description</th> + </tr> + + <tr> + <td>{@link android.renderscript.Element}</td> + + <td> + <p>An element describes one cell of a memory allocation and can have two forms: basic or + complex.</p> + + <p>A basic element contains a single component of data of any valid Renderscript data type. + Examples of basic element data types include a single <code>float</code> value, a <code>float4</code> vector, or a + single RGB-565 color.</p> + + <p>Complex elements contain a list of basic elements and are created from + <code>struct</code>s that you declare in your Renderscript code. For instance an allocation + can contain multiple <code>struct</code>s arranged in order in memory. Each struct is considered as its + own element, rather than each data type within that struct.</p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.Type}</td> + + <td> + <p>A type is a memory allocation template and consists of an element and one or more + dimensions. It describes the layout of the memory (basically an array of {@link + android.renderscript.Element}s) but does not allocate the memory for the data that it + describes.</p> + + <p>A type consists of five dimensions: X, Y, Z, LOD (level of detail), and Faces (of a cube + map). You can assign the X,Y,Z dimensions to any positive integer value within the + constraints of available memory. A single dimension allocation has an X dimension of + greater than zero while the Y and Z dimensions are zero to indicate not present. For + example, an allocation of x=10, y=1 is considered two dimensional and x=10, y=0 is + considered one dimensional. The LOD and Faces dimensions are booleans to indicate present + or not present.</p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.Allocation}</td> + + <td> + <p>An allocation provides the memory for applications based on a description of the memory + that is represented by a {@link android.renderscript.Type}. Allocated memory can exist in + many memory spaces concurrently. If memory is modified in one space, you must explicitly + synchronize the memory, so that it is updated in all the other spaces in which it exists. + </p> + + <p>Allocation data is uploaded in one of two primary ways: type checked and type unchecked. + For simple arrays there are <code>copyFrom()</code> functions that take an array from the + Android system and copy it to the native layer memory store. The unchecked variants allow + the Android system to copy over arrays of structures because it does not support + structures. For example, if there is an allocation that is an array of n floats, the data + contained in a float[n] array or a <code>byte[n*4]</code> array can be copied.</p> + </td> + </tr> + </table> + + <h2 id="memory">Working with Memory</h2> + +<p>Non-static, global variables that you declare in your Renderscript are allocated memory at compile time. +You can work with these variables directly in your Renderscript code without having to allocate +memory for them at the Android framework level. The Android framework layer also has access to these variables +with the provided accessor methods that are generated in the reflected layer classes. If these variables are +initialized at the Renderscript runtime layer, those values are used to initialize the corresponding +values in the Android framework layer. If global variables are marked as const, then a <code>set</code> method is +not generated.</p> + + +<p class="note"><strong>Note:</strong> If you are using certain Renderscript structures that contain pointers, such as +<code>rs_program_fragment</code> and <code>rs_allocation</code>, you have to obtain an object of the +corresponding Android framework class first and then call the <code>set</code> method for that +structure to bind the memory to the Renderscript runtime. You cannot directly manipulate these structures +at the Renderscript runtime layer. This restriction is not applicable to user-defined structures +that contain pointers, because they cannot be exported to a reflected layer class +in the first place. A compiler error is generated if you try to declare a non-static, global +struct that contains a pointer. +</p> + +<p>Renderscript also has support for pointers, but you must explicitly allocate the memory in your +Android framework code. When you declare a global pointer in your <code>.rs</code> file, you +allocate memory through the appropriate reflected layer class and bind that memory to the native +Renderscript layer. You can interact with this memory from the Android framework layer as well as +the Renderscript layer, which offers you the flexibility to modify variables in the most +appropriate layer.</p> + + + + <h3 id="allocating-mem">Allocating and binding dynamic memory to the Renderscript</h3> + + <p>To allocate dynamic memory, you need to call the constructor of a + {@link android.renderscript.Script.FieldBase} class, which is the most common way. An alternative is to create an + {@link android.renderscript.Allocation} manually, which is required for things such as primitive type pointers. You should + use a {@link android.renderscript.Script.FieldBase} class constructor whenever available for simplicity. + After obtaining a memory allocation, call the reflected <code>bind</code> method of the pointer to bind the allocated memory to the + Renderscript runtime.</p> + <p>The example below allocates memory for both a primitive type pointer, + <code>intPointer</code>, and a pointer to a struct, <code>touchPoints</code>. It also binds the memory to the + Renderscript:</p> + <pre> +private RenderScriptGL glRenderer; +private ScriptC_example script; +private Resources resources; + +public void init(RenderScriptGL rs, Resources res) { + //get the rendering context and resources from the calling method + glRenderer = rs; + resources = res; + + //allocate memory for the struct pointer, calling the constructor + ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2); + + //Create an element manually and allocate memory for the int pointer + intPointer = Allocation.createSized(glRenderer, Element.I32(glRenderer), 2); + + //create an instance of the Renderscript, pointing it to the bytecode resource + mScript = new ScriptC_example(glRenderer, resources, R.raw.example); + + //bind the struct and int pointers to the Renderscript + mScript.bind_touchPoints(touchPoints); + script.bind_intPointer(intPointer); + + ... +} +</pre> + + <h3>Reading and writing to memory</h3> + <p>You can read and write to statically and dynamically allocated memory both at the Renderscript runtime + and Android framework layer.</p> + +<p>Statically allocated memory comes with a one-way communication restriction +at the Renderscript runtime level. When Renderscript code changes the value of a variable, it is not +communicated back to the Android framework layer for efficiency purposes. The last value +that is set from the Android framework is always returned during a call to a <code>get</code> +method. However, when Android framework code modifies a variable, that change can be communicated to +the Renderscript runtime automatically or synchronized at a later time. If you need to send data +from the Renderscript runtime to the Android framework layer, you can use the +<a href="{@docRoot}reference/renderscript/rs__core_8rsh.html"><code>rsSendToClient()</code></a> function +to overcome this limitation. +</p> +<p>When working with dynamically allocated memory, any changes at the Renderscript runtime layer are propagated +back to the Android framework layer if you modified the memory allocation using its associated pointer. +Modifying an object at the Android framework layer immediately propagates that change back to the Renderscript +runtime layer.</p> + + <h4>Reading and writing to global variables</h4> + + <p>Reading and writing to global variables is a straightforward process. You can use the accessor methods + at the Android framework level or set them directly in the Renderscript code. Keep in mind that any + changes that you make in your Renderscript code are not propagated back to the Android framework layer.</p> + + <p>For example, given the following struct declared in a file named <code>rsfile.rs</code>:</p> +<pre> +typedef struct Point { + int x; + int y; +} Point_t; + +Point_t point; + +</pre> +<p>You can assign values to the struct like this directly in <code>rsfile.rs</code>. These values are not +propagated back to the Android framework level:</p> +<pre> +point.x = 1; +point.y = 1; +</pre> + +<p>You can assign values to the struct at the Android framework layer like this. These values are +propagated back to the Renderscript runtime level:</p> +<pre> +ScriptC_rsfile mScript; + +... + +Item i = new ScriptField_Point.Item(); +i.x = 1; +i.y = 1; +mScript.set_point(i); +</pre> + +<p>You can read the values in your Renderscript code like this:</p> + +<pre> +rsDebug("Printing out a Point", point.x, point.y); +</pre> + +<p>You can read the values in the Android framework layer with the following code. Keep in mind that this +code only returns a value if one was set at the Android framework level. You will get a null pointer +exception if you only set the value at the Renderscript runtime level:</p> + +<pre> +Log.i("TAGNAME", "Printing out a Point: " + mScript.get_point().x + " " + mScript.get_point().y); +System.out.println(point.get_x() + " " + point.get_y()); +</pre> + +<h4>Reading and writing global pointers</h4> + +<p>Assuming that memory has been allocated in the Android framework level and bound to the Renderscript runtime, +you can read and write memory from the Android framework level by using the <code>get</code> and <code>set</code> methods for that pointer. +In the Renderscript runtime layer, you can read and write to memory with pointers as normal and the changes are propagated +back to the Android framework layer, unlike with statically allocated memory.</p> + +<p>For example, given the following pointer to a <code>struct</code> in a file named <code>rsfile.rs</code>:</p> +<pre> +typedef struct Point { + int x; + int y; +} Point_t; + +Point_t *point; +</pre> + +<p>Assuming you already allocated memory at the Android framework layer, you can access values in +the <code>struct</code> as normal. Any changes you make to the struct via its pointer variable +are automatically available to the Android framework layer:</p> + +<pre> +point[index].x = 1; +point[index].y = 1; +</pre> + +<p>You can read and write values to the pointer at the Android framework layer as well: +<pre> +ScriptField_Point p = new ScriptField_Point(mRS, 1); + Item i = new ScriptField_Point.Item(); + i.x=100; + i.y = 100; + p.set(i, 0, true); + mScript.bind_point(p); + + points.get_x(0); //read x and y from index 0 + points.get_x(0); +</pre> + +<p>Once memory is already bound, you do not have to rebind the memory to the Renderscript +runtime every time you make a change to a value.</p> diff --git a/docs/html/guide/topics/graphics/renderscript/reference.jd b/docs/html/guide/topics/graphics/renderscript/reference.jd new file mode 100644 index 0000000..a0a9df2 --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/reference.jd @@ -0,0 +1,18 @@ +page.title=Runtime API Reference +@jd:body + +<script language="JavaScript"> + +function autoResize(element){ + var newheight; + var newwidth; + + newheight = element.contentWindow.document.body.scrollHeight + 20; + newwidth = element.contentWindow.document.body.scrollWidth; + element.height = (newheight) + "px"; + element.width = (newwidth) + "px"; +} +</script> + + +<iframe SRC="{@docRoot}reference/renderscript/index.html" width="100%" id="iframe" marginheight="0" frameborder="0" onLoad="autoResize(this);"></iframe> |