Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 97020807

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.main;
21

    
22
import android.content.res.Resources;
23
import android.opengl.GLES31;
24
import android.util.Log;
25

    
26
import org.distorted.library.R;
27
import org.distorted.library.effect.Effect;
28
import org.distorted.library.effect.EffectName;
29
import org.distorted.library.effect.EffectType;
30
import org.distorted.library.effect.FragmentEffect;
31
import org.distorted.library.effect.VertexEffect;
32
import org.distorted.library.message.EffectListener;
33
import org.distorted.library.program.DistortedProgram;
34

    
35
import java.io.InputStream;
36
import java.nio.ByteBuffer;
37
import java.nio.ByteOrder;
38
import java.nio.FloatBuffer;
39
import java.nio.IntBuffer;
40

    
41
///////////////////////////////////////////////////////////////////////////////////////////////////
42
/**
43
 * Class containing Matrix, Vertex, Fragment and Postprocessing effect queues.
44
 * <p>
45
 * The queues hold actual effects to be applied to a given (InputSurface,MeshObject) combo.
46
 */
47
public class DistortedEffects
48
  {
49
  /// MAIN PROGRAM ///
50
  private static DistortedProgram mMainProgram;
51
  private static int mMainTextureH;
52

    
53
  /// BLIT PROGRAM ///
54
  private static DistortedProgram mBlitProgram;
55
  private static int mBlitTextureH;
56
  private static int mBlitDepthH;
57
  private static final FloatBuffer mQuadPositions;
58

    
59
  static
60
    {
61
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
62
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
63
    mQuadPositions.put(positionData).position(0);
64
    }
65

    
66
  /// BLIT DEPTH PROGRAM ///
67
  private static DistortedProgram mBlitDepthProgram;
68
  private static int mBlitDepthTextureH;
69
  private static int mBlitDepthDepthTextureH;
70
  private static int mBlitDepthDepthH;
71
  private static int mBlitDepthTexCorrH;
72

    
73
  /// OIT SSBO BUFFER ///
74
  private static int[] mLinkedListSSBO = new int[1];
75
  private static int[] mAtomicCounter = new int[1];
76

    
77
  static
78
    {
79
    mLinkedListSSBO[0]= -1;
80
    mAtomicCounter[0] = -1;
81
    }
82

    
83
  ///////////////////////////////////////////////////////////////
84
  // this has to be at least as big as the number of pixels in
85
  // the screen, lest the oitClear() pass overwrite memory.
86
  private static int mBufferSize=(0x1<<23);  // 8 million entries
87

    
88
  /// OIT CLEAR PROGRAM ///
89
  private static DistortedProgram mOITClearProgram;
90
  private static int mOITClearDepthH;
91
  private static int mOITClearTexCorrH;
92
  private static int mOITClearSizeH;
93

    
94
  /// OIT BUILD PROGRAM ///
95
  private static DistortedProgram mOITBuildProgram;
96
  private static int mOITBuildTextureH;
97
  private static int mOITBuildDepthTextureH;
98
  private static int mOITBuildDepthH;
99
  private static int mOITBuildTexCorrH;
100
  private static int mOITBuildSizeH;
101
  private static int mOITBuildNumRecordsH;
102

    
103
  /// OIT COLLAPSE PROGRAM ///
104
  private static DistortedProgram mOITCollapseProgram;
105
  private static int mOITCollapseDepthTextureH;
106
  private static int mOITCollapseDepthH;
107
  private static int mOITCollapseTexCorrH;
108
  private static int mOITCollapseSizeH;
109

    
110
  /// OIT RENDER PROGRAM ///
111
  private static DistortedProgram mOITRenderProgram;
112
  private static int mOITRenderDepthH;
113
  private static int mOITRenderTexCorrH;
114
  private static int mOITRenderSizeH;
115

    
116
  /// NORMAL PROGRAM /////
117
  private static DistortedProgram mNormalProgram;
118
  private static int mNormalMVPMatrixH;
119
  /// END PROGRAMS //////
120

    
121
  private static long mNextID =0;
122
  private long mID;
123

    
124
  private EffectQueueMatrix mM;
125
  private EffectQueueFragment mF;
126
  private EffectQueueVertex mV;
127
  private EffectQueuePostprocess mP;
128

    
129
  private boolean matrixCloned, vertexCloned, fragmentCloned, postprocessCloned;
130

    
131
///////////////////////////////////////////////////////////////////////////////////////////////////
132

    
133
  static void createProgram(Resources resources)
134
    {
135
    // MAIN PROGRAM ////////////////////////////////////
136
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
137
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
138

    
139
    int numF = FragmentEffect.getNumEnabled();
140
    int numV = VertexEffect.getNumEnabled();
141

    
142
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
143
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
144
    String enabledEffectV= VertexEffect.getGLSL();
145
    String enabledEffectF= FragmentEffect.getGLSL();
146

    
147
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
148
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
149
    //android.util.Log.e("Effects", "enabledV= "+enabledEffectV);
150
    //android.util.Log.e("Effects", "enabledF= "+enabledEffectF);
151

    
152
    String[] feedback = { "v_Position", "v_endPosition" };
153

    
154
    try
155
      {
156
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
157
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
158
      }
159
    catch(Exception e)
160
      {
161
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
162
      throw new RuntimeException(e.getMessage());
163
      }
164

    
165
    int mainProgramH = mMainProgram.getProgramHandle();
166
    EffectQueueFragment.getUniforms(mainProgramH);
167
    EffectQueueVertex.getUniforms(mainProgramH);
168
    EffectQueueMatrix.getUniforms(mainProgramH);
169
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
170

    
171
    // BLIT PROGRAM ////////////////////////////////////
172
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
173
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
174

    
175
    try
176
      {
177
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
178
      }
179
    catch(Exception e)
180
      {
181
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
182
      throw new RuntimeException(e.getMessage());
183
      }
184

    
185
    int blitProgramH = mBlitProgram.getProgramHandle();
186
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
187
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
188

    
189
    // BLIT DEPTH PROGRAM ////////////////////////////////////
190
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
191
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
192

    
193
    try
194
      {
195
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
196
      }
197
    catch(Exception e)
198
      {
199
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
200
      throw new RuntimeException(e.getMessage());
201
      }
202

    
203
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
204
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
205
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
206
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
207
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
208

    
209
    // OIT CLEAR PROGRAM ////////////////////////////////////
210
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
211
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
212

    
213
    try
214
      {
215
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
216
      }
217
    catch(Exception e)
218
      {
219
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
220
      throw new RuntimeException(e.getMessage());
221
      }
222

    
223
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
224
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
225
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
226
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
227

    
228
    // OIT BUILD PROGRAM ////////////////////////////////////
229
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
230
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
231

    
232
    try
233
      {
234
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
235
      }
236
    catch(Exception e)
237
      {
238
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
239
      throw new RuntimeException(e.getMessage());
240
      }
241

    
242
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
243
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
244
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
245
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
246
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
247
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
248
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
249

    
250
    if( mLinkedListSSBO[0]<0 )
251
      {
252
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
253
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
254
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
255
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
256
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
257
      }
258

    
259
    if( mAtomicCounter[0]<0 )
260
      {
261
      GLES31.glGenBuffers(1,mAtomicCounter,0);
262
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[0]);
263
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
264
      GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
265
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
266
      }
267

    
268
    // OIT COLLAPSE PROGRAM ///////////////////////////
269
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
270
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
271

    
272
    try
273
      {
274
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
275
      }
276
    catch(Exception e)
277
      {
278
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
279
      throw new RuntimeException(e.getMessage());
280
      }
281

    
282
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
283
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
284
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
285
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
286
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
287

    
288
    // OIT RENDER PROGRAM ///////////////////////////
289
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
290
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
291

    
292
    try
293
      {
294
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
295
      }
296
    catch(Exception e)
297
      {
298
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
299
      throw new RuntimeException(e.getMessage());
300
      }
301

    
302
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
303
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
304
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
305
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
306

    
307
    // NORMAL PROGRAM //////////////////////////////////////
308
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
309
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
310

    
311
    try
312
      {
313
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
314
      }
315
    catch(Exception e)
316
      {
317
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
318
      throw new RuntimeException(e.getMessage());
319
      }
320

    
321
    int normalProgramH = mNormalProgram.getProgramHandle();
322
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
323
    }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326

    
