Project

General

Profile

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

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

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

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

    
39
import java.io.InputStream;
40
import java.nio.ByteBuffer;
41
import java.nio.ByteOrder;
42
import java.nio.FloatBuffer;
43

    
44
///////////////////////////////////////////////////////////////////////////////////////////////////
45

    
46
class EffectQueuePostprocess extends EffectQueue
47
  {
48
  private static final int MAX_HALO = 50;    // Support effects creating up to MAX_HALO pixels wide 'halo' around the object.
49

    
50
  private static final int POS_DATA_SIZE= 2; // Post Program: size of the position data in elements
51
  private static final int TEX_DATA_SIZE= 2; // Post Program: size of the texture coordinate data in elements.
52

    
53
  private static final int NUM_UNIFORMS = 5;
54
  private static final int NUM_CACHE    = 0;
55
  private static final int INDEX = EffectTypes.POSTPROCESS.ordinal();
56

    
57
  private static final FloatBuffer mQuadPositions, mQuadTexture, mQuadTextureInv;
58

    
59
  static
60
    {
61
    int dataLength      = 4;
62
    int bytes_per_float = 4;
63

    
64
    float[] position  = { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
65
    float[] textureNor= {  0.0f,  0.0f,   0.0f, 1.0f,  1.0f, 0.0f,  1.0f, 1.0f };
66
    float[] textureInv= {  0.0f,  0.0f,   1.0f, 0.0f,  0.0f, 1.0f,  1.0f, 1.0f };
67

    
68
    mQuadPositions = ByteBuffer.allocateDirect(POS_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
69
    mQuadPositions.put(position).position(0);
70
    mQuadTexture= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
71
    mQuadTexture.put(textureNor).position(0);
72
    mQuadTextureInv= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
73
    mQuadTextureInv.put(textureInv).position(0);
74
    }
75

    
76
  int mQualityLevel;
77
  float mQualityScale;
78
  private int mHalo;
79

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

    
105
  private static DistortedProgram mBlur1Program, mBlur2Program;
106
  private static int mRadius1H,mOffsets1H,mWeights1H,mDepth1H, mColorTexture1H;
107
  private static int mRadius2H,mOffsets2H,mWeights2H,mDepth2H, mColorTexture2H;
108
  private static float[] mWeights = new float[MAX_HALO];
109
  private static float[] mOffsets = new float[MAX_HALO];
110
  /////////////////////////////////////////////////////////////////////////////////
111
  // GLOW effect
112

    
113

    
114
///////////////////////////////////////////////////////////////////////////////////////////////////
115

    
116
  EffectQueuePostprocess(long id)
117
    { 
118
    super(id,NUM_UNIFORMS,NUM_CACHE,INDEX );
119

    
120
    mQualityLevel = 0;
121
    mQualityScale = 1.0f;
122
    }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

    
126
  static void createProgram(Resources resources)
127
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
128
    {
129
    final InputStream blur1VertexStream   = resources.openRawResource(R.raw.blur_vertex_shader);
130
    final InputStream blur1FragmentStream = resources.openRawResource(R.raw.blur1_fragment_shader);
131

    
132
    try
133
      {
134
      mBlur1Program = new DistortedProgram(blur1VertexStream,blur1FragmentStream,
135
                                          Distorted.GLSL_VERSION,
136
                                          Distorted.GLSL_VERSION + "#define MAX_BLUR "+MAX_HALO, Distorted.GLSL);
137
      }
138
    catch(Exception e)
139
      {
140
      android.util.Log.e("EFFECTS", "exception trying to compile BLUR1 program: "+e.getMessage());
141
      throw new RuntimeException(e.getMessage());
142
      }
143

    
144
    int blur1ProgramH = mBlur1Program.getProgramHandle();
145
    mRadius1H       = GLES30.glGetUniformLocation( blur1ProgramH, "u_Radius");
146
    mOffsets1H      = GLES30.glGetUniformLocation( blur1ProgramH, "u_Offsets");
147
    mWeights1H      = GLES30.glGetUniformLocation( blur1ProgramH, "u_Weights");
148
    mDepth1H        = GLES30.glGetUniformLocation( blur1ProgramH, "u_Depth");
149
    mColorTexture1H = GLES30.glGetUniformLocation( blur1ProgramH, "u_ColorTexture");
150

    
151
    final InputStream blur2VertexStream   = resources.openRawResource(R.raw.blur_vertex_shader);
152
    final InputStream blur2FragmentStream = resources.openRawResource(R.raw.blur2_fragment_shader);
153

    
154
    try
155
      {
156
      mBlur2Program = new DistortedProgram(blur2VertexStream,blur2FragmentStream,
157
                                          Distorted.GLSL_VERSION,
158
                                          Distorted.GLSL_VERSION + "#define MAX_BLUR "+MAX_HALO, Distorted.GLSL);
159
      }
160
    catch(Exception e)
161
      {
162
      android.util.Log.e("EFFECTS", "exception trying to compile BLUR2 program: "+e.getMessage());
163
      // run anyway as compiling Blur2 WILL fail on OpenGL 2.0 contexts
164
      mBlur2Program = mBlur1Program;
165
      }
166

    
167
    int blur2ProgramH = mBlur2Program.getProgramHandle();
168
    mRadius2H       = GLES30.glGetUniformLocation( blur2ProgramH, "u_Radius");
169
    mOffsets2H      = GLES30.glGetUniformLocation( blur2ProgramH, "u_Offsets");
170
    mWeights2H      = GLES30.glGetUniformLocation( blur2ProgramH, "u_Weights");
171
    mDepth2H        = GLES30.glGetUniformLocation( blur2ProgramH, "u_Depth");
172
    mColorTexture2H = GLES30.glGetUniformLocation( blur2ProgramH, "u_ColorTexture");
173
    }
174

    
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176

    
177
  private boolean compute(long currTime)
178
    {
179
    if( currTime==mTime ) return false;
180
    if( mTime==0 ) mTime = currTime;
181
    long step = (currTime-mTime);
182

    
183
    mHalo = 0;
184
    int halo;
185

    
186
    for(int i=0; i<mNumEffects; i++)
187
      {
188
      mCurrentDuration[i] += step;
189

    
190
      if( mInter[0][i]!=null && mInter[0][i].interpolateMain(mUniforms ,NUM_UNIFORMS*i, mCurrentDuration[i], step) )
191
        {
192
        for(int j=0; j<mNumListeners; j++)
193
          EffectMessageSender.newMessage( mListeners.elementAt(j),
194
                                          EffectMessage.EFFECT_FINISHED,
195
                                         (mID[i]<<EffectTypes.LENGTH)+EffectTypes.POSTPROCESS.type,
196
                                          mName[i],
197
                                          mObjectID);
198

    
199
        if( EffectNames.isUnity(mName[i], mUniforms, NUM_UNIFORMS*i) )
200
          {
201
          remove(i);
202
          i--;
203
          continue;
204
          }
205
        else mInter[0][i] = null;
206
        }
207

    
208
      if( mInter[1][i]!=null ) mInter[1][i].interpolateMain( mUniforms, NUM_UNIFORMS*i+1, mCurrentDuration[i], step);
209

    
210
      halo = (int)mUniforms[NUM_UNIFORMS*i];
211
      if( halo>mHalo ) mHalo = halo;
212
      }
213

    
214
    mTime = currTime;
215

    
216
    return true;
217
    }  
218

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

    
221
  protected void moveEffect(int index)
222
    {
223
    mUniforms[NUM_UNIFORMS*index  ] = mUniforms[NUM_UNIFORMS*(index+1)  ];
224
    mUniforms[NUM_UNIFORMS*index+1] = mUniforms[NUM_UNIFORMS*(index+1)+1];
225
    mUniforms[NUM_UNIFORMS*index+2] = mUniforms[NUM_UNIFORMS*(index+1)+2];
226
    mUniforms[NUM_UNIFORMS*index+3] = mUniforms[NUM_UNIFORMS*(index+1)+3];
227
    mUniforms[NUM_UNIFORMS*index+4] = mUniforms[NUM_UNIFORMS*(index+1)+4];
228
    }
229

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

    
234
  private void computeGaussianKernel(int radius)
235
    {
236
    int offset = radius + radius*radius/4;
237

    
238
    if( weightsCache[offset]==0.0f )
239
      {
240
      float z, x= 0.0f, P= (float)NUM_GAUSSIAN / (radius>3 ? radius:3);
241
      mWeights[0] = GAUSSIAN[0];
242
      float sum   = GAUSSIAN[0];
243
      int j;
244

    
245
      for(int i=1; i<=radius; i++)
246
        {
247
        x += P;
248
        j = (int)x;
249
        z = x-j;
250

    
251
        mWeights[i] = (1-z)*GAUSSIAN[j] + z*GAUSSIAN[j+1];
252
        sum += 2*mWeights[i];
253
        }
254

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

    
257
      int numloops = radius/2;
258
      weightsCache[offset] = mWeights[0];
259
      offsetsCache[offset] = 0.0f;
260

    
261
      for(int i=0; i<numloops; i++)
262
        {
263
        offsetsCache[offset+i+1] = mWeights[2*i+1]*(2*i+1) + mWeights[2*i+2]*(2*i+2);
264
        weightsCache[offset+i+1] = mWeights[2*i+1] + mWeights[2*i+2];
265
        offsetsCache[offset+i+1]/= weightsCache[offset+i+1];
266
        }
267

    
268
      if( radius%2 == 1 )
269
        {
270
        int index = offset + radius/2 +1;
271
        offsetsCache[index]=radius;
272
        weightsCache[index]=mWeights[radius];
273
        }
274
      }
275
    }
276

    
277
///////////////////////////////////////////////////////////////////////////////////////////////////
278

    
279
  int getHalo()
280
    {
281
    return mNumEffects>0 ? mHalo : 0;
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285

    
286
  int postprocess(long time, DistortedOutputSurface surface)
287
    {
288
    int numRenders = 0;
289

    
290
    if( mNumEffects>0 )
291
      {
292
      compute(time);
293

    
294
      for(int i=0; i<mNumEffects; i++)
295
        {
296
        if (mName[i] == EffectNames.BLUR.ordinal() )
297
          {
298
          blur(NUM_UNIFORMS*i,surface);
299
          numRenders += 2;
300
          }
301
        else if (mName[i] == EffectNames.GLOW.ordinal() )
302
          {
303
          glow(NUM_UNIFORMS*i,surface);
304
          numRenders += 2;
305
          }
306
        }
307
      }
308

    
309
    return numRenders;
310
    }
311

    
312
///////////////////////////////////////////////////////////////////////////////////////////////////
313

    
314
  private void blur(int index, DistortedOutputSurface surface)
315
    {
316
    DistortedFramebuffer buffer = surface.mBuffer[mQualityLevel];
317
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, buffer.mFBOH[0]);
318

    
319
    float w1 = buffer.mWidth;
320
    float h1 = buffer.mHeight;
321

    
322
    int radius = (int)(mUniforms[index]*mQualityScale);
323
    if( radius>=MAX_HALO ) radius = MAX_HALO-1;
324
    computeGaussianKernel(radius);
325

    
326
    int offset = radius + radius*radius/4;
327
    radius = (radius+1)/2;
328

    
329
    // horizontal blur
330
    GLES30.glViewport(0, 0, (int)w1, (int)h1);
331
    mBlur1Program.useProgram();
332
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
333
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
334
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
335

    
336
    GLES30.glUniform1fv( mWeights1H, radius+1, weightsCache,offset);
337
    GLES30.glUniform1i( mRadius1H, radius);
338
    GLES30.glUniform1f( mDepth1H , 1.0f-surface.mNear);
339
    GLES30.glUniform1i( mColorTexture1H , 0 );
340
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/h1;
341
    GLES30.glUniform1fv( mOffsets1H ,radius+1, mOffsets,0);
342
    GLES30.glVertexAttribPointer(mBlur1Program.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
343
    GLES30.glVertexAttribPointer(mBlur1Program.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTexture);
344

    
345
    DistortedRenderState.useStencilMark();
346
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
347
    DistortedRenderState.unuseStencilMark();
348
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
349
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
350

    
351
    // vertical blur
352
    mBlur2Program.useProgram();
353
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
354
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
355
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[1]);
356

    
357
    GLES30.glColorMask(true,true,true,true);
358
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
359
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
360

    
361
    GLES30.glUniform1fv( mWeights2H, radius+1, weightsCache,offset);
362
    GLES30.glUniform1i( mRadius2H, radius);
363
    GLES30.glUniform1f( mDepth2H , 1.0f-surface.mNear);
364
    GLES30.glUniform1i( mColorTexture2H , 0 );
365
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/w1;
366
    GLES30.glUniform1fv( mOffsets2H ,radius+1, mOffsets,0);
367
    GLES30.glVertexAttribPointer(mBlur2Program.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
368
    GLES30.glVertexAttribPointer(mBlur2Program.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTexture);
369

    
370
    DistortedRenderState.useStencilMark();
371
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
372
    DistortedRenderState.unuseStencilMark();
373
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
374
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
375
    }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378

    
379
  private void glow(int index, DistortedOutputSurface surface)
380
    {
381

    
382
    }
383

    
384
///////////////////////////////////////////////////////////////////////////////////////////////////
385
// blur
386

    
387
  synchronized long add(EffectNames eln, Data1D degree)
388
    {
389
    if( mMax[INDEX]>mNumEffects )
390
      {
391
      if( degree instanceof Dynamic1D)
392
        {
393
        mInter[0][mNumEffects] = (Dynamic1D)degree;
394
        }
395
      else if( degree instanceof Static1D)
396
        {
397
        mInter[0][mNumEffects] = null;
398
        mUniforms[NUM_UNIFORMS*mNumEffects] = ((Static1D)degree).getX();
399
        }
400
      else return -1;
401

    
402
      mInter[1][mNumEffects] = null;
403
      mInter[2][mNumEffects] = null;
404

    
405
      return addBase(eln);
406
      }
407
      
408
    return -1;
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
// glow
413

    
414
  synchronized long add(EffectNames eln, Data1D degree, Data4D color)
415
    {
416
    if( mMax[INDEX]>mNumEffects )
417
      {
418
      if( degree instanceof Dynamic1D)
419
        {
420
        mInter[0][mNumEffects] = (Dynamic1D)degree;
421
        }
422
      else if( degree instanceof Static1D)
423
        {
424
        mInter[0][mNumEffects] = null;
425
        mUniforms[NUM_UNIFORMS*mNumEffects] = ((Static1D)degree).getX();
426
        }
427
      else return -1;
428

    
429
      if( color instanceof Dynamic4D)
430
        {
431
        mInter[1][mNumEffects] = (Dynamic4D)color;
432
        }
433
      else if( color instanceof Static4D)
434
        {
435
        mInter[1][mNumEffects] = null;
436
        Static4D tmp = (Static4D)color;
437
        mUniforms[NUM_UNIFORMS*mNumEffects+1] = tmp.getW();  //
438
        mUniforms[NUM_UNIFORMS*mNumEffects+2] = tmp.getX();  // Invert: RGBA sent
439
        mUniforms[NUM_UNIFORMS*mNumEffects+3] = tmp.getY();  // in, ARGB inside
440
        mUniforms[NUM_UNIFORMS*mNumEffects+4] = tmp.getZ();  //
441
        }
442
      else return -1;
443

    
444
      mInter[2][mNumEffects] = null;
445

    
446
      return addBase(eln);
447
      }
448

    
449
    return -1;
450
    }
451
  }
(21-21/26)