RenderScript.java revision 0b1ad704f4d66219e4b0e1e87947b4d004d3414f
1/*
2 * Copyright (C) 2008-2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.renderscript;
18
19import java.lang.reflect.Field;
20
21import android.content.Context;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.PackageManager;
24import android.content.res.AssetManager;
25import android.graphics.Bitmap;
26import android.graphics.BitmapFactory;
27import android.graphics.SurfaceTexture;
28import android.os.Process;
29import android.util.Log;
30import android.view.Surface;
31
32
33
34/**
35 * Renderscript base master class.  An instance of this class creates native
36 * worker threads for processing commands from this object.  This base class
37 * does not provide any extended capabilities beyond simple data processing.
38 * For extended capabilities use derived classes such as RenderScriptGL.
39 *
40 * <div class="special reference">
41 * <h3>Developer Guides</h3>
42 * <p>For more information about creating an application that uses Renderscript, read the
43 * <a href="{@docRoot}guide/topics/graphics/renderscript.html">Renderscript</a> developer guide.</p>
44 * </div>
45 **/
46public class RenderScript {
47    static final String LOG_TAG = "RenderScript_jni";
48    static final boolean DEBUG  = false;
49    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
50    static final boolean LOG_ENABLED = false;
51
52    private Context mApplicationContext;
53
54    /*
55     * We use a class initializer to allow the native code to cache some
56     * field offsets.
57     */
58    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
59    static boolean sInitialized;
60    native static void _nInit();
61
62
63    static {
64        sInitialized = false;
65        try {
66            System.loadLibrary("rs_jni");
67            _nInit();
68            sInitialized = true;
69        } catch (UnsatisfiedLinkError e) {
70            Log.e(LOG_TAG, "Error loading RS jni library: " + e);
71            throw new RSRuntimeException("Error loading RS jni library: " + e);
72        }
73    }
74
75    // Non-threadsafe functions.
76    native int  nDeviceCreate();
77    native void nDeviceDestroy(int dev);
78    native void nDeviceSetConfig(int dev, int param, int value);
79    native int nContextGetUserMessage(int con, int[] data);
80    native String nContextGetErrorMessage(int con);
81    native int  nContextPeekMessage(int con, int[] subID);
82    native void nContextInitToClient(int con);
83    native void nContextDeinitToClient(int con);
84
85
86    // Methods below are wrapped to protect the non-threadsafe
87    // lockless fifo.
88    native int  rsnContextCreateGL(int dev, int ver, int sdkVer,
89                 int colorMin, int colorPref,
90                 int alphaMin, int alphaPref,
91                 int depthMin, int depthPref,
92                 int stencilMin, int stencilPref,
93                 int samplesMin, int samplesPref, float samplesQ, int dpi);
94    synchronized int nContextCreateGL(int dev, int ver, int sdkVer,
95                 int colorMin, int colorPref,
96                 int alphaMin, int alphaPref,
97                 int depthMin, int depthPref,
98                 int stencilMin, int stencilPref,
99                 int samplesMin, int samplesPref, float samplesQ, int dpi) {
100        return rsnContextCreateGL(dev, ver, sdkVer, colorMin, colorPref,
101                                  alphaMin, alphaPref, depthMin, depthPref,
102                                  stencilMin, stencilPref,
103                                  samplesMin, samplesPref, samplesQ, dpi);
104    }
105    native int  rsnContextCreate(int dev, int ver, int sdkVer);
106    synchronized int nContextCreate(int dev, int ver, int sdkVer) {
107        return rsnContextCreate(dev, ver, sdkVer);
108    }
109    native void rsnContextDestroy(int con);
110    synchronized void nContextDestroy() {
111        validate();
112        rsnContextDestroy(mContext);
113    }
114    native void rsnContextSetSurface(int con, int w, int h, Surface sur);
115    synchronized void nContextSetSurface(int w, int h, Surface sur) {
116        validate();
117        rsnContextSetSurface(mContext, w, h, sur);
118    }
119    native void rsnContextSetSurfaceTexture(int con, int w, int h, SurfaceTexture sur);
120    synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
121        validate();
122        rsnContextSetSurfaceTexture(mContext, w, h, sur);
123    }
124    native void rsnContextSetPriority(int con, int p);
125    synchronized void nContextSetPriority(int p) {
126        validate();
127        rsnContextSetPriority(mContext, p);
128    }
129    native void rsnContextDump(int con, int bits);
130    synchronized void nContextDump(int bits) {
131        validate();
132        rsnContextDump(mContext, bits);
133    }
134    native void rsnContextFinish(int con);
135    synchronized void nContextFinish() {
136        validate();
137        rsnContextFinish(mContext);
138    }
139
140    native void rsnContextBindRootScript(int con, int script);
141    synchronized void nContextBindRootScript(int script) {
142        validate();
143        rsnContextBindRootScript(mContext, script);
144    }
145    native void rsnContextBindSampler(int con, int sampler, int slot);
146    synchronized void nContextBindSampler(int sampler, int slot) {
147        validate();
148        rsnContextBindSampler(mContext, sampler, slot);
149    }
150    native void rsnContextBindProgramStore(int con, int pfs);
151    synchronized void nContextBindProgramStore(int pfs) {
152        validate();
153        rsnContextBindProgramStore(mContext, pfs);
154    }
155    native void rsnContextBindProgramFragment(int con, int pf);
156    synchronized void nContextBindProgramFragment(int pf) {
157        validate();
158        rsnContextBindProgramFragment(mContext, pf);
159    }
160    native void rsnContextBindProgramVertex(int con, int pv);
161    synchronized void nContextBindProgramVertex(int pv) {
162        validate();
163        rsnContextBindProgramVertex(mContext, pv);
164    }
165    native void rsnContextBindProgramRaster(int con, int pr);
166    synchronized void nContextBindProgramRaster(int pr) {
167        validate();
168        rsnContextBindProgramRaster(mContext, pr);
169    }
170    native void rsnContextPause(int con);
171    synchronized void nContextPause() {
172        validate();
173        rsnContextPause(mContext);
174    }
175    native void rsnContextResume(int con);
176    synchronized void nContextResume() {
177        validate();
178        rsnContextResume(mContext);
179    }
180
181    native void rsnAssignName(int con, int obj, byte[] name);
182    synchronized void nAssignName(int obj, byte[] name) {
183        validate();
184        rsnAssignName(mContext, obj, name);
185    }
186    native String rsnGetName(int con, int obj);
187    synchronized String nGetName(int obj) {
188        validate();
189        return rsnGetName(mContext, obj);
190    }
191    native void rsnObjDestroy(int con, int id);
192    synchronized void nObjDestroy(int id) {
193        // There is a race condition here.  The calling code may be run
194        // by the gc while teardown is occuring.  This protects againts
195        // deleting dead objects.
196        if (mContext != 0) {
197            rsnObjDestroy(mContext, id);
198        }
199    }
200
201    native int  rsnElementCreate(int con, int type, int kind, boolean norm, int vecSize);
202    synchronized int nElementCreate(int type, int kind, boolean norm, int vecSize) {
203        validate();
204        return rsnElementCreate(mContext, type, kind, norm, vecSize);
205    }
206    native int  rsnElementCreate2(int con, int[] elements, String[] names, int[] arraySizes);
207    synchronized int nElementCreate2(int[] elements, String[] names, int[] arraySizes) {
208        validate();
209        return rsnElementCreate2(mContext, elements, names, arraySizes);
210    }
211    native void rsnElementGetNativeData(int con, int id, int[] elementData);
212    synchronized void nElementGetNativeData(int id, int[] elementData) {
213        validate();
214        rsnElementGetNativeData(mContext, id, elementData);
215    }
216    native void rsnElementGetSubElements(int con, int id,
217                                         int[] IDs, String[] names, int[] arraySizes);
218    synchronized void nElementGetSubElements(int id, int[] IDs, String[] names, int[] arraySizes) {
219        validate();
220        rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
221    }
222
223    native int rsnTypeCreate(int con, int eid, int x, int y, int z, boolean mips, boolean faces);
224    synchronized int nTypeCreate(int eid, int x, int y, int z, boolean mips, boolean faces) {
225        validate();
226        return rsnTypeCreate(mContext, eid, x, y, z, mips, faces);
227    }
228    native void rsnTypeGetNativeData(int con, int id, int[] typeData);
229    synchronized void nTypeGetNativeData(int id, int[] typeData) {
230        validate();
231        rsnTypeGetNativeData(mContext, id, typeData);
232    }
233
234    native int  rsnAllocationCreateTyped(int con, int type, int mip, int usage, int pointer);
235    synchronized int nAllocationCreateTyped(int type, int mip, int usage, int pointer) {
236        validate();
237        return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
238    }
239    native int  rsnAllocationCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
240    synchronized int nAllocationCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
241        validate();
242        return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
243    }
244    native int  rsnAllocationCubeCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
245    synchronized int nAllocationCubeCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
246        validate();
247        return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
248    }
249    native int  rsnAllocationCreateBitmapRef(int con, int type, Bitmap bmp);
250    synchronized int nAllocationCreateBitmapRef(int type, Bitmap bmp) {
251        validate();
252        return rsnAllocationCreateBitmapRef(mContext, type, bmp);
253    }
254    native int  rsnAllocationCreateFromAssetStream(int con, int mips, int assetStream, int usage);
255    synchronized int nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
256        validate();
257        return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage);
258    }
259
260    native void  rsnAllocationCopyToBitmap(int con, int alloc, Bitmap bmp);
261    synchronized void nAllocationCopyToBitmap(int alloc, Bitmap bmp) {
262        validate();
263        rsnAllocationCopyToBitmap(mContext, alloc, bmp);
264    }
265
266
267    native void rsnAllocationSyncAll(int con, int alloc, int src);
268    synchronized void nAllocationSyncAll(int alloc, int src) {
269        validate();
270        rsnAllocationSyncAll(mContext, alloc, src);
271    }
272    native int rsnAllocationGetSurfaceTextureID(int con, int alloc);
273    synchronized int nAllocationGetSurfaceTextureID(int alloc) {
274        validate();
275        return rsnAllocationGetSurfaceTextureID(mContext, alloc);
276    }
277
278    native void rsnAllocationGenerateMipmaps(int con, int alloc);
279    synchronized void nAllocationGenerateMipmaps(int alloc) {
280        validate();
281        rsnAllocationGenerateMipmaps(mContext, alloc);
282    }
283    native void  rsnAllocationCopyFromBitmap(int con, int alloc, Bitmap bmp);
284    synchronized void nAllocationCopyFromBitmap(int alloc, Bitmap bmp) {
285        validate();
286        rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
287    }
288
289
290    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, int[] d, int sizeBytes);
291    synchronized void nAllocationData1D(int id, int off, int mip, int count, int[] d, int sizeBytes) {
292        validate();
293        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
294    }
295    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, short[] d, int sizeBytes);
296    synchronized void nAllocationData1D(int id, int off, int mip, int count, short[] d, int sizeBytes) {
297        validate();
298        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
299    }
300    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, byte[] d, int sizeBytes);
301    synchronized void nAllocationData1D(int id, int off, int mip, int count, byte[] d, int sizeBytes) {
302        validate();
303        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
304    }
305    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, float[] d, int sizeBytes);
306    synchronized void nAllocationData1D(int id, int off, int mip, int count, float[] d, int sizeBytes) {
307        validate();
308        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
309    }
310
311    native void rsnAllocationElementData1D(int con, int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes);
312    synchronized void nAllocationElementData1D(int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes) {
313        validate();
314        rsnAllocationElementData1D(mContext, id, xoff, mip, compIdx, d, sizeBytes);
315    }
316
317    native void rsnAllocationData2D(int con,
318                                    int dstAlloc, int dstXoff, int dstYoff,
319                                    int dstMip, int dstFace,
320                                    int width, int height,
321                                    int srcAlloc, int srcXoff, int srcYoff,
322                                    int srcMip, int srcFace);
323    synchronized void nAllocationData2D(int dstAlloc, int dstXoff, int dstYoff,
324                                        int dstMip, int dstFace,
325                                        int width, int height,
326                                        int srcAlloc, int srcXoff, int srcYoff,
327                                        int srcMip, int srcFace) {
328        validate();
329        rsnAllocationData2D(mContext,
330                            dstAlloc, dstXoff, dstYoff,
331                            dstMip, dstFace,
332                            width, height,
333                            srcAlloc, srcXoff, srcYoff,
334                            srcMip, srcFace);
335    }
336
337    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes);
338    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes) {
339        validate();
340        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
341    }
342    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes);
343    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes) {
344        validate();
345        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
346    }
347    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes);
348    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes) {
349        validate();
350        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
351    }
352    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes);
353    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes) {
354        validate();
355        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
356    }
357    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, Bitmap b);
358    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, Bitmap b) {
359        validate();
360        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
361    }
362
363    native void rsnAllocationRead(int con, int id, byte[] d);
364    synchronized void nAllocationRead(int id, byte[] d) {
365        validate();
366        rsnAllocationRead(mContext, id, d);
367    }
368    native void rsnAllocationRead(int con, int id, short[] d);
369    synchronized void nAllocationRead(int id, short[] d) {
370        validate();
371        rsnAllocationRead(mContext, id, d);
372    }
373    native void rsnAllocationRead(int con, int id, int[] d);
374    synchronized void nAllocationRead(int id, int[] d) {
375        validate();
376        rsnAllocationRead(mContext, id, d);
377    }
378    native void rsnAllocationRead(int con, int id, float[] d);
379    synchronized void nAllocationRead(int id, float[] d) {
380        validate();
381        rsnAllocationRead(mContext, id, d);
382    }
383    native int  rsnAllocationGetType(int con, int id);
384    synchronized int nAllocationGetType(int id) {
385        validate();
386        return rsnAllocationGetType(mContext, id);
387    }
388
389    native void rsnAllocationResize1D(int con, int id, int dimX);
390    synchronized void nAllocationResize1D(int id, int dimX) {
391        validate();
392        rsnAllocationResize1D(mContext, id, dimX);
393    }
394    native void rsnAllocationResize2D(int con, int id, int dimX, int dimY);
395    synchronized void nAllocationResize2D(int id, int dimX, int dimY) {
396        validate();
397        rsnAllocationResize2D(mContext, id, dimX, dimY);
398    }
399
400    native int  rsnFileA3DCreateFromAssetStream(int con, int assetStream);
401    synchronized int nFileA3DCreateFromAssetStream(int assetStream) {
402        validate();
403        return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
404    }
405    native int  rsnFileA3DCreateFromFile(int con, String path);
406    synchronized int nFileA3DCreateFromFile(String path) {
407        validate();
408        return rsnFileA3DCreateFromFile(mContext, path);
409    }
410    native int  rsnFileA3DCreateFromAsset(int con, AssetManager mgr, String path);
411    synchronized int nFileA3DCreateFromAsset(AssetManager mgr, String path) {
412        validate();
413        return rsnFileA3DCreateFromAsset(mContext, mgr, path);
414    }
415    native int  rsnFileA3DGetNumIndexEntries(int con, int fileA3D);
416    synchronized int nFileA3DGetNumIndexEntries(int fileA3D) {
417        validate();
418        return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
419    }
420    native void rsnFileA3DGetIndexEntries(int con, int fileA3D, int numEntries, int[] IDs, String[] names);
421    synchronized void nFileA3DGetIndexEntries(int fileA3D, int numEntries, int[] IDs, String[] names) {
422        validate();
423        rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
424    }
425    native int  rsnFileA3DGetEntryByIndex(int con, int fileA3D, int index);
426    synchronized int nFileA3DGetEntryByIndex(int fileA3D, int index) {
427        validate();
428        return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
429    }
430
431    native int  rsnFontCreateFromFile(int con, String fileName, float size, int dpi);
432    synchronized int nFontCreateFromFile(String fileName, float size, int dpi) {
433        validate();
434        return rsnFontCreateFromFile(mContext, fileName, size, dpi);
435    }
436    native int  rsnFontCreateFromAssetStream(int con, String name, float size, int dpi, int assetStream);
437    synchronized int nFontCreateFromAssetStream(String name, float size, int dpi, int assetStream) {
438        validate();
439        return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
440    }
441    native int  rsnFontCreateFromAsset(int con, AssetManager mgr, String path, float size, int dpi);
442    synchronized int nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
443        validate();
444        return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
445    }
446
447
448    native void rsnScriptBindAllocation(int con, int script, int alloc, int slot);
449    synchronized void nScriptBindAllocation(int script, int alloc, int slot) {
450        validate();
451        rsnScriptBindAllocation(mContext, script, alloc, slot);
452    }
453    native void rsnScriptSetTimeZone(int con, int script, byte[] timeZone);
454    synchronized void nScriptSetTimeZone(int script, byte[] timeZone) {
455        validate();
456        rsnScriptSetTimeZone(mContext, script, timeZone);
457    }
458    native void rsnScriptInvoke(int con, int id, int slot);
459    synchronized void nScriptInvoke(int id, int slot) {
460        validate();
461        rsnScriptInvoke(mContext, id, slot);
462    }
463    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout, byte[] params);
464    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout);
465    synchronized void nScriptForEach(int id, int slot, int ain, int aout, byte[] params) {
466        validate();
467        if (params == null) {
468            rsnScriptForEach(mContext, id, slot, ain, aout);
469        } else {
470            rsnScriptForEach(mContext, id, slot, ain, aout, params);
471        }
472    }
473    native void rsnScriptInvokeV(int con, int id, int slot, byte[] params);
474    synchronized void nScriptInvokeV(int id, int slot, byte[] params) {
475        validate();
476        rsnScriptInvokeV(mContext, id, slot, params);
477    }
478    native void rsnScriptSetVarI(int con, int id, int slot, int val);
479    synchronized void nScriptSetVarI(int id, int slot, int val) {
480        validate();
481        rsnScriptSetVarI(mContext, id, slot, val);
482    }
483    native void rsnScriptSetVarJ(int con, int id, int slot, long val);
484    synchronized void nScriptSetVarJ(int id, int slot, long val) {
485        validate();
486        rsnScriptSetVarJ(mContext, id, slot, val);
487    }
488    native void rsnScriptSetVarF(int con, int id, int slot, float val);
489    synchronized void nScriptSetVarF(int id, int slot, float val) {
490        validate();
491        rsnScriptSetVarF(mContext, id, slot, val);
492    }
493    native void rsnScriptSetVarD(int con, int id, int slot, double val);
494    synchronized void nScriptSetVarD(int id, int slot, double val) {
495        validate();
496        rsnScriptSetVarD(mContext, id, slot, val);
497    }
498    native void rsnScriptSetVarV(int con, int id, int slot, byte[] val);
499    synchronized void nScriptSetVarV(int id, int slot, byte[] val) {
500        validate();
501        rsnScriptSetVarV(mContext, id, slot, val);
502    }
503    native void rsnScriptSetVarObj(int con, int id, int slot, int val);
504    synchronized void nScriptSetVarObj(int id, int slot, int val) {
505        validate();
506        rsnScriptSetVarObj(mContext, id, slot, val);
507    }
508
509    native int  rsnScriptCCreate(int con, String resName, String cacheDir,
510                                 byte[] script, int length);
511    synchronized int nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
512        validate();
513        return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
514    }
515
516    native int  rsnSamplerCreate(int con, int magFilter, int minFilter,
517                                 int wrapS, int wrapT, int wrapR, float aniso);
518    synchronized int nSamplerCreate(int magFilter, int minFilter,
519                                 int wrapS, int wrapT, int wrapR, float aniso) {
520        validate();
521        return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
522    }
523
524    native int  rsnProgramStoreCreate(int con, boolean r, boolean g, boolean b, boolean a,
525                                      boolean depthMask, boolean dither,
526                                      int srcMode, int dstMode, int depthFunc);
527    synchronized int nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
528                                         boolean depthMask, boolean dither,
529                                         int srcMode, int dstMode, int depthFunc) {
530        validate();
531        return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
532                                     dstMode, depthFunc);
533    }
534
535    native int  rsnProgramRasterCreate(int con, boolean pointSprite, int cullMode);
536    synchronized int nProgramRasterCreate(boolean pointSprite, int cullMode) {
537        validate();
538        return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
539    }
540
541    native void rsnProgramBindConstants(int con, int pv, int slot, int mID);
542    synchronized void nProgramBindConstants(int pv, int slot, int mID) {
543        validate();
544        rsnProgramBindConstants(mContext, pv, slot, mID);
545    }
546    native void rsnProgramBindTexture(int con, int vpf, int slot, int a);
547    synchronized void nProgramBindTexture(int vpf, int slot, int a) {
548        validate();
549        rsnProgramBindTexture(mContext, vpf, slot, a);
550    }
551    native void rsnProgramBindSampler(int con, int vpf, int slot, int s);
552    synchronized void nProgramBindSampler(int vpf, int slot, int s) {
553        validate();
554        rsnProgramBindSampler(mContext, vpf, slot, s);
555    }
556    native int  rsnProgramFragmentCreate(int con, String shader, int[] params);
557    synchronized int nProgramFragmentCreate(String shader, int[] params) {
558        validate();
559        return rsnProgramFragmentCreate(mContext, shader, params);
560    }
561    native int  rsnProgramVertexCreate(int con, String shader, int[] params);
562    synchronized int nProgramVertexCreate(String shader, int[] params) {
563        validate();
564        return rsnProgramVertexCreate(mContext, shader, params);
565    }
566
567    native int  rsnMeshCreate(int con, int[] vtx, int[] idx, int[] prim);
568    synchronized int nMeshCreate(int[] vtx, int[] idx, int[] prim) {
569        validate();
570        return rsnMeshCreate(mContext, vtx, idx, prim);
571    }
572    native int  rsnMeshGetVertexBufferCount(int con, int id);
573    synchronized int nMeshGetVertexBufferCount(int id) {
574        validate();
575        return rsnMeshGetVertexBufferCount(mContext, id);
576    }
577    native int  rsnMeshGetIndexCount(int con, int id);
578    synchronized int nMeshGetIndexCount(int id) {
579        validate();
580        return rsnMeshGetIndexCount(mContext, id);
581    }
582    native void rsnMeshGetVertices(int con, int id, int[] vtxIds, int vtxIdCount);
583    synchronized void nMeshGetVertices(int id, int[] vtxIds, int vtxIdCount) {
584        validate();
585        rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
586    }
587    native void rsnMeshGetIndices(int con, int id, int[] idxIds, int[] primitives, int vtxIdCount);
588    synchronized void nMeshGetIndices(int id, int[] idxIds, int[] primitives, int vtxIdCount) {
589        validate();
590        rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
591    }
592
593    native int  rsnPathCreate(int con, int prim, boolean isStatic, int vtx, int loop, float q);
594    synchronized int nPathCreate(int prim, boolean isStatic, int vtx, int loop, float q) {
595        validate();
596        return rsnPathCreate(mContext, prim, isStatic, vtx, loop, q);
597    }
598
599    int     mDev;
600    int     mContext;
601    @SuppressWarnings({"FieldCanBeLocal"})
602    MessageThread mMessageThread;
603
604    Element mElement_U8;
605    Element mElement_I8;
606    Element mElement_U16;
607    Element mElement_I16;
608    Element mElement_U32;
609    Element mElement_I32;
610    Element mElement_U64;
611    Element mElement_I64;
612    Element mElement_F32;
613    Element mElement_F64;
614    Element mElement_BOOLEAN;
615
616    Element mElement_ELEMENT;
617    Element mElement_TYPE;
618    Element mElement_ALLOCATION;
619    Element mElement_SAMPLER;
620    Element mElement_SCRIPT;
621    Element mElement_MESH;
622    Element mElement_PROGRAM_FRAGMENT;
623    Element mElement_PROGRAM_VERTEX;
624    Element mElement_PROGRAM_RASTER;
625    Element mElement_PROGRAM_STORE;
626
627    Element mElement_A_8;
628    Element mElement_RGB_565;
629    Element mElement_RGB_888;
630    Element mElement_RGBA_5551;
631    Element mElement_RGBA_4444;
632    Element mElement_RGBA_8888;
633
634    Element mElement_FLOAT_2;
635    Element mElement_FLOAT_3;
636    Element mElement_FLOAT_4;
637
638    Element mElement_DOUBLE_2;
639    Element mElement_DOUBLE_3;
640    Element mElement_DOUBLE_4;
641
642    Element mElement_UCHAR_2;
643    Element mElement_UCHAR_3;
644    Element mElement_UCHAR_4;
645
646    Element mElement_CHAR_2;
647    Element mElement_CHAR_3;
648    Element mElement_CHAR_4;
649
650    Element mElement_USHORT_2;
651    Element mElement_USHORT_3;
652    Element mElement_USHORT_4;
653
654    Element mElement_SHORT_2;
655    Element mElement_SHORT_3;
656    Element mElement_SHORT_4;
657
658    Element mElement_UINT_2;
659    Element mElement_UINT_3;
660    Element mElement_UINT_4;
661
662    Element mElement_INT_2;
663    Element mElement_INT_3;
664    Element mElement_INT_4;
665
666    Element mElement_ULONG_2;
667    Element mElement_ULONG_3;
668    Element mElement_ULONG_4;
669
670    Element mElement_LONG_2;
671    Element mElement_LONG_3;
672    Element mElement_LONG_4;
673
674    Element mElement_MATRIX_4X4;
675    Element mElement_MATRIX_3X3;
676    Element mElement_MATRIX_2X2;
677
678    Sampler mSampler_CLAMP_NEAREST;
679    Sampler mSampler_CLAMP_LINEAR;
680    Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
681    Sampler mSampler_WRAP_NEAREST;
682    Sampler mSampler_WRAP_LINEAR;
683    Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
684
685    ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
686    ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
687    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
688    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
689
690    ProgramRaster mProgramRaster_CULL_BACK;
691    ProgramRaster mProgramRaster_CULL_FRONT;
692    ProgramRaster mProgramRaster_CULL_NONE;
693
694    ///////////////////////////////////////////////////////////////////////////////////
695    //
696
697    /**
698     * Base class application should derive from for handling RS messages
699     * coming from their scripts.  When a script calls sendToClient the data
700     * fields will be filled in and then the run method called by a message
701     * handling thread.  This will occur some time after sendToClient completes
702     * in the script.
703     *
704     */
705    public static class RSMessageHandler implements Runnable {
706        protected int[] mData;
707        protected int mID;
708        protected int mLength;
709        public void run() {
710        }
711    }
712    /**
713     * If an application is expecting messages it should set this field to an
714     * instance of RSMessage.  This instance will receive all the user messages
715     * sent from sendToClient by scripts from this context.
716     *
717     */
718    RSMessageHandler mMessageCallback = null;
719
720    public void setMessageHandler(RSMessageHandler msg) {
721        mMessageCallback = msg;
722    }
723    public RSMessageHandler getMessageHandler() {
724        return mMessageCallback;
725    }
726
727    /**
728     * Runtime error base class.  An application should derive from this class
729     * if it wishes to install an error handler.  When errors occur at runtime
730     * the fields in this class will be filled and the run method called.
731     *
732     */
733    public static class RSErrorHandler implements Runnable {
734        protected String mErrorMessage;
735        protected int mErrorNum;
736        public void run() {
737        }
738    }
739
740    /**
741     * Application Error handler.  All runtime errors will be dispatched to the
742     * instance of RSAsyncError set here.  If this field is null a
743     * RSRuntimeException will instead be thrown with details about the error.
744     * This will cause program termaination.
745     *
746     */
747    RSErrorHandler mErrorCallback = null;
748
749    public void setErrorHandler(RSErrorHandler msg) {
750        mErrorCallback = msg;
751    }
752    public RSErrorHandler getErrorHandler() {
753        return mErrorCallback;
754    }
755
756    /**
757     * RenderScript worker threads priority enumeration.  The default value is
758     * NORMAL.  Applications wishing to do background processing such as
759     * wallpapers should set their priority to LOW to avoid starving forground
760     * processes.
761     */
762    public enum Priority {
763        LOW (Process.THREAD_PRIORITY_BACKGROUND + (5 * Process.THREAD_PRIORITY_LESS_FAVORABLE)),
764        NORMAL (Process.THREAD_PRIORITY_DISPLAY);
765
766        int mID;
767        Priority(int id) {
768            mID = id;
769        }
770    }
771
772    void validate() {
773        if (mContext == 0) {
774            throw new RSInvalidStateException("Calling RS with no Context active.");
775        }
776    }
777
778
779    /**
780     * Change the priority of the worker threads for this context.
781     *
782     * @param p New priority to be set.
783     */
784    public void setPriority(Priority p) {
785        validate();
786        nContextSetPriority(p.mID);
787    }
788
789    static class MessageThread extends Thread {
790        RenderScript mRS;
791        boolean mRun = true;
792        int[] mAuxData = new int[2];
793
794        static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
795        static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
796        static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
797        static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
798        static final int RS_MESSAGE_TO_CLIENT_USER = 4;
799
800        static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
801
802        MessageThread(RenderScript rs) {
803            super("RSMessageThread");
804            mRS = rs;
805
806        }
807
808        public void run() {
809            // This function is a temporary solution.  The final solution will
810            // used typed allocations where the message id is the type indicator.
811            int[] rbuf = new int[16];
812            mRS.nContextInitToClient(mRS.mContext);
813            while(mRun) {
814                rbuf[0] = 0;
815                int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
816                int size = mAuxData[1];
817                int subID = mAuxData[0];
818
819                if (msg == RS_MESSAGE_TO_CLIENT_USER) {
820                    if ((size>>2) >= rbuf.length) {
821                        rbuf = new int[(size + 3) >> 2];
822                    }
823                    if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
824                        RS_MESSAGE_TO_CLIENT_USER) {
825                        throw new RSDriverException("Error processing message from Renderscript.");
826                    }
827
828                    if(mRS.mMessageCallback != null) {
829                        mRS.mMessageCallback.mData = rbuf;
830                        mRS.mMessageCallback.mID = subID;
831                        mRS.mMessageCallback.mLength = size;
832                        mRS.mMessageCallback.run();
833                    } else {
834                        throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
835                    }
836                    continue;
837                }
838
839                if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
840                    String e = mRS.nContextGetErrorMessage(mRS.mContext);
841
842                    if (subID >= RS_ERROR_FATAL_UNKNOWN) {
843                        throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
844                    }
845
846                    if(mRS.mErrorCallback != null) {
847                        mRS.mErrorCallback.mErrorMessage = e;
848                        mRS.mErrorCallback.mErrorNum = subID;
849                        mRS.mErrorCallback.run();
850                    } else {
851                        // Do not throw here. In these cases, we do not have
852                        // a fatal error.
853                    }
854                    continue;
855                }
856
857                // 2: teardown.
858                // But we want to avoid starving other threads during
859                // teardown by yielding until the next line in the destructor
860                // can execute to set mRun = false
861                try {
862                    sleep(1, 0);
863                } catch(InterruptedException e) {
864                }
865            }
866            Log.d(LOG_TAG, "MessageThread exiting.");
867        }
868    }
869
870    RenderScript(Context ctx) {
871        mApplicationContext = ctx.getApplicationContext();
872    }
873
874    /**
875     * Gets the application context associated with the RenderScript context.
876     *
877     * @return The application context.
878     */
879    public final Context getApplicationContext() {
880        return mApplicationContext;
881    }
882
883    static int getTargetSdkVersion(Context ctx) {
884        return ctx.getApplicationInfo().targetSdkVersion;
885    }
886
887    /**
888     * Create a basic RenderScript context.
889     *
890     * @param ctx The context.
891     * @return RenderScript
892     */
893    public static RenderScript create(Context ctx) {
894        RenderScript rs = new RenderScript(ctx);
895
896        int sdkVersion = getTargetSdkVersion(ctx);
897
898        rs.mDev = rs.nDeviceCreate();
899        rs.mContext = rs.nContextCreate(rs.mDev, 0, sdkVersion);
900        if (rs.mContext == 0) {
901            throw new RSDriverException("Failed to create RS context.");
902        }
903        rs.mMessageThread = new MessageThread(rs);
904        rs.mMessageThread.start();
905        return rs;
906    }
907
908    /**
909     * Print the currently available debugging information about the state of
910     * the RS context to the log.
911     *
912     */
913    public void contextDump() {
914        validate();
915        nContextDump(0);
916    }
917
918    /**
919     * Wait for any commands in the fifo between the java bindings and native to
920     * be processed.
921     *
922     */
923    public void finish() {
924        nContextFinish();
925    }
926
927    /**
928     * Destroy this renderscript context.  Once this function is called its no
929     * longer legal to use this or any objects created by this context.
930     *
931     */
932    public void destroy() {
933        validate();
934        nContextDeinitToClient(mContext);
935        mMessageThread.mRun = false;
936        try {
937            mMessageThread.join();
938        } catch(InterruptedException e) {
939        }
940
941        nContextDestroy();
942        mContext = 0;
943
944        nDeviceDestroy(mDev);
945        mDev = 0;
946    }
947
948    boolean isAlive() {
949        return mContext != 0;
950    }
951
952    int safeID(BaseObj o) {
953        if(o != null) {
954            return o.getID();
955        }
956        return 0;
957    }
958}
959