RenderScript.java revision e29f3e74f71ea730519ff8ae1d8dd4c1630bbaf9
1/*
2 * Copyright (C) 2008 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.graphics.Bitmap;
22import android.graphics.BitmapFactory;
23import android.util.Config;
24import android.util.Log;
25import android.view.Surface;
26
27
28/**
29 * @hide
30 *
31 **/
32public class RenderScript {
33    static final String LOG_TAG = "RenderScript_jni";
34    protected static final boolean DEBUG  = false;
35    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
36    protected static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
37
38
39
40     /*
41     * We use a class initializer to allow the native code to cache some
42     * field offsets.
43     */
44    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
45    protected static boolean sInitialized;
46    native protected static void _nInit();
47
48
49    static {
50        sInitialized = false;
51        try {
52            System.loadLibrary("rs_jni");
53            _nInit();
54            sInitialized = true;
55        } catch (UnsatisfiedLinkError e) {
56            Log.d(LOG_TAG, "RenderScript JNI library not found!");
57        }
58    }
59
60    native void nInitElements(int a8, int rgba4444, int rgba8888, int rgb565);
61
62    native int  nDeviceCreate();
63    native void nDeviceDestroy(int dev);
64    native void nDeviceSetConfig(int dev, int param, int value);
65    native int  nContextCreateGL(int dev, int ver, boolean useDepth);
66    native int  nContextCreate(int dev, int ver);
67    native void nContextDestroy(int con);
68    native void nContextSetSurface(int w, int h, Surface sur);
69    native void nContextSetPriority(int p);
70    native void nContextDump(int bits);
71
72    native void nContextBindRootScript(int script);
73    native void nContextBindSampler(int sampler, int slot);
74    native void nContextBindProgramStore(int pfs);
75    native void nContextBindProgramFragment(int pf);
76    native void nContextBindProgramVertex(int pf);
77    native void nContextBindProgramRaster(int pr);
78    native void nContextPause();
79    native void nContextResume();
80    native int nContextGetMessage(int[] data, boolean wait);
81    native void nContextInitToClient();
82    native void nContextDeinitToClient();
83
84    native void nAssignName(int obj, byte[] name);
85    native void nObjDestroy(int id);
86    native void nObjDestroyOOB(int id);
87    native int  nFileOpen(byte[] name);
88
89
90    native int  nElementCreate(int type, int kind, boolean norm, int vecSize);
91    native int  nElementCreate2(int[] elements, String[] names);
92
93    native void nTypeBegin(int elementID);
94    native void nTypeAdd(int dim, int val);
95    native int  nTypeCreate();
96    native void nTypeFinalDestroy(Type t);
97    native void nTypeSetupFields(Type t, int[] types, int[] bits, Field[] IDs);
98
99    native int  nAllocationCreateTyped(int type);
100    native int  nAllocationCreateFromBitmap(int dstFmt, boolean genMips, Bitmap bmp);
101    native int  nAllocationCreateBitmapRef(int type, Bitmap bmp);
102    native int  nAllocationCreateFromBitmapBoxed(int dstFmt, boolean genMips, Bitmap bmp);
103    native int  nAllocationCreateFromAssetStream(int dstFmt, boolean genMips, int assetStream);
104
105    native void nAllocationUploadToTexture(int alloc, boolean genMips, int baseMioLevel);
106    native void nAllocationUploadToBufferObject(int alloc);
107
108    native void nAllocationSubData1D(int id, int off, int count, int[] d, int sizeBytes);
109    native void nAllocationSubData1D(int id, int off, int count, short[] d, int sizeBytes);
110    native void nAllocationSubData1D(int id, int off, int count, byte[] d, int sizeBytes);
111    native void nAllocationSubData1D(int id, int off, int count, float[] d, int sizeBytes);
112
113    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, int[] d, int sizeBytes);
114    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, float[] d, int sizeBytes);
115    native void nAllocationRead(int id, int[] d);
116    native void nAllocationRead(int id, float[] d);
117    native void nAllocationSubDataFromObject(int id, Type t, int offset, Object o);
118    native void nAllocationSubReadFromObject(int id, Type t, int offset, Object o);
119
120    native int  nFileA3DCreateFromAssetStream(int assetStream);
121    native int  nFileA3DGetNumIndexEntries(int fileA3D);
122    native void nFileA3DGetIndexEntries(int fileA3D, int numEntries, int[] IDs, String[] names);
123    native int  nFileA3DGetEntryByIndex(int fileA3D, int index);
124
125    native void nAdapter1DBindAllocation(int ad, int alloc);
126    native void nAdapter1DSetConstraint(int ad, int dim, int value);
127    native void nAdapter1DData(int ad, int[] d);
128    native void nAdapter1DData(int ad, float[] d);
129    native void nAdapter1DSubData(int ad, int off, int count, int[] d);
130    native void nAdapter1DSubData(int ad, int off, int count, float[] d);
131    native int  nAdapter1DCreate();
132
133    native void nAdapter2DBindAllocation(int ad, int alloc);
134    native void nAdapter2DSetConstraint(int ad, int dim, int value);
135    native void nAdapter2DData(int ad, int[] d);
136    native void nAdapter2DData(int ad, float[] d);
137    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, int[] d);
138    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, float[] d);
139    native int  nAdapter2DCreate();
140
141    native void nScriptBindAllocation(int script, int alloc, int slot);
142    native void nScriptSetTimeZone(int script, byte[] timeZone);
143    native void nScriptInvoke(int id, int slot);
144    native void nScriptInvokeData(int id, int slot);
145    native void nScriptInvokeV(int id, int slot, byte[] params);
146    native void nScriptSetVarI(int id, int slot, int val);
147    native void nScriptSetVarF(int id, int slot, float val);
148    native void nScriptSetVarV(int id, int slot, byte[] val);
149
150    native void nScriptCBegin();
151    native void nScriptCSetScript(byte[] script, int offset, int length);
152    native int  nScriptCCreate();
153
154    native void nSamplerBegin();
155    native void nSamplerSet(int param, int value);
156    native int  nSamplerCreate();
157
158    native void nProgramStoreBegin(int in, int out);
159    native void nProgramStoreDepthFunc(int func);
160    native void nProgramStoreDepthMask(boolean enable);
161    native void nProgramStoreColorMask(boolean r, boolean g, boolean b, boolean a);
162    native void nProgramStoreBlendFunc(int src, int dst);
163    native void nProgramStoreDither(boolean enable);
164    native int  nProgramStoreCreate();
165
166    native int  nProgramRasterCreate(int in, int out, boolean pointSmooth, boolean lineSmooth, boolean pointSprite);
167    native void nProgramRasterSetLineWidth(int pr, float v);
168    native void nProgramRasterSetPointSize(int pr, float v);
169
170    native void nProgramBindConstants(int pv, int slot, int mID);
171    native void nProgramBindTexture(int vpf, int slot, int a);
172    native void nProgramBindSampler(int vpf, int slot, int s);
173
174    native int  nProgramFragmentCreate(int[] params);
175    native int  nProgramFragmentCreate2(String shader, int[] params);
176
177    native int  nProgramVertexCreate(boolean texMat);
178    native int  nProgramVertexCreate2(String shader, int[] params);
179
180    native void nLightBegin();
181    native void nLightSetIsMono(boolean isMono);
182    native void nLightSetIsLocal(boolean isLocal);
183    native int  nLightCreate();
184    native void nLightSetColor(int l, float r, float g, float b);
185    native void nLightSetPosition(int l, float x, float y, float z);
186
187    native int  nSimpleMeshCreate(int batchID, int idxID, int[] vtxID, int prim);
188    native void nSimpleMeshBindVertex(int id, int alloc, int slot);
189    native void nSimpleMeshBindIndex(int id, int alloc);
190
191    native void nAnimationBegin(int attribCount, int keyframeCount);
192    native void nAnimationAdd(float time, float[] attribs);
193    native int  nAnimationCreate();
194
195    protected int     mDev;
196    protected int     mContext;
197    @SuppressWarnings({"FieldCanBeLocal"})
198    protected MessageThread mMessageThread;
199
200    Element mElement_U8;
201    Element mElement_I8;
202    Element mElement_U16;
203    Element mElement_I16;
204    Element mElement_U32;
205    Element mElement_I32;
206    Element mElement_F32;
207
208    Element mElement_ELEMENT;
209    Element mElement_TYPE;
210    Element mElement_ALLOCATION;
211    Element mElement_SAMPLER;
212    Element mElement_SCRIPT;
213    Element mElement_MESH;
214    Element mElement_PROGRAM_FRAGMENT;
215    Element mElement_PROGRAM_VERTEX;
216    Element mElement_PROGRAM_RASTER;
217    Element mElement_PROGRAM_STORE;
218
219    Element mElement_A_8;
220    Element mElement_RGB_565;
221    Element mElement_RGB_888;
222    Element mElement_RGBA_5551;
223    Element mElement_RGBA_4444;
224    Element mElement_RGBA_8888;
225
226    Element mElement_FLOAT_2;
227    Element mElement_FLOAT_3;
228    Element mElement_FLOAT_4;
229    Element mElement_UCHAR_4;
230
231    Sampler mSampler_CLAMP_NEAREST;
232    Sampler mSampler_CLAMP_LINEAR;
233    Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
234    Sampler mSampler_WRAP_NEAREST;
235    Sampler mSampler_WRAP_LINEAR;
236    Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
237
238    ///////////////////////////////////////////////////////////////////////////////////
239    //
240
241    public static class RSMessage implements Runnable {
242        protected int[] mData;
243        protected int mID;
244        public void run() {
245        }
246    }
247    public RSMessage mMessageCallback = null;
248
249    public enum Priority {
250        LOW (5),     //ANDROID_PRIORITY_BACKGROUND + 5
251        NORMAL (-4);  //ANDROID_PRIORITY_DISPLAY
252
253        int mID;
254        Priority(int id) {
255            mID = id;
256        }
257    }
258
259    void validate() {
260        if (mContext == 0) {
261            throw new IllegalStateException("Calling RS with no Context active.");
262        }
263    }
264
265    public void contextSetPriority(Priority p) {
266        validate();
267        nContextSetPriority(p.mID);
268    }
269
270    protected static class MessageThread extends Thread {
271        RenderScript mRS;
272        boolean mRun = true;
273
274        MessageThread(RenderScript rs) {
275            super("RSMessageThread");
276            mRS = rs;
277
278        }
279
280        public void run() {
281            // This function is a temporary solution.  The final solution will
282            // used typed allocations where the message id is the type indicator.
283            int[] rbuf = new int[16];
284            mRS.nContextInitToClient();
285            while(mRun) {
286                int msg = mRS.nContextGetMessage(rbuf, true);
287                if (msg == 0) {
288                    // Should only happen during teardown.
289                    // But we want to avoid starving other threads during
290                    // teardown by yielding until the next line in the destructor
291                    // can execute to set mRun = false
292                    try {
293                        sleep(1, 0);
294                    } catch(InterruptedException e) {
295                    }
296                }
297                if(mRS.mMessageCallback != null) {
298                    mRS.mMessageCallback.mData = rbuf;
299                    mRS.mMessageCallback.mID = msg;
300                    mRS.mMessageCallback.run();
301                }
302            }
303            Log.d(LOG_TAG, "MessageThread exiting.");
304        }
305    }
306
307    protected RenderScript() {
308    }
309
310    public static RenderScript create() {
311        RenderScript rs = new RenderScript();
312
313        rs.mDev = rs.nDeviceCreate();
314        rs.mContext = rs.nContextCreate(rs.mDev, 0);
315        rs.mMessageThread = new MessageThread(rs);
316        rs.mMessageThread.start();
317        Element.initPredefined(rs);
318        return rs;
319    }
320
321    public void contextDump(int bits) {
322        validate();
323        nContextDump(bits);
324    }
325
326    public void destroy() {
327        validate();
328        nContextDeinitToClient();
329        mMessageThread.mRun = false;
330
331        nContextDestroy(mContext);
332        mContext = 0;
333
334        nDeviceDestroy(mDev);
335        mDev = 0;
336    }
337
338    boolean isAlive() {
339        return mContext != 0;
340    }
341
342    ///////////////////////////////////////////////////////////////////////////////////
343    // Root state
344
345    protected int safeID(BaseObj o) {
346        if(o != null) {
347            return o.mID;
348        }
349        return 0;
350    }
351}
352
353
354