327
  private void initializeEffectLists(DistortedEffects d, int flags)
328
    {
329
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
330
      {
331
      mM = d.mM;
332
      matrixCloned = true;
333
      }
334
    else
335
      {
336
      mM = new EffectQueueMatrix(mID);
337
      matrixCloned = false;
338
      }
339
    
340
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
341
      {
342
      mV = d.mV;
343
      vertexCloned = true;
344
      }
345
    else
346
      {
347
      mV = new EffectQueueVertex(mID);
348
      vertexCloned = false;
349
      }
350
    
351
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
352
      {
353
      mF = d.mF;
354
      fragmentCloned = true;
355
      }
356
    else
357
      {
358
      mF = new EffectQueueFragment(mID);
359
      fragmentCloned = false;
360
      }
361

    
362
    if( (flags & Distorted.CLONE_POSTPROCESS) != 0 )
363
      {
364
      mP = d.mP;
365
      postprocessCloned = true;
366
      }
367
    else
368
      {
369
      mP = new EffectQueuePostprocess(mID);
370
      postprocessCloned = false;
371
      }
372
    }
373

    
374
///////////////////////////////////////////////////////////////////////////////////////////////////
375

    
376
  EffectQueuePostprocess getPostprocess()
377
    {
378
    return mP;
379
    }
