rsProgram.cpp revision 886f11ade9dde05485cb11c0d67d87f76a428f6c
1/*
2 * Copyright (C) 2009 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
17#ifndef ANDROID_RS_BUILD_FOR_HOST
18#include "rsContext.h"
19#include <GLES2/gl2.h>
20#include <GLES2/gl2ext.h>
21#else
22#include "rsContextHostStub.h"
23#include <OpenGL/gl.h>
24#include <OpenGL/glext.h>
25#endif //ANDROID_RS_BUILD_FOR_HOST
26
27#include "rsProgram.h"
28
29using namespace android;
30using namespace android::renderscript;
31
32Program::Program(Context *rsc) : ObjectBase(rsc)
33{
34    mAllocFile = __FILE__;
35    mAllocLine = __LINE__;
36    mDirty = true;
37    mShaderID = 0;
38    mAttribCount = 0;
39    mUniformCount = 0;
40    mTextureCount = 0;
41
42    mTextures = NULL;
43    mSamplers = NULL;
44    mInputElements = NULL;
45    mOutputElements = NULL;
46    mConstantTypes = NULL;
47    mInputCount = 0;
48    mOutputCount = 0;
49    mConstantCount = 0;
50    mIsValid = false;
51    mIsInternal = false;
52}
53
54Program::Program(Context *rsc, const char * shaderText, uint32_t shaderLength,
55                 const uint32_t * params, uint32_t paramLength) :
56    ObjectBase(rsc)
57{
58    mAllocFile = __FILE__;
59    mAllocLine = __LINE__;
60    mDirty = true;
61    mShaderID = 0;
62    mAttribCount = 0;
63    mUniformCount = 0;
64    mTextureCount = 0;
65
66    mInputCount = 0;
67    mOutputCount = 0;
68    mConstantCount = 0;
69
70    for (uint32_t ct=0; ct < paramLength; ct+=2) {
71        if (params[ct] == RS_PROGRAM_PARAM_INPUT) {
72            mInputCount++;
73        }
74        if (params[ct] == RS_PROGRAM_PARAM_OUTPUT) {
75            mOutputCount++;
76        }
77        if (params[ct] == RS_PROGRAM_PARAM_CONSTANT) {
78            mConstantCount++;
79        }
80        if (params[ct] == RS_PROGRAM_PARAM_TEXTURE_COUNT) {
81            mTextureCount = params[ct+1];
82        }
83    }
84
85    mTextures = new ObjectBaseRef<Allocation>[mTextureCount];
86    mSamplers = new ObjectBaseRef<Sampler>[mTextureCount];
87    mInputElements = new ObjectBaseRef<Element>[mInputCount];
88    mOutputElements = new ObjectBaseRef<Element>[mOutputCount];
89    mConstantTypes = new ObjectBaseRef<Type>[mConstantCount];
90
91    uint32_t input = 0;
92    uint32_t output = 0;
93    uint32_t constant = 0;
94    for (uint32_t ct=0; ct < paramLength; ct+=2) {
95        if (params[ct] == RS_PROGRAM_PARAM_INPUT) {
96            mInputElements[input++].set(reinterpret_cast<Element *>(params[ct+1]));
97        }
98        if (params[ct] == RS_PROGRAM_PARAM_OUTPUT) {
99            mOutputElements[output++].set(reinterpret_cast<Element *>(params[ct+1]));
100        }
101        if (params[ct] == RS_PROGRAM_PARAM_CONSTANT) {
102            mConstantTypes[constant++].set(reinterpret_cast<Type *>(params[ct+1]));
103        }
104    }
105    mIsInternal = false;
106    uint32_t internalTokenLen = strlen(RS_SHADER_INTERNAL);
107    if(shaderLength > internalTokenLen &&
108       strncmp(RS_SHADER_INTERNAL, shaderText, internalTokenLen) == 0) {
109        mIsInternal = true;
110        shaderText += internalTokenLen;
111        shaderLength -= internalTokenLen;
112    }
113    mUserShader.setTo(shaderText, shaderLength);
114}
115
116Program::~Program()
117{
118    for (uint32_t ct=0; ct < MAX_UNIFORMS; ct++) {
119        bindAllocation(NULL, NULL, ct);
120    }
121
122    for (uint32_t ct=0; ct < mTextureCount; ct++) {
123        bindTexture(NULL, ct, NULL);
124        bindSampler(NULL, ct, NULL);
125    }
126    delete[] mTextures;
127    delete[] mSamplers;
128    delete[] mInputElements;
129    delete[] mOutputElements;
130    delete[] mConstantTypes;
131    mInputCount = 0;
132    mOutputCount = 0;
133    mConstantCount = 0;
134}
135
136
137void Program::bindAllocation(Context *rsc, Allocation *alloc, uint32_t slot)
138{
139    if (alloc != NULL) {
140        if (slot >= mConstantCount) {
141            LOGE("Attempt to bind alloc at slot %u, on shader id %u, but const count is %u",
142                 slot, (uint32_t)this, mConstantCount);
143            rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation");
144            return;
145        }
146        if (!alloc->getType()->isEqual(mConstantTypes[slot].get())) {
147            LOGE("Attempt to bind alloc at slot %u, on shader id %u, but types mismatch",
148                 slot, (uint32_t)this);
149            rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation");
150            return;
151        }
152    }
153    if (mConstants[slot].get() == alloc) {
154        return;
155    }
156    if (mConstants[slot].get()) {
157        mConstants[slot].get()->removeProgramToDirty(this);
158    }
159    mConstants[slot].set(alloc);
160    if (alloc) {
161        alloc->addProgramToDirty(this);
162    }
163    mDirty = true;
164}
165
166void Program::bindTexture(Context *rsc, uint32_t slot, Allocation *a)
167{
168    if (slot >= mTextureCount) {
169        LOGE("Attempt to bind texture to slot %u but tex count is %u", slot, mTextureCount);
170        rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind texture");
171        return;
172    }
173
174    //LOGE("bindtex %i %p", slot, a);
175    mTextures[slot].set(a);
176    mDirty = true;
177}
178
179void Program::bindSampler(Context *rsc, uint32_t slot, Sampler *s)
180{
181    if (slot >= mTextureCount) {
182        LOGE("Attempt to bind sampler to slot %u but tex count is %u", slot, mTextureCount);
183        rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind sampler");
184        return;
185    }
186
187    mSamplers[slot].set(s);
188    mDirty = true;
189}
190
191String8 Program::getGLSLInputString() const
192{
193    String8 s;
194    for (uint32_t ct=0; ct < mInputCount; ct++) {
195        const Element *e = mInputElements[ct].get();
196        for (uint32_t field=0; field < e->getFieldCount(); field++) {
197            const Element *f = e->getField(field);
198
199            // Cannot be complex
200            rsAssert(!f->getFieldCount());
201            switch(f->getComponent().getVectorSize()) {
202            case 1: s.append("attribute float ATTRIB_"); break;
203            case 2: s.append("attribute vec2 ATTRIB_"); break;
204            case 3: s.append("attribute vec3 ATTRIB_"); break;
205            case 4: s.append("attribute vec4 ATTRIB_"); break;
206            default:
207                rsAssert(0);
208            }
209
210            s.append(e->getFieldName(field));
211            s.append(";\n");
212        }
213    }
214    return s;
215}
216
217String8 Program::getGLSLOutputString() const
218{
219    return String8();
220}
221
222String8 Program::getGLSLConstantString() const
223{
224    return String8();
225}
226
227
228void Program::createShader()
229{
230}
231
232bool Program::loadShader(Context *rsc, uint32_t type)
233{
234    mShaderID = glCreateShader(type);
235    rsAssert(mShaderID);
236
237    if (rsc->props.mLogShaders) {
238        LOGV("Loading shader type %x, ID %i", type, mShaderID);
239        LOGV("%s", mShader.string());
240    }
241
242    if (mShaderID) {
243        const char * ss = mShader.string();
244        glShaderSource(mShaderID, 1, &ss, NULL);
245        glCompileShader(mShaderID);
246
247        GLint compiled = 0;
248        glGetShaderiv(mShaderID, GL_COMPILE_STATUS, &compiled);
249        if (!compiled) {
250            GLint infoLen = 0;
251            glGetShaderiv(mShaderID, GL_INFO_LOG_LENGTH, &infoLen);
252            if (infoLen) {
253                char* buf = (char*) malloc(infoLen);
254                if (buf) {
255                    glGetShaderInfoLog(mShaderID, infoLen, NULL, buf);
256                    LOGE("Could not compile shader \n%s\n", buf);
257                    free(buf);
258                }
259                glDeleteShader(mShaderID);
260                mShaderID = 0;
261                rsc->setError(RS_ERROR_BAD_SHADER, "Error returned from GL driver loading shader text,");
262                return false;
263            }
264        }
265    }
266
267    if (rsc->props.mLogShaders) {
268        LOGV("--Shader load result %x ", glGetError());
269    }
270    mIsValid = true;
271    return true;
272}
273
274void Program::setShader(const char *txt, uint32_t len)
275{
276    mUserShader.setTo(txt, len);
277}
278
279void Program::appendUserConstants() {
280    for (uint32_t ct=0; ct < mConstantCount; ct++) {
281        const Element *e = mConstantTypes[ct]->getElement();
282        for (uint32_t field=0; field < e->getFieldCount(); field++) {
283            const Element *f = e->getField(field);
284            const char *fn = e->getFieldName(field);
285
286            if (fn[0] == '#') {
287                continue;
288            }
289
290            // Cannot be complex
291            rsAssert(!f->getFieldCount());
292            if(f->getType() == RS_TYPE_MATRIX_4X4) {
293                mShader.append("uniform mat4 UNI_");
294            }
295            else if(f->getType() == RS_TYPE_MATRIX_3X3) {
296                mShader.append("uniform mat3 UNI_");
297            }
298            else if(f->getType() == RS_TYPE_MATRIX_2X2) {
299                mShader.append("uniform mat2 UNI_");
300            }
301            else {
302                switch(f->getComponent().getVectorSize()) {
303                case 1: mShader.append("uniform float UNI_"); break;
304                case 2: mShader.append("uniform vec2 UNI_"); break;
305                case 3: mShader.append("uniform vec3 UNI_"); break;
306                case 4: mShader.append("uniform vec4 UNI_"); break;
307                default:
308                    rsAssert(0);
309                }
310            }
311
312            mShader.append(fn);
313            mShader.append(";\n");
314        }
315    }
316}
317
318void Program::setupUserConstants(Context *rsc, ShaderCache *sc, bool isFragment) {
319    uint32_t uidx = 0;
320    for (uint32_t ct=0; ct < mConstantCount; ct++) {
321        Allocation *alloc = mConstants[ct].get();
322        if (!alloc) {
323            LOGE("Attempting to set constants on shader id %u, but alloc at slot %u is not set", (uint32_t)this, ct);
324            rsc->setError(RS_ERROR_BAD_SHADER, "No constant allocation bound");
325            continue;
326        }
327
328        const uint8_t *data = static_cast<const uint8_t *>(alloc->getPtr());
329        const Element *e = mConstantTypes[ct]->getElement();
330        for (uint32_t field=0; field < e->getFieldCount(); field++) {
331            const Element *f = e->getField(field);
332            const char *fieldName = e->getFieldName(field);
333            // If this field is padding, skip it
334            if(fieldName[0] == '#') {
335                continue;
336            }
337
338            uint32_t offset = e->getFieldOffsetBytes(field);
339            const float *fd = reinterpret_cast<const float *>(&data[offset]);
340
341            int32_t slot = -1;
342            if(!isFragment) {
343                slot = sc->vtxUniformSlot(uidx);
344            }
345            else {
346                slot = sc->fragUniformSlot(uidx);
347            }
348
349            if(rsc->props.mLogShadersUniforms) {
350                LOGV("Uniform  slot=%i, offset=%i, constant=%i, field=%i, uidx=%i, name=%s", slot, offset, ct, field, uidx, fieldName);
351            }
352            if (slot >= 0) {
353                if(f->getType() == RS_TYPE_MATRIX_4X4) {
354                    if(rsc->props.mLogShadersUniforms) {
355                        LOGV("Matrix4x4");
356                        LOGV("{%f, %f, %f, %f",  fd[0], fd[4], fd[8], fd[12]);
357                        LOGV(" %f, %f, %f, %f",  fd[1], fd[5], fd[9], fd[13]);
358                        LOGV(" %f, %f, %f, %f",  fd[2], fd[6], fd[10], fd[14]);
359                        LOGV(" %f, %f, %f, %f}", fd[3], fd[7], fd[11], fd[15]);
360                    }
361                    glUniformMatrix4fv(slot, 1, GL_FALSE, fd);
362                }
363                else if(f->getType() == RS_TYPE_MATRIX_3X3) {
364                    if(rsc->props.mLogShadersUniforms) {
365                        LOGV("Matrix3x3");
366                        LOGV("{%f, %f, %f",  fd[0], fd[3], fd[6]);
367                        LOGV(" %f, %f, %f",  fd[1], fd[4], fd[7]);
368                        LOGV(" %f, %f, %f}", fd[2], fd[5], fd[8]);
369                    }
370                    glUniformMatrix3fv(slot, 1, GL_FALSE, fd);
371                }
372                else if(f->getType() == RS_TYPE_MATRIX_2X2) {
373                    if(rsc->props.mLogShadersUniforms){
374                        LOGV("Matrix2x2");
375                        LOGV("{%f, %f",  fd[0], fd[2]);
376                        LOGV(" %f, %f}", fd[1], fd[3]);
377                    }
378                    glUniformMatrix2fv(slot, 1, GL_FALSE, fd);
379                }
380                else {
381                    switch(f->getComponent().getVectorSize()) {
382                    case 1:
383                        if(rsc->props.mLogShadersUniforms) {
384                            LOGV("Uniform 1 = %f", fd[0]);
385                        }
386                        glUniform1fv(slot, 1, fd);
387                        break;
388                    case 2:
389                        if(rsc->props.mLogShadersUniforms) {
390                            LOGV("Uniform 2 = %f %f", fd[0], fd[1]);
391                        }
392                        glUniform2fv(slot, 1, fd);
393                        break;
394                    case 3:
395                        if(rsc->props.mLogShadersUniforms) {
396                            LOGV("Uniform 3 = %f %f %f", fd[0], fd[1], fd[2]);
397                        }
398                        glUniform3fv(slot, 1, fd);
399                        break;
400                    case 4:
401                        if(rsc->props.mLogShadersUniforms) {
402                            LOGV("Uniform 4 = %f %f %f %f", fd[0], fd[1], fd[2], fd[3]);
403                        }
404                        glUniform4fv(slot, 1, fd);
405                        break;
406                    default:
407                        rsAssert(0);
408                    }
409                }
410            }
411            uidx ++;
412        }
413    }
414}
415
416void Program::initAddUserElement(const Element *e, String8 *names, uint32_t *count, const char *prefix)
417{
418    rsAssert(e->getFieldCount());
419    for (uint32_t ct=0; ct < e->getFieldCount(); ct++) {
420        const Element *ce = e->getField(ct);
421        if (ce->getFieldCount()) {
422            initAddUserElement(ce, names, count, prefix);
423        }
424        else if(e->getFieldName(ct)[0] != '#') {
425            String8 tmp(prefix);
426            tmp.append(e->getFieldName(ct));
427            names[*count].setTo(tmp.string());
428            (*count)++;
429        }
430    }
431}
432
433namespace android {
434namespace renderscript {
435
436
437void rsi_ProgramBindConstants(Context *rsc, RsProgram vp, uint32_t slot, RsAllocation constants)
438{
439    Program *p = static_cast<Program *>(vp);
440    p->bindAllocation(rsc, static_cast<Allocation *>(constants), slot);
441}
442
443void rsi_ProgramBindTexture(Context *rsc, RsProgram vpf, uint32_t slot, RsAllocation a)
444{
445    Program *p = static_cast<Program *>(vpf);
446    p->bindTexture(rsc, slot, static_cast<Allocation *>(a));
447}
448
449void rsi_ProgramBindSampler(Context *rsc, RsProgram vpf, uint32_t slot, RsSampler s)
450{
451    Program *p = static_cast<Program *>(vpf);
452    p->bindSampler(rsc, slot, static_cast<Sampler *>(s));
453}
454
455}
456}
457
458