Project

General

Profile

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

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

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 createPrograms(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
    // NORMAL PROGRAM //////////////////////////////////////
210
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
211
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
212

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

    
223
    int normalProgramH = mNormalProgram.getProgramHandle();
224
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
225
    }
226

    
227
  ///////////////////////////////////////////////////////////////////////////////////////////////////
228

    
229
  static void createProgramsOIT(Resources resources)
230
    {
231
    // OIT CLEAR PROGRAM ////////////////////////////////////
232
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
233
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
234

    
235
    try
236
      {
237
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
238
      }
239
    catch(Exception e)
240
      {
241
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
242
      throw new RuntimeException(e.getMessage());
243
      }
244

    
245
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
246
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
247
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
248
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
249

    
250
    // OIT BUILD PROGRAM ////////////////////////////////////
251
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
252
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
253

    
254
    try
255
      {
256
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
257
      }
258
    catch(Exception e)
259
      {
260
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
261
      throw new RuntimeException(e.getMessage());
262
      }
263

    
264
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
265
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
266
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
267
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
268
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
269
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
270
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
271

    
272
    if( mLinkedListSSBO[0]<0 )
273
      {
274
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
275
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
276
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
277
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
278
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
279
      }
280

    
281
    if( mAtomicCounter[0]<0 )
282
      {
283
      GLES31.glGenBuffers(1,mAtomicCounter,0);
284
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[0]);
285
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
286
      GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
287
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
288
      }
289

    
290
    // OIT COLLAPSE PROGRAM ///////////////////////////
291
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
292
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
293

    
294
    try
295
      {
296
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
297
      }
298
    catch(Exception e)
299
      {
300
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
301
      throw new RuntimeException(e.getMessage());
302
      }
303

    
304
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
305
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
306
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
307
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
308
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
309

    
310
    // OIT RENDER PROGRAM ///////////////////////////
311
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
312
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
313

    
314
    try
315
      {
316
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
317
      }
318
    catch(Exception e)
319
      {
320
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
321
      throw new RuntimeException(e.getMessage());
322
      }
323

    
324
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
325
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
326
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
327
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

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

    
367
    if( (flags & Distorted.CLONE_POSTPROCESS) != 0 )
368
      {
369
      mP = d.mP;
370
      postprocessCloned = true;
371
      }
372
    else
373
      {
374
      mP = new EffectQueuePostprocess(mID);
375
      postprocessCloned = false;
376
      }
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
  EffectQueuePostprocess getPostprocess()
382
    {
383
    return mP;
384
    }
385

    
386
///////////////////////////////////////////////////////////////////////////////////////////////////
387

    
388
  void newNode(DistortedNode node)
389
    {
390
    mM.newNode(node);
391
    mF.newNode(node);
392
    mV.newNode(node);
393
    mP.newNode(node);
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397

    
398
  private void displayNormals(MeshObject mesh)
399
    {
400
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
401
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
402
    DistortedRenderState.switchOffDrawing();
403
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
404
    DistortedRenderState.restoreDrawing();
405
    GLES31.glEndTransformFeedback();
406
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
407

    
408
    mNormalProgram.useProgram();
409
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
410
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttTFO[0]);
411
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
412
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
413
    GLES31.glLineWidth(8.0f);
414
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*mesh.numVertices);
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

    
419
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
420
    {
421
    float halfZ = halfW*mesh.zFactor;
422

    
423
    mM.compute(currTime);
424
    mV.compute(currTime,halfW,halfH,halfZ);
425
    mF.compute(currTime,halfW,halfH);
426
    mP.compute(currTime);
427

    
428
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
429

    
430
    mMainProgram.useProgram();
431
    GLES31.glUniform1i(mMainTextureH, 0);
432

    
433
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
434
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
435
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
436
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
437
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
438

    
439
    mM.send(surface,halfW,halfH,halfZ,marginInPixels);
440
    mV.send();
441
    mF.send();
442

    
443
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
444

    
445
    if( mesh.mShowNormals ) displayNormals(mesh);
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449
/**
450
 * Only for use by the library itself.
451
 *
452
 * @y.exclude
453
 */
454
  public static void blitPriv(DistortedOutputSurface surface)
455
    {
456
    mBlitProgram.useProgram();
457

    
458
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
459
    GLES31.glUniform1i(mBlitTextureH, 0);
460
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
461
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
462
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466

    
467
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
468
    {
469
    mBlitDepthProgram.useProgram();
470

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

    
480
///////////////////////////////////////////////////////////////////////////////////////////////////
481
// reset atomic counter to 0
482

    
483
  static void zeroOutAtomic()
484
    {
485
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
486

    
487
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
488
                                                                GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
489
    if( atomicBuf!=null )
490
      {
491
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
492

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

    
503
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
504
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
509

    
510
  static void oitClear(DistortedOutputSurface surface)
511
    {
512
    mOITClearProgram.useProgram();
513

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

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523
// Pass2 of the OIT algorithm - build per-pixel linked lists.
524

    
525
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
526
    {
527
    mOITBuildProgram.useProgram();
528

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

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
542

    
543
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
544
    {
545
    mOITCollapseProgram.useProgram();
546

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

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
558

    
559
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
560
    {
561
    mOITRenderProgram.useProgram();
562

    
563
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
564
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
565
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
566
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
567
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
568
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
569
    }
570

    
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572

    
573
  private void releasePriv()
574
    {
575
    if( !matrixCloned      ) mM.abortAll(false);
576
    if( !vertexCloned      ) mV.abortAll(false);
577
    if( !fragmentCloned    ) mF.abortAll(false);
578
    if( !postprocessCloned ) mP.abortAll(false);
579

    
580
    mM = null;
581
    mV = null;
582
    mF = null;
583
    mP = null;
584
    }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

    
588
  static void onPause()
589
    {
590
    mLinkedListSSBO[0]= -1;
591
    mAtomicCounter[0] = -1;
592
    }
593

    
594
///////////////////////////////////////////////////////////////////////////////////////////////////
595

    
596
  static void onDestroy()
597
    {
598
    mNextID =  0;
599
    }
600

    
601
///////////////////////////////////////////////////////////////////////////////////////////////////
602
// PUBLIC API
603
///////////////////////////////////////////////////////////////////////////////////////////////////
604
/**
605
 * Create empty effect queue.
606
 */
607
  public DistortedEffects()
608
    {
609
    mID = ++mNextID;
610
    initializeEffectLists(this,0);
611
    }
612

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

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630
/**
631
 * Releases all resources. After this call, the queue should not be used anymore.
632
 */
633
  @SuppressWarnings("unused")
634
  public synchronized void delete()
635
    {
636
    releasePriv();
637
    }
638

    
639
///////////////////////////////////////////////////////////////////////////////////////////////////
640
/**
641
 * Returns unique ID of this instance.
642
 *
643
 * @return ID of the object.
644
 */
645
  public long getID()
646
      {
647
      return mID;
648
      }
649

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

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

    
681
///////////////////////////////////////////////////////////////////////////////////////////////////
682
/**
683
 * Aborts all Effects.
684
 * @return Number of effects aborted.
685
 */
686
  public int abortAllEffects()
687
    {
688
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
689
    }
690

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

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

    
721
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
722
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
723
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
724
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
725

    
726
    return 0;
727
    }
728

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

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

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

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

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

    
821
    return false;
822
    }
823
  }
(2-2/21)