380

    
381
///////////////////////////////////////////////////////////////////////////////////////////////////
382

    
383
  void newNode(DistortedNode node)
384
    {
385
    mM.newNode(node);
386
    mF.newNode(node);
387
    mV.newNode(node);
388
    mP.newNode(node);
389
    }
390

    
391
///////////////////////////////////////////////////////////////////////////////////////////////////
392

    
393
  private void displayNormals(MeshObject mesh)
394
    {
395
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
396
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
397
    DistortedRenderState.switchOffDrawing();
398
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
399
    DistortedRenderState.restoreDrawing();
400
    GLES31.glEndTransformFeedback();
401
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
402

    
403
    mNormalProgram.useProgram();
404
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
405
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttTFO[0]);
406
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
407
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
408
    GLES31.glLineWidth(8.0f);
409
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*mesh.numVertices);
410
    }
411

    
412
///////////////////////////////////////////////////////////////////////////////////////////////////
413

    
414
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
415
    {
416
    float halfZ = halfW*mesh.zFactor;
417

    
418
    mM.compute(currTime);
419
    mV.compute(currTime,halfW,halfH,halfZ);
420
    mF.compute(currTime,halfW,halfH);
421
    mP.compute(currTime);
422

    
423
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
424

    
425
    mMainProgram.useProgram();
426
    GLES31.glUniform1i(mMainTextureH, 0);
427

    
428
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
429
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
430
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
431
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
432
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
433

    
434
    mM.send(surface,halfW,halfH,halfZ,marginInPixels);
435
    mV.send();
436
    mF.send();
437

    
438
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
439

    
440
    if( mesh.mShowNormals ) displayNormals(mesh);
441
    }
442

    
443
///////////////////////////////////////////////////////////////////////////////////////////////////
444
/**
445
 * Only for use by the library itself.
446
 *
447
 * @y.exclude
448
 */
449
  public static void blitPriv(DistortedOutputSurface surface)
450
    {
451
    mBlitProgram.useProgram();
452

    
453
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
454
    GLES31.glUniform1i(mBlitTextureH, 0);
455
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
456
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
457
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
458
    }
459

    
460
///////////////////////////////////////////////////////////////////////////////////////////////////
461

    
462
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
463
    {
464
    mBlitDepthProgram.useProgram();
465

    
466
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
467
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
468
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
469
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
470
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
471
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
472
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
473
    }
474

    
475
///////////////////////////////////////////////////////////////////////////////////////////////////
476
// reset atomic counter to 0
477

    
478
  static void zeroOutAtomic()
479
    {
480
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
481

    
482
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
483
                                                                GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
484
    if( atomicBuf!=null )
485
      {
486
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
487

    
488
      //int counter = atomicIntBuf.get(0);
489
      //android.util.Log.e("counter", "now = "+counter+" w="+surface.mWidth+" h="+surface.mHeight
490
      //                             +" diff="+(counter-surface.mWidth*surface.mHeight));
491
      atomicIntBuf.put(0,0);
492
      }
493
    else
494
      {
495
      android.util.Log.e("effects", "failed to map atomic buffer");
496
      }
497

    
498
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
499
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
500
    }
501

    
502
///////////////////////////////////////////////////////////////////////////////////////////////////
503
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
504

    
505
  static void oitClear(DistortedOutputSurface surface)
506
    {
507
    mOITClearProgram.useProgram();
508

    
509
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
510
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
511
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
512
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
513
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
514
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518
// Pass2 of the OIT algorithm - build per-pixel linked lists.
519

    
520
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
521
    {
522
    mOITBuildProgram.useProgram();
523

    
524
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
525
    GLES31.glUniform1i(mOITBuildTextureH, 0);
526
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
527
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
528
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
529
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (mBufferSize-surface.mWidth*surface.mHeight)/3 );  // see the fragment shader
530
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
531
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
532
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
537

    
538
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
539
    {
540
    mOITCollapseProgram.useProgram();
541

    
542
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
543
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
544
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
545
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
546
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
547
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
548
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
553

    
554
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
555
    {
556
    mOITRenderProgram.useProgram();
557

    
558
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
559
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
560
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
561
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
562
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
563
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567

    
568
  private void releasePriv()
569
    {
570
    if( !matrixCloned      ) mM.abortAll(false);
571
    if( !vertexCloned      ) mV.abortAll(false);
572
    if( !fragmentCloned    ) mF.abortAll(false);
573
    if( !postprocessCloned ) mP.abortAll(false);
574

    
575
    mM = null;
576
    mV = null;
577
    mF = null;
578
    mP = null;
579
    }
580

    
581
///////////////////////////////////////////////////////////////////////////////////////////////////
582

    
583
  static void onPause()
584
    {
585
    mLinkedListSSBO[0]= -1;
586
    mAtomicCounter[0] = -1;
587
    }
588

    
589
///////////////////////////////////////////////////////////////////////////////////////////////////
590

    
591
  static void onDestroy()
592
    {
593
    mNextID =  0;
594
    }
595

    
596
///////////////////////////////////////////////////////////////////////////////////////////////////
597
// PUBLIC API
598
///////////////////////////////////////////////////////////////////////////////////////////////////
599
/**
600
 * Create empty effect queue.
601
 */
602
  public DistortedEffects()
603
    {
604
    mID = ++mNextID;
605
    initializeEffectLists(this,0);
606
    }
607

    
608
///////////////////////////////////////////////////////////////////////////////////////////////////
609
/**
610
 * Copy constructor.
611
 * <p>
612
 * Whatever we do not clone gets created just like in the default constructor.
613
 *
614
 * @param dc    Source object to create our object from
615
 * @param flags A bitmask of values specifying what to copy.
616
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
617
 */
618
  public DistortedEffects(DistortedEffects dc, int flags)
619
    {
620
    mID = ++mNextID;
621
    initializeEffectLists(dc,flags);
622
    }
623

    
624
///////////////////////////////////////////////////////////////////////////////////////////////////
625
/**
626
 * Releases all resources. After this call, the queue should not be used anymore.
627
 */
628
  @SuppressWarnings("unused")
629
  public synchronized void delete()
630
    {
631
    releasePriv();
632
    }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635
/**
636
 * Returns unique ID of this instance.
637
 *
638
 * @return ID of the object.
639
 */
640
  public long getID()
641
      {
642
      return mID;
643
      }
644

    
645
///////////////////////////////////////////////////////////////////////////////////////////////////
646
/**
647
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
648
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
649
 * 
650
 * @param el A class implementing the EffectListener interface that wants to get notifications.
651
 */
652
  @SuppressWarnings("unused")
653
  public void registerForMessages(EffectListener el)
654
    {
655
    mM.registerForMessages(el);
656
    mV.registerForMessages(el);
657
    mF.registerForMessages(el);
658
    mP.registerForMessages(el);
659
    }
660

    
661
///////////////////////////////////////////////////////////////////////////////////////////////////
662
/**
663
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
664
 * 
665
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
666
 */
667
  @SuppressWarnings("unused")
668
  public void deregisterForMessages(EffectListener el)
669
    {
670
    mM.deregisterForMessages(el);
671
    mV.deregisterForMessages(el);
672
    mF.deregisterForMessages(el);
673
    mP.deregisterForMessages(el);
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677
/**
678
 * Aborts all Effects.
679
 * @return Number of effects aborted.
680
 */
681
  public int abortAllEffects()
682
    {
683
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
684
    }
685

    
686
///////////////////////////////////////////////////////////////////////////////////////////////////
687
/**
688
 * Aborts all Effects of a given type, for example all MATRIX Effects.
689
 * 
690
 * @param type one of the constants defined in {@link EffectType}
691
 * @return Number of effects aborted.
692
 */
693
  public int abortByType(EffectType type)
694
    {
695
    switch(type)
696
      {
697
      case MATRIX     : return mM.abortAll(true);
698
      case VERTEX     : return mV.abortAll(true);
699
      case FRAGMENT   : return mF.abortAll(true);
700
      case POSTPROCESS: return mP.abortAll(true);
701
      default         : return 0;
702
      }
703
    }
704

    
705
///////////////////////////////////////////////////////////////////////////////////////////////////
706
/**
707
 * Aborts an Effect by its ID.
708
 *
709
 * @param id the Id of the Effect to be removed, as returned by getID().
710
 * @return Number of effects aborted.
711
 */
712
  public int abortById(long id)
713
    {
714
    long type = id&EffectType.MASK;
715

    
716
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
717
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
718
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
719
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
720

    
721
    return 0;
722
    }
723

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725
/**
726
 * Aborts a single Effect.
727
 * 
728
 * @param effect the Effect we want to abort.
729
 * @return number of Effects aborted. Always either 0 or 1.
730
 */
731
  public int abortEffect(Effect effect)
732
    {
733
    switch(effect.getType())
734
      {
735
      case MATRIX     : return mM.removeEffect(effect);
736
      case VERTEX     : return mV.removeEffect(effect);
737
      case FRAGMENT   : return mF.removeEffect(effect);
738
      case POSTPROCESS: return mP.removeEffect(effect);
739
      default         : return 0;
740
      }
741
    }
742

    
743
///////////////////////////////////////////////////////////////////////////////////////////////////
744
/**
745
 * Abort all Effects of a given name, for example all rotations.
746
 * 
747
 * @param name one of the constants defined in {@link EffectName}
748
 * @return number of Effects aborted.
749
 */
750
  public int abortByName(EffectName name)
751
    {
752
    switch(name.getType())
753
      {
754
      case MATRIX     : return mM.removeByName(name);
755
      case VERTEX     : return mV.removeByName(name);
756
      case FRAGMENT   : return mF.removeByName(name);
757
      case POSTPROCESS: return mP.removeByName(name);
758
      default                : return 0;
759
      }
760
    }
761

    
762
///////////////////////////////////////////////////////////////////////////////////////////////////
763
/**
764
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
765
 * single (InputSurface,MeshObject) combo.
766
 *
767
 * @param type {@link EffectType}
768
 * @return The maximum number of effects of a given type.
769
 */
770
  @SuppressWarnings("unused")
771
  public static int getMax(EffectType type)
772
    {
773
    return EffectQueue.getMax(type.ordinal());
774
    }
775

    
776
///////////////////////////////////////////////////////////////////////////////////////////////////
777
/**
778
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
779
 * This can fail if:
780
 * <ul>
781
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
782
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
783
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
784
 *     time only decreasing the value of 'max' is permitted.
785
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
786
 * </ul>
787
 *
788
 * @param type {@link EffectType}
789
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
790
 *            than Byte.MAX_VALUE
791
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
792
 */
793
  @SuppressWarnings("unused")
794
  public static boolean setMax(EffectType type, int max)
795
    {
796
    return EffectQueue.setMax(type.ordinal(),max);
797
    }
798

    
799
///////////////////////////////////////////////////////////////////////////////////////////////////
800
/**
801
 * Add a new Effect to our queue.
802
 *
803
 * @param effect The Effect to add.
804
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
805
 */
806
  public boolean apply(Effect effect)
807
    {
808
    switch(effect.getType())
809
      {
810
      case MATRIX      : return mM.add(effect);
811
      case VERTEX      : return mV.add(effect);
812
      case FRAGMENT    : return mF.add(effect);
813
      case POSTPROCESS : return mP.add(effect);
814
      }
815

    
816
    return false;
817
    }
818
  }
(2-2/21)