RenderScript.java revision 7d787b4722eaeb79cab42c36060336e092b77b5f
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    private static final boolean DEBUG  = false;
35    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
36    private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
37    int mWidth;
38    int mHeight;
39
40
41
42     /*
43     * We use a class initializer to allow the native code to cache some
44     * field offsets.
45     */
46    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
47    private static boolean sInitialized;
48    native private static void _nInit();
49
50
51    static {
52        sInitialized = false;
53        try {
54            System.loadLibrary("rs_jni");
55            _nInit();
56            sInitialized = true;
57        } catch (UnsatisfiedLinkError e) {
58            Log.d(LOG_TAG, "RenderScript JNI library not found!");
59        }
60    }
61
62    native void nInitElements(int a8, int rgba4444, int rgba8888, int rgb565);
63
64    native int  nDeviceCreate();
65    native void nDeviceDestroy(int dev);
66    native void nDeviceSetConfig(int dev, int param, int value);
67    native int  nContextCreate(int dev, int ver, boolean useDepth);
68    native void nContextDestroy(int con);
69    native void nContextSetSurface(int w, int h, Surface sur);
70    native void nContextSetPriority(int p);
71
72    native void nContextBindRootScript(int script);
73    native void nContextBindSampler(int sampler, int slot);
74    native void nContextBindProgramFragmentStore(int pfs);
75    native void nContextBindProgramFragment(int pf);
76    native void nContextBindProgramVertex(int pf);
77    native void nContextBindProgramRaster(int pr);
78    native void nContextAddDefineI32(String name, int value);
79    native void nContextAddDefineF(String name, float value);
80    native void nContextPause();
81    native void nContextResume();
82    native int nContextGetMessage(int[] data, boolean wait);
83    native void nContextInitToClient();
84    native void nContextDeinitToClient();
85
86    native void nAssignName(int obj, byte[] name);
87    native void nObjDestroy(int id);
88    native void nObjDestroyOOB(int id);
89    native int  nFileOpen(byte[] name);
90
91    native void nElementBegin();
92    native void nElementAdd(int kind, int type, boolean norm, int bits, String s);
93    native int  nElementCreate();
94
95    native void nTypeBegin(int elementID);
96    native void nTypeAdd(int dim, int val);
97    native int  nTypeCreate();
98    native void nTypeFinalDestroy(Type t);
99    native void nTypeSetupFields(Type t, int[] types, int[] bits, Field[] IDs);
100
101    native int  nAllocationCreateTyped(int type);
102    native int  nAllocationCreateFromBitmap(int dstFmt, boolean genMips, Bitmap bmp);
103    native int  nAllocationCreateFromBitmapBoxed(int dstFmt, boolean genMips, Bitmap bmp);
104    native int  nAllocationCreateFromAssetStream(int dstFmt, boolean genMips, int assetStream);
105
106    native void nAllocationUploadToTexture(int alloc, int baseMioLevel);
107    native void nAllocationUploadToBufferObject(int alloc);
108
109    native void nAllocationSubData1D(int id, int off, int count, int[] d, int sizeBytes);
110    native void nAllocationSubData1D(int id, int off, int count, short[] d, int sizeBytes);
111    native void nAllocationSubData1D(int id, int off, int count, byte[] d, int sizeBytes);
112    native void nAllocationSubData1D(int id, int off, int count, float[] d, int sizeBytes);
113
114    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, int[] d, int sizeBytes);
115    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, float[] d, int sizeBytes);
116    native void nAllocationRead(int id, int[] d);
117    native void nAllocationRead(int id, float[] d);
118    native void nAllocationSubDataFromObject(int id, Type t, int offset, Object o);
119    native void nAllocationSubReadFromObject(int id, Type t, int offset, Object o);
120
121    native void nAdapter1DBindAllocation(int ad, int alloc);
122    native void nAdapter1DSetConstraint(int ad, int dim, int value);
123    native void nAdapter1DData(int ad, int[] d);
124    native void nAdapter1DData(int ad, float[] d);
125    native void nAdapter1DSubData(int ad, int off, int count, int[] d);
126    native void nAdapter1DSubData(int ad, int off, int count, float[] d);
127    native int  nAdapter1DCreate();
128
129    native void nAdapter2DBindAllocation(int ad, int alloc);
130    native void nAdapter2DSetConstraint(int ad, int dim, int value);
131    native void nAdapter2DData(int ad, int[] d);
132    native void nAdapter2DData(int ad, float[] d);
133    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, int[] d);
134    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, float[] d);
135    native int  nAdapter2DCreate();
136
137    native void nScriptBindAllocation(int script, int alloc, int slot);
138    native void nScriptSetClearColor(int script, float r, float g, float b, float a);
139    native void nScriptSetClearDepth(int script, float depth);
140    native void nScriptSetClearStencil(int script, int stencil);
141    native void nScriptSetTimeZone(int script, byte[] timeZone);
142    native void nScriptSetType(int type, boolean writable, String name, int slot);
143    native void nScriptSetRoot(boolean isRoot);
144    native void nScriptSetInvokable(String name, int slot);
145    native void nScriptInvoke(int id, int slot);
146
147    native void nScriptCBegin();
148    native void nScriptCSetScript(byte[] script, int offset, int length);
149    native int  nScriptCCreate();
150    native void nScriptCAddDefineI32(String name, int value);
151    native void nScriptCAddDefineF(String name, float value);
152
153    native void nSamplerBegin();
154    native void nSamplerSet(int param, int value);
155    native int  nSamplerCreate();
156
157    native void nProgramFragmentStoreBegin(int in, int out);
158    native void nProgramFragmentStoreDepthFunc(int func);
159    native void nProgramFragmentStoreDepthMask(boolean enable);
160    native void nProgramFragmentStoreColorMask(boolean r, boolean g, boolean b, boolean a);
161    native void nProgramFragmentStoreBlendFunc(int src, int dst);
162    native void nProgramFragmentStoreDither(boolean enable);
163    native int  nProgramFragmentStoreCreate();
164
165    native int  nProgramRasterCreate(int in, int out, boolean pointSmooth, boolean lineSmooth, boolean pointSprite);
166    native void nProgramRasterSetLineWidth(int pr, float v);
167    native void nProgramRasterSetPointSize(int pr, float v);
168
169    native void nProgramFragmentBegin(int in, int out, boolean pointSpriteEnable);
170    native void nProgramFragmentBindTexture(int vpf, int slot, int a);
171    native void nProgramFragmentBindSampler(int vpf, int slot, int s);
172    native void nProgramFragmentSetSlot(int slot, boolean enable, int env, int vt);
173    native int  nProgramFragmentCreate();
174
175    native void nProgramVertexBindAllocation(int pv, int mID);
176    native void nProgramVertexBegin(int inID, int outID);
177    native void nProgramVertexSetTextureMatrixEnable(boolean enable);
178    native void nProgramVertexAddLight(int id);
179    native int  nProgramVertexCreate();
180
181    native void nLightBegin();
182    native void nLightSetIsMono(boolean isMono);
183    native void nLightSetIsLocal(boolean isLocal);
184    native int  nLightCreate();
185    native void nLightSetColor(int l, float r, float g, float b);
186    native void nLightSetPosition(int l, float x, float y, float z);
187
188    native int  nSimpleMeshCreate(int batchID, int idxID, int[] vtxID, int prim);
189    native void nSimpleMeshBindVertex(int id, int alloc, int slot);
190    native void nSimpleMeshBindIndex(int id, int alloc);
191
192    native void nAnimationBegin(int attribCount, int keyframeCount);
193    native void nAnimationAdd(float time, float[] attribs);
194    native int  nAnimationCreate();
195
196    private int     mDev;
197    private int     mContext;
198    @SuppressWarnings({"FieldCanBeLocal"})
199    private Surface mSurface;
200    private MessageThread mMessageThread;
201
202
203    Element mElement_USER_U8;
204    Element mElement_USER_I8;
205    Element mElement_USER_U16;
206    Element mElement_USER_I16;
207    Element mElement_USER_U32;
208    Element mElement_USER_I32;
209    Element mElement_USER_FLOAT;
210
211    Element mElement_A_8;
212    Element mElement_RGB_565;
213    Element mElement_RGB_888;
214    Element mElement_RGBA_5551;
215    Element mElement_RGBA_4444;
216    Element mElement_RGBA_8888;
217
218    Element mElement_INDEX_16;
219    Element mElement_XY_F32;
220    Element mElement_XYZ_F32;
221
222
223    ///////////////////////////////////////////////////////////////////////////////////
224    //
225
226    public static class RSMessage implements Runnable {
227        protected int[] mData;
228        protected int mID;
229        public void run() {
230        }
231    }
232    public RSMessage mMessageCallback = null;
233
234    public enum Priority {
235        LOW (5),     //ANDROID_PRIORITY_BACKGROUND + 5
236        NORMAL (-4);  //ANDROID_PRIORITY_DISPLAY
237
238        int mID;
239        Priority(int id) {
240            mID = id;
241        }
242    }
243
244    public void contextSetPriority(Priority p) {
245        nContextSetPriority(p.mID);
246    }
247
248    private static class MessageThread extends Thread {
249        RenderScript mRS;
250        boolean mRun = true;
251
252        MessageThread(RenderScript rs) {
253            super("RSMessageThread");
254            mRS = rs;
255
256        }
257
258        public void run() {
259            // This function is a temporary solution.  The final solution will
260            // used typed allocations where the message id is the type indicator.
261            int[] rbuf = new int[16];
262            mRS.nContextInitToClient();
263            while(mRun) {
264                int msg = mRS.nContextGetMessage(rbuf, true);
265                if (msg == 0) {
266                    // Should only happen during teardown.
267                    // But we want to avoid starving other threads during
268                    // teardown by yielding until the next line in the destructor
269                    // can execute to set mRun = false
270                    try {
271                        sleep(1, 0);
272                    } catch(InterruptedException e) {
273                    }
274                }
275                if(mRS.mMessageCallback != null) {
276                    mRS.mMessageCallback.mData = rbuf;
277                    mRS.mMessageCallback.mID = msg;
278                    mRS.mMessageCallback.run();
279                }
280                //Log.d(LOG_TAG, "MessageThread msg " + msg + " v1 " + rbuf[0] + " v2 " + rbuf[1] + " v3 " +rbuf[2]);
281            }
282            Log.d(LOG_TAG, "MessageThread exiting.");
283        }
284    }
285
286    public RenderScript(boolean useDepth, boolean forceSW) {
287        mSurface = null;
288        mWidth = 0;
289        mHeight = 0;
290        mDev = nDeviceCreate();
291        if(forceSW) {
292            nDeviceSetConfig(mDev, 0, 1);
293        }
294        mContext = nContextCreate(mDev, 0, useDepth);
295        Element.initPredefined(this);
296        mMessageThread = new MessageThread(this);
297        mMessageThread.start();
298    }
299
300    public void contextSetSurface(int w, int h, Surface sur) {
301        mSurface = sur;
302        mWidth = w;
303        mHeight = h;
304        nContextSetSurface(w, h, mSurface);
305    }
306
307    public void destroy() {
308        nContextDeinitToClient();
309        mMessageThread.mRun = false;
310
311        nContextDestroy(mContext);
312        mContext = 0;
313
314        nDeviceDestroy(mDev);
315        mDev = 0;
316    }
317
318    boolean isAlive() {
319        return mContext != 0;
320    }
321
322    void pause() {
323        nContextPause();
324    }
325
326    void resume() {
327        nContextResume();
328    }
329
330    //////////////////////////////////////////////////////////////////////////////////
331    // File
332
333    public class File extends BaseObj {
334        File(int id) {
335            super(RenderScript.this);
336            mID = id;
337        }
338    }
339
340    public File fileOpen(String s) throws IllegalStateException, IllegalArgumentException
341    {
342        if(s.length() < 1) {
343            throw new IllegalArgumentException("fileOpen does not accept a zero length string.");
344        }
345
346        try {
347            byte[] bytes = s.getBytes("UTF-8");
348            int id = nFileOpen(bytes);
349            return new File(id);
350        } catch (java.io.UnsupportedEncodingException e) {
351            throw new RuntimeException(e);
352        }
353    }
354
355
356    ///////////////////////////////////////////////////////////////////////////////////
357    // Root state
358
359    private int safeID(BaseObj o) {
360        if(o != null) {
361            return o.mID;
362        }
363        return 0;
364    }
365
366    public void contextBindRootScript(Script s) {
367        nContextBindRootScript(safeID(s));
368    }
369
370    public void contextBindProgramFragmentStore(ProgramStore p) {
371        nContextBindProgramFragmentStore(safeID(p));
372    }
373
374    public void contextBindProgramFragment(ProgramFragment p) {
375        nContextBindProgramFragment(safeID(p));
376    }
377
378    public void contextBindProgramRaster(ProgramRaster p) {
379        nContextBindProgramRaster(safeID(p));
380    }
381
382    public void contextBindProgramVertex(ProgramVertex p) {
383        nContextBindProgramVertex(safeID(p));
384    }
385
386}
387
388
389