Project

General

Profile

Download (13.8 KB) Statistics
| Branch: | Revision:

library / src / main / java / org / distorted / library / EffectQueuePostprocess.java @ b9798977

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library;
21

    
22
import android.content.res.Resources;
23
import android.opengl.GLES30;
24
import android.opengl.Matrix;
25

    
26
import org.distorted.library.message.EffectMessage;
27
import org.distorted.library.program.DistortedProgram;
28
import org.distorted.library.program.FragmentCompilationException;
29
import org.distorted.library.program.FragmentUniformsException;
30
import org.distorted.library.program.LinkingException;
31
import org.distorted.library.program.VertexCompilationException;
32
import org.distorted.library.program.VertexUniformsException;
33
import org.distorted.library.type.Data1D;
34
import org.distorted.library.type.Dynamic1D;
35
import org.distorted.library.type.Static1D;
36

    
37
import java.io.InputStream;
38
import java.nio.ByteBuffer;
39
import java.nio.ByteOrder;
40
import java.nio.FloatBuffer;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
class EffectQueuePostprocess extends EffectQueue
45
  {
46
  private static final int POS_DATA_SIZE= 2; // Post Program: size of the position data in elements
47
  private static final int TEX_DATA_SIZE= 2; // Post Program: size of the texture coordinate data in elements.
48

    
49
  private static final int NUM_UNIFORMS = 4;
50
  private static final int NUM_CACHE    = 0;
51
  private static final int INDEX = EffectTypes.POSTPROCESS.ordinal();
52

    
53
  private static final FloatBuffer mQuadPositions, mQuadTextureNor, mQuadTextureInv;
54

    
55
  static
56
    {
57
    int dataLength      = 4;
58
    int bytes_per_float = 4;
59

    
60
    float[] position  = { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
61
    float[] textureNor= {  0.0f,  0.0f,   0.0f, 1.0f,  1.0f, 0.0f,  1.0f, 1.0f };
62
    float[] textureInv= {  0.0f,  0.0f,   1.0f, 0.0f,  0.0f, 1.0f,  1.0f, 1.0f };
63

    
64
    mQuadPositions = ByteBuffer.allocateDirect(POS_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
65
    mQuadPositions.put(position).position(0);
66
    mQuadTextureNor= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
67
    mQuadTextureNor.put(textureNor).position(0);
68
    mQuadTextureInv= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
69
    mQuadTextureInv.put(textureInv).position(0);
70
    }
71

    
72
  private static DistortedFramebuffer mPostBuffer = new DistortedFramebuffer(true,DistortedSurface.TYPE_SYST,1,1);
73
                 DistortedFramebuffer mMainBuffer = new DistortedFramebuffer(true,DistortedSurface.TYPE_SYST,1,1);
74

    
75
  private static float[] mMVPMatrix = new float[16];
76
  private static float[] mTmpMatrix = new float[16];
77

    
78
  // BLUR effect
79
  private static final float GAUSSIAN[] =   // G(0.00), G(0.03), G(0.06), ..., G(3.00), 0
80
    {                                       // where G(x)= (1/(sqrt(2*PI))) * e^(-(x^2)/2). The last 0 terminates.
81
    0.398948f, 0.398769f, 0.398231f, 0.397336f, 0.396086f, 0.394485f, 0.392537f, 0.390247f, 0.387622f, 0.384668f,
82
    0.381393f, 0.377806f, 0.373916f, 0.369733f, 0.365268f, 0.360532f, 0.355538f, 0.350297f, 0.344823f, 0.339129f,
83
    0.333229f, 0.327138f, 0.320868f, 0.314436f, 0.307856f, 0.301142f, 0.294309f, 0.287373f, 0.280348f, 0.273248f,
84
    0.266089f, 0.258884f, 0.251648f, 0.244394f, 0.237135f, 0.229886f, 0.222657f, 0.215461f, 0.208311f, 0.201217f,
85
    0.194189f, 0.187238f, 0.180374f, 0.173605f, 0.166940f, 0.160386f, 0.153951f, 0.147641f, 0.141462f, 0.135420f,
86
    0.129520f, 0.123765f, 0.118159f, 0.112706f, 0.107408f, 0.102266f, 0.097284f, 0.092461f, 0.087797f, 0.083294f,
87
    0.078951f, 0.074767f, 0.070741f, 0.066872f, 0.063158f, 0.059596f, 0.056184f, 0.052920f, 0.049801f, 0.046823f,
88
    0.043984f, 0.041280f, 0.038707f, 0.036262f, 0.033941f, 0.031740f, 0.029655f, 0.027682f, 0.025817f, 0.024056f,
89
    0.022395f, 0.020830f, 0.019357f, 0.017971f, 0.016670f, 0.015450f, 0.014305f, 0.013234f, 0.012232f, 0.011295f,
90
    0.010421f, 0.009606f, 0.008847f, 0.008140f, 0.007483f, 0.006873f, 0.006307f, 0.005782f, 0.005296f, 0.004847f,
91
    0.004432f, 0.000000f
92
    };
93
  private static final int NUM_GAUSSIAN = GAUSSIAN.length-2;
94

    
95
  // Support blurs consisting of the present pixel and up to MAX_BLUR pixels in each direction
96
  private static final int MAX_BLUR = 50;
97

    
98
  // The (fixed-function-sampled) Gaussian Blur kernels are of the size k0=1, k1=2, k2=2, k3=3, k4=3, k5=4, k6=4,...
99
  // i.e. k(i)=floor((i+3)/2).  (the 'i' in k(i) means 'blur taking into account the present pixel and 'i' pixels
100
  // in all 4 directions)
101
  // We need room for MAX_BLUR of them, and sum(i=0...N, floor((i+3)/2)) = N + floor(N*N/4)
102
  private static float[] weightsCache = new float[MAX_BLUR + MAX_BLUR*MAX_BLUR/4];
103
  private static float[] offsetsCache = new float[MAX_BLUR + MAX_BLUR*MAX_BLUR/4];
104

    
105
  private static DistortedProgram mBlurProgram;
106
  private static int mRadiusH,mOffsetsH,mWeightsH,mObjDH,mMVPMatrixH;
107
  private static float[] mWeights = new float[MAX_BLUR];
108
  private static float[] mOffsets = new float[MAX_BLUR];
109
  // another effect ....
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
  EffectQueuePostprocess(long id)
114
    { 
115
    super(id,NUM_UNIFORMS,NUM_CACHE,INDEX );
116
    }
117

    
118
///////////////////////////////////////////////////////////////////////////////////////////////////
119

    
120
  static void createProgram(Resources resources)
121
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
122
    {
123
    final InputStream postVertexStream   = resources.openRawResource(R.raw.blur_vertex_shader);
124
    final InputStream postFragmentStream = resources.openRawResource(R.raw.blur_fragment_shader);
125

    
126
    mBlurProgram = new DistortedProgram(postVertexStream,postFragmentStream,
127
                                        "#version 100\n",
128
                                        "#version 100\n#define MAX_BLUR "+MAX_BLUR);
129

    
130
    int blurProgramH = mBlurProgram.getProgramHandle();
131
    mRadiusH    = GLES30.glGetUniformLocation( blurProgramH, "u_Radius");
132
    mOffsetsH   = GLES30.glGetUniformLocation( blurProgramH, "u_Offsets");
133
    mWeightsH   = GLES30.glGetUniformLocation( blurProgramH, "u_Weights");
134
    mObjDH      = GLES30.glGetUniformLocation( blurProgramH, "u_objD");
135
    mMVPMatrixH = GLES30.glGetUniformLocation( blurProgramH, "u_MVPMatrix");
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139
  
140
  synchronized void compute(long currTime) 
141
    {
142
    if( currTime==mTime ) return;
143
    if( mTime==0 ) mTime = currTime;
144
    long step = (currTime-mTime);
145
   
146
    for(int i=0; i<mNumEffects; i++)
147
      {
148
      mCurrentDuration[i] += step;
149

    
150
      if( mInter[0][i]!=null && mInter[0][i].interpolateMain(mUniforms ,NUM_UNIFORMS*i, mCurrentDuration[i], step) )
151
        {
152
        for(int j=0; j<mNumListeners; j++)
153
          EffectMessageSender.newMessage( mListeners.elementAt(j),
154
                                          EffectMessage.EFFECT_FINISHED,
155
                                         (mID[i]<<EffectTypes.LENGTH)+EffectTypes.POSTPROCESS.type,
156
                                          mName[i],
157
                                          mObjectID);
158

    
159
        if( EffectNames.isUnity(mName[i], mUniforms, NUM_UNIFORMS*i) )
160
          {
161
          remove(i);
162
          i--;
163
          continue;
164
          }
165
        else mInter[0][i] = null;
166
        }
167
      }
168
     
169
    mTime = currTime;  
170
    }  
171

    
172
///////////////////////////////////////////////////////////////////////////////////////////////////
173

    
174
  protected void moveEffect(int index)
175
    {
176
    mUniforms[NUM_UNIFORMS*index  ] = mUniforms[NUM_UNIFORMS*(index+1)  ];
177
    mUniforms[NUM_UNIFORMS*index+1] = mUniforms[NUM_UNIFORMS*(index+1)+1];
178
    mUniforms[NUM_UNIFORMS*index+2] = mUniforms[NUM_UNIFORMS*(index+1)+2];
179
    mUniforms[NUM_UNIFORMS*index+3] = mUniforms[NUM_UNIFORMS*(index+1)+3];
180
    }
181

    
182
///////////////////////////////////////////////////////////////////////////////////////////////////
183
// This implements the 'Better separable implementation using GPU fixed function sampling' from
184
// https://software.intel.com/en-us/blogs/2014/07/15/an-investigation-of-fast-real-time-gpu-based-image-blur-algorithms
185

    
186
  private void computeGaussianKernel(int radius)
187
    {
188
    int offset = radius + radius*radius/4;
189

    
190
    if( weightsCache[offset]==0.0f )
191
      {
192
      float z, x= 0.0f, P= (float)NUM_GAUSSIAN / (radius>3 ? radius:3);
193
      mWeights[0] = GAUSSIAN[0];
194
      float sum   = GAUSSIAN[0];
195
      int j;
196

    
197
      for(int i=1; i<=radius; i++)
198
        {
199
        x += P;
200
        j = (int)x;
201
        z = x-j;
202

    
203
        mWeights[i] = (1-z)*GAUSSIAN[j] + z*GAUSSIAN[j+1];
204
        sum += 2*mWeights[i];
205
        }
206

    
207
      for(int i=0; i<=radius; i++) mWeights[i] /= sum;
208

    
209
      int numloops = radius/2;
210
      weightsCache[offset] = mWeights[0];
211
      offsetsCache[offset] = 0.0f;
212

    
213
      for(int i=0; i<numloops; i++)
214
        {
215
        offsetsCache[offset+i+1] = mWeights[2*i+1]*(2*i+1) + mWeights[2*i+2]*(2*i+2);
216
        weightsCache[offset+i+1] = mWeights[2*i+1] + mWeights[2*i+2];
217
        offsetsCache[offset+i+1]/= weightsCache[offset+i+1];
218
        }
219

    
220
      if( radius%2 == 1 )
221
        {
222
        int index = offset + radius/2 +1;
223
        offsetsCache[index]=mOffsets[radius];
224
        weightsCache[index]=mWeights[radius];
225
        }
226
      }
227
    }
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230
// w,h - width and height of the input texture. MVP - Model-View-Projection matrix to apply to the
231
// texture; df - output FBO.
232

    
233
  synchronized void render(float w, float h, float[] mvp, DistortedOutputSurface surface)
234
    {
235
    mBlurProgram.useProgram();
236

    
237
    int radius = (int)mUniforms[0];
238
    if( radius>=MAX_BLUR ) radius = MAX_BLUR-1;
239
    computeGaussianKernel(radius);
240

    
241
    int offset = radius + radius*radius/4;
242
    radius = (radius+1)/2;
243
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/h;
244

    
245
    GLES30.glUniform1fv( mWeightsH, radius+1, weightsCache,offset);
246
    GLES30.glUniform1i( mRadiusH, radius);
247
    GLES30.glUniform2f( mObjDH , w, h );
248

    
249
    mPostBuffer.resizeFast( (int)w, (int)h);
250
    mPostBuffer.setAsOutput();
251
    GLES30.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
252
    GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
253
    GLES30.glViewport(0, 0, (int)w, (int)h);
254

    
255
    Matrix.setIdentityM(mTmpMatrix, 0);
256
    Matrix.translateM(mTmpMatrix, 0, 0, 0, -mPostBuffer.mDistance);
257
    Matrix.multiplyMM(mMVPMatrix, 0, mPostBuffer.mProjectionMatrix, 0, mTmpMatrix, 0);
258

    
259
    // horizontal blur
260
    GLES30.glUniform1fv( mOffsetsH ,radius+1, mOffsets,0);
261
    GLES30.glUniformMatrix4fv(mMVPMatrixH, 1, false, mMVPMatrix , 0);
262
    GLES30.glVertexAttribPointer(mBlurProgram.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
263
    GLES30.glVertexAttribPointer(mBlurProgram.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTextureInv);
264
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
265

    
266
    mPostBuffer.setAsInput();
267
    surface.setAsOutput();
268

    
269
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight);
270

    
271
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/w;
272

    
273
    // vertical blur
274
    GLES30.glUniform1fv( mOffsetsH ,radius+1, mOffsets,0);
275
    GLES30.glUniformMatrix4fv(mMVPMatrixH, 1, false, mvp , 0);
276
    GLES30.glVertexAttribPointer(mBlurProgram.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
277
    GLES30.glVertexAttribPointer(mBlurProgram.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTextureInv);
278
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
279
    }
280

    
281
///////////////////////////////////////////////////////////////////////////////////////////////////
282
// blur
283

    
284
  synchronized long add(EffectNames eln, Data1D degree)
285
    {
286
    if( mMax[INDEX]>mNumEffects )
287
      {
288
      if( degree instanceof Dynamic1D)
289
        {
290
        mInter[0][mNumEffects] = (Dynamic1D)degree;
291
        }
292
      else if( degree instanceof Static1D)
293
        {
294
        mInter[0][mNumEffects] = null;
295
        mUniforms[NUM_UNIFORMS*mNumEffects] = ((Static1D)degree).getX();
296
        }
297
      else return -1;
298

    
299
      mInter[1][mNumEffects] = null;
300
      mInter[2][mNumEffects] = null;
301

    
302
      return addBase(eln);
303
      }
304
      
305
    return -1;
306
    }
307
  }
(18-18/23)