Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 78e89fb5

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
import org.distorted.library.program.FragmentCompilationException;
35
import org.distorted.library.program.FragmentUniformsException;
36
import org.distorted.library.program.LinkingException;
37
import org.distorted.library.program.VertexCompilationException;
38
import org.distorted.library.program.VertexUniformsException;
39

    
40
import java.io.InputStream;
41
import java.nio.ByteBuffer;
42
import java.nio.ByteOrder;
43
import java.nio.FloatBuffer;
44
import java.nio.IntBuffer;
45

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

    
58
  /// BLIT PROGRAM ///
59
  private static DistortedProgram mBlitProgram;
60
  private static int mBlitTextureH;
61
  private static int mBlitDepthH;
62
  private static final FloatBuffer mQuadPositions;
63

    
64
  static
65
    {
66
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
67
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
68
    mQuadPositions.put(positionData).position(0);
69
    }
70

    
71
  /// BLIT DEPTH PROGRAM ///
72
  private static DistortedProgram mBlitDepthProgram;
73
  private static int mBlitDepthTextureH;
74
  private static int mBlitDepthDepthTextureH;
75
  private static int mBlitDepthDepthH;
76
  private static int mBlitDepthTexCorrH;
77
  private static int mBlitDepthSizeH;
78
  private static int mBlitDepthNumRecordsH;
79

    
80
  private static int[] mLinkedListSSBO = new int[1];
81
  private static int[] mAtomicCounter = new int[1];
82

    
83
  static
84
    {
85
    mLinkedListSSBO[0]= -1;
86
    mAtomicCounter[0] = -1;
87
    }
88

    
89
  private static int mBufferSize=(0x1<<23);  // 8 million entries
90

    
91
  /// BLIT DEPTH RENDER PROGRAM ///
92
  private static DistortedProgram mBlitDepthRenderProgram;
93
  private static int mBlitDepthRenderDepthTextureH;
94
  private static int mBlitDepthRenderDepthH;
95
  private static int mBlitDepthRenderTexCorrH;
96
  private static int mBlitDepthRenderSizeH;
97

    
98
  /// NORMAL PROGRAM /////
99
  private static DistortedProgram mNormalProgram;
100
  private static int mNormalMVPMatrixH;
101
  /// END PROGRAMS //////
102

    
103
  private static long mNextID =0;
104
  private long mID;
105

    
106
  private EffectQueueMatrix mM;
107
  private EffectQueueFragment mF;
108
  private EffectQueueVertex mV;
109
  private EffectQueuePostprocess mP;
110

    
111
  private boolean matrixCloned, vertexCloned, fragmentCloned, postprocessCloned;
112

    
113
///////////////////////////////////////////////////////////////////////////////////////////////////
114

    
115
  static void createProgram(Resources resources)
116
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
117
    {
118
    // MAIN PROGRAM ////////////////////////////////////
119
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
120
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
121

    
122
    int numF = FragmentEffect.getNumEnabled();
123
    int numV = VertexEffect.getNumEnabled();
124

    
125
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
126
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
127
    String enabledEffectV= VertexEffect.getGLSL();
128
    String enabledEffectF= FragmentEffect.getGLSL();
129

    
130
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
131
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
132
    //android.util.Log.e("Effects", "enabledV= "+enabledEffectV);
133
    //android.util.Log.e("Effects", "enabledF= "+enabledEffectF);
134

    
135
    String[] feedback = { "v_Position", "v_endPosition" };
136

    
137
    try
138
      {
139
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
140
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
141
      }
142
    catch(Exception e)
143
      {
144
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
145
      throw new RuntimeException(e.getMessage());
146
      }
147

    
148
    int mainProgramH = mMainProgram.getProgramHandle();
149
    EffectQueueFragment.getUniforms(mainProgramH);
150
    EffectQueueVertex.getUniforms(mainProgramH);
151
    EffectQueueMatrix.getUniforms(mainProgramH);
152
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
153

    
154
    // BLIT PROGRAM ////////////////////////////////////
155
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
156
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
157

    
158
    String blitVertHeader= (Distorted.GLSL_VERSION + "#define NUM_VERTEX 0\n"  );
159
    String blitFragHeader= (Distorted.GLSL_VERSION + "#define NUM_FRAGMENT 0\n");
160

    
161
    try
162
      {
163
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,blitVertHeader,blitFragHeader, Distorted.GLSL);
164
      }
165
    catch(Exception e)
166
      {
167
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
168
      throw new RuntimeException(e.getMessage());
169
      }
170

    
171
    int blitProgramH = mBlitProgram.getProgramHandle();
172
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
173
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
174

    
175
    // BLIT DEPTH PROGRAM ////////////////////////////////////
176
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
177
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
178

    
179
    try
180
      {
181
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,blitVertHeader,blitFragHeader, Distorted.GLSL);
182
      }
183
    catch(Exception e)
184
      {
185
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
186
      throw new RuntimeException(e.getMessage());
187
      }
188

    
189
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
190
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
191
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
192
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
193
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
194
    mBlitDepthSizeH         = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Size");
195
    mBlitDepthNumRecordsH   = GLES31.glGetUniformLocation( blitDepthProgramH, "u_numRecords");
196

    
197
    if( mLinkedListSSBO[0]<0 )
198
      {
199
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
200
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
201
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
202
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
203
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
204
      }
205

    
206
    if( mAtomicCounter[0]<0 )
207
      {
208
      GLES31.glGenBuffers(1,mAtomicCounter,0);
209
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[0]);
210
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
211
      GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
212
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
213
      }
214

    
215
    // BLIT DEPTH RENDER PROGRAM ///////////////////////////
216
    final InputStream blitDepthRenderVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
217
    final InputStream blitDepthRenderFragStream = resources.openRawResource(R.raw.blit_depth_render_fragment_shader);
218

    
219
    try
220
      {
221
      mBlitDepthRenderProgram = new DistortedProgram(blitDepthRenderVertStream,blitDepthRenderFragStream,blitVertHeader,blitFragHeader, Distorted.GLSL);
222
      }
223
    catch(Exception e)
224
      {
225
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH RENDER program: "+e.getMessage());
226
      throw new RuntimeException(e.getMessage());
227
      }
228

    
229
    int blitDepthRenderProgramH   = mBlitDepthRenderProgram.getProgramHandle();
230
    mBlitDepthRenderDepthTextureH = GLES31.glGetUniformLocation( blitDepthRenderProgramH, "u_DepthTexture");
231
    mBlitDepthRenderDepthH        = GLES31.glGetUniformLocation( blitDepthRenderProgramH, "u_Depth");
232
    mBlitDepthRenderTexCorrH      = GLES31.glGetUniformLocation( blitDepthRenderProgramH, "u_TexCorr");
233
    mBlitDepthRenderSizeH         = GLES31.glGetUniformLocation( blitDepthRenderProgramH, "u_Size");
234

    
235
    // NORMAL PROGRAM //////////////////////////////////////
236
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
237
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
238

    
239
    try
240
      {
241
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
242
      }
243
    catch(Exception e)
244
      {
245
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
246
      throw new RuntimeException(e.getMessage());
247
      }
248

    
249
    int normalProgramH = mNormalProgram.getProgramHandle();
250
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
251
    }
252

    
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254

    
255
  private void initializeEffectLists(DistortedEffects d, int flags)
256
    {
257
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
258
      {
259
      mM = d.mM;
260
      matrixCloned = true;
261
      }
262
    else
263
      {
264
      mM = new EffectQueueMatrix(mID);
265
      matrixCloned = false;
266
      }
267
    
268
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
269
      {
270
      mV = d.mV;
271
      vertexCloned = true;
272
      }
273
    else
274
      {
275
      mV = new EffectQueueVertex(mID);
276
      vertexCloned = false;
277
      }
278
    
279
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
280
      {
281
      mF = d.mF;
282
      fragmentCloned = true;
283
      }
284
    else
285
      {
286
      mF = new EffectQueueFragment(mID);
287
      fragmentCloned = false;
288
      }
289

    
290
    if( (flags & Distorted.CLONE_POSTPROCESS) != 0 )
291
      {
292
      mP = d.mP;
293
      postprocessCloned = true;
294
      }
295
    else
296
      {
297
      mP = new EffectQueuePostprocess(mID);
298
      postprocessCloned = false;
299
      }
300
    }
301

    
302
///////////////////////////////////////////////////////////////////////////////////////////////////
303

    
304
  EffectQueuePostprocess getPostprocess()
305
    {
306
    return mP;
307
    }
308

    
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310

    
311
  void newNode(DistortedNode node)
312
    {
313
    mM.newNode(node);
314
    mF.newNode(node);
315
    mV.newNode(node);
316
    mP.newNode(node);
317
    }
318

    
319
///////////////////////////////////////////////////////////////////////////////////////////////////
320

    
321
  private void displayNormals(MeshObject mesh)
322
    {
323
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
324
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
325
    DistortedRenderState.switchOffDrawing();
326
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
327
    DistortedRenderState.restoreDrawing();
328
    GLES31.glEndTransformFeedback();
329
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
330

    
331
    mNormalProgram.useProgram();
332
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
333
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttTFO[0]);
334
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
335
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
336
    GLES31.glLineWidth(8.0f);
337
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*mesh.numVertices);
338
    }
339

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341

    
342
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
343
    {
344
    float halfZ = halfW*mesh.zFactor;
345

    
346
    mM.compute(currTime);
347
    mV.compute(currTime,halfW,halfH,halfZ);
348
    mF.compute(currTime,halfW,halfH);
349
    mP.compute(currTime);
350

    
351
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
352

    
353
    mMainProgram.useProgram();
354
    GLES31.glUniform1i(mMainTextureH, 0);
355

    
356
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
357
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
358
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
359
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
360
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
361

    
362
    mM.send(surface,halfW,halfH,halfZ,marginInPixels);
363
    mV.send();
364
    mF.send();
365

    
366
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
367

    
368
    if( mesh.mShowNormals ) displayNormals(mesh);
369
    }
370

    
371
///////////////////////////////////////////////////////////////////////////////////////////////////
372
/**
373
 * Only for use by the library itself.
374
 *
375
 * @y.exclude
376
 */
377
  public static void blitPriv(DistortedOutputSurface surface)
378
    {
379
    mBlitProgram.useProgram();
380

    
381
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
382
    GLES31.glUniform1i(mBlitTextureH, 0);
383
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
384
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
385
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
386
    }
387

    
388
///////////////////////////////////////////////////////////////////////////////////////////////////
389
// reset atomic counter to 0
390

    
391
  static void zeroOutAtomic()
392
    {
393
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
394

    
395
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
396
                                                                GLES31.GL_MAP_READ_BIT|GLES31.GL_MAP_WRITE_BIT);
397
    if( atomicBuf!=null )
398
      {
399
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
400

    
401
      //int counter = atomicIntBuf.get(0);
402
      //android.util.Log.e("counter", "now = "+counter+" w="+surface.mWidth+" h="+surface.mHeight
403
      //                             +" diff="+(counter-surface.mWidth*surface.mHeight));
404
      atomicIntBuf.put(0,0);
405
      }
406
    else
407
      {
408
      android.util.Log.e("effects", "failed to map atomic buffer");
409
      }
410

    
411
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
412
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
413
    }
414

    
415
///////////////////////////////////////////////////////////////////////////////////////////////////
416

    
417
  static void blitDepth(DistortedOutputSurface surface, float corrW, float corrH)
418
    {
419
    mBlitDepthProgram.useProgram();
420

    
421
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
422
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
423
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
424
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
425
    GLES31.glUniform2f(mBlitDepthSizeH, surface.mWidth, surface.mHeight);
426
    GLES31.glUniform1ui(mBlitDepthNumRecordsH, (mBufferSize-surface.mWidth*surface.mHeight)/3 );  // see the fragment shader
427
    GLES31.glUniform1f(mBlitDepthDepthH , 1.0f-surface.mNear);
428
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
429
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
430
    }
431

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433
// render all the transparent pixels from the per-pixel linked lists. This is in the 'merge
434
// postprocessing buckets' stage.
435

    
436
  static void mergeOIT(DistortedOutputSurface surface, float corrW, float corrH)
437
    {
438
    mBlitDepthRenderProgram.useProgram();
439

    
440
    //analyzeBuffer(surface.mWidth, surface.mHeight);
441

    
442
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
443
    GLES31.glUniform1i(mBlitDepthRenderDepthTextureH, 1);
444
    GLES31.glUniform2f(mBlitDepthRenderTexCorrH, corrW, corrH );
445
    GLES31.glUniform2f(mBlitDepthRenderSizeH, surface.mWidth, surface.mHeight);
446
    GLES31.glUniform1f( mBlitDepthRenderDepthH , 1.0f-surface.mNear);
447
    GLES31.glVertexAttribPointer(mBlitDepthRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
448
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
449
    }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452

    
453
  private static void analyzeBuffer(int w, int h)
454
    {
455
    int ptr, index;
456
    int errors = 0;
457

    
458
    GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
459
    ByteBuffer buf = (ByteBuffer)GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, mBufferSize*4, GLES31.GL_MAP_READ_BIT);
460
    IntBuffer intBuf = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
461

    
462
    for(int col=0; col<w; col++)
463
      for(int row=0; row<h; row++)
464
        {
465
        index = col+row*w;
466
        ptr = intBuf.get(index);
467

    
468
        if( ptr!=0 )
469
          {
470
          if( ptr>0 && ptr<mBufferSize )
471
            {
472
            ptr = intBuf.get(ptr);
473
            if( ptr != index )
474
              {
475
              android.util.Log.d("surface", "col="+col+" row="+row+" val="+ptr+" expected: "+index);
476
              errors++;
477
              }
478
            }
479
          else
480
            {
481
            android.util.Log.d("surface", "overflow!");
482
            }
483
          }
484
        }
485

    
486
    GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER);
487
    GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
488

    
489
    if( errors>0 ) android.util.Log.e("surface", "errors: "+errors);
490
    }
491

    
492
///////////////////////////////////////////////////////////////////////////////////////////////////
493

    
494
  private void releasePriv()
495
    {
496
    if( !matrixCloned   )   mM.abortAll(false);
497
    if( !vertexCloned   )   mV.abortAll(false);
498
    if( !fragmentCloned )   mF.abortAll(false);
499
    if( !postprocessCloned) mP.abortAll(false);
500

    
501
    mM = null;
502
    mV = null;
503
    mF = null;
504
    mP = null;
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508

    
509
  static void onPause()
510
    {
511
    mLinkedListSSBO[0]= -1;
512
    mAtomicCounter[0] = -1;
513
    }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516

    
517
  static void onDestroy()
518
    {
519
    mNextID =  0;
520
    }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523
// PUBLIC API
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525
/**
526
 * Create empty effect queue.
527
 */
528
  public DistortedEffects()
529
    {
530
    mID = ++mNextID;
531
    initializeEffectLists(this,0);
532
    }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535
/**
536
 * Copy constructor.
537
 * <p>
538
 * Whatever we do not clone gets created just like in the default constructor.
539
 *
540
 * @param dc    Source object to create our object from
541
 * @param flags A bitmask of values specifying what to copy.
542
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
543
 */
544
  public DistortedEffects(DistortedEffects dc, int flags)
545
    {
546
    mID = ++mNextID;
547
    initializeEffectLists(dc,flags);
548
    }
549

    
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551
/**
552
 * Releases all resources. After this call, the queue should not be used anymore.
553
 */
554
  @SuppressWarnings("unused")
555
  public synchronized void delete()
556
    {
557
    releasePriv();
558
    }
559

    
560
///////////////////////////////////////////////////////////////////////////////////////////////////
561
/**
562
 * Returns unique ID of this instance.
563
 *
564
 * @return ID of the object.
565
 */
566
  public long getID()
567
      {
568
      return mID;
569
      }
570

    
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572
/**
573
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
574
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
575
 * 
576
 * @param el A class implementing the EffectListener interface that wants to get notifications.
577
 */
578
  @SuppressWarnings("unused")
579
  public void registerForMessages(EffectListener el)
580
    {
581
    mM.registerForMessages(el);
582
    mV.registerForMessages(el);
583
    mF.registerForMessages(el);
584
    mP.registerForMessages(el);
585
    }
586

    
587
///////////////////////////////////////////////////////////////////////////////////////////////////
588
/**
589
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
590
 * 
591
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
592
 */
593
  @SuppressWarnings("unused")
594
  public void deregisterForMessages(EffectListener el)
595
    {
596
    mM.deregisterForMessages(el);
597
    mV.deregisterForMessages(el);
598
    mF.deregisterForMessages(el);
599
    mP.deregisterForMessages(el);
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603
/**
604
 * Aborts all Effects.
605
 * @return Number of effects aborted.
606
 */
607
  public int abortAllEffects()
608
    {
609
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
610
    }
611

    
612
///////////////////////////////////////////////////////////////////////////////////////////////////
613
/**
614
 * Aborts all Effects of a given type, for example all MATRIX Effects.
615
 * 
616
 * @param type one of the constants defined in {@link EffectType}
617
 * @return Number of effects aborted.
618
 */
619
  public int abortByType(EffectType type)
620
    {
621
    switch(type)
622
      {
623
      case MATRIX     : return mM.abortAll(true);
624
      case VERTEX     : return mV.abortAll(true);
625
      case FRAGMENT   : return mF.abortAll(true);
626
      case POSTPROCESS: return mP.abortAll(true);
627
      default         : return 0;
628
      }
629
    }
630

    
631
///////////////////////////////////////////////////////////////////////////////////////////////////
632
/**
633
 * Aborts an Effect by its ID.
634
 *
635
 * @param id the Id of the Effect to be removed, as returned by getID().
636
 * @return Number of effects aborted.
637
 */
638
  public int abortById(long id)
639
    {
640
    long type = id&EffectType.MASK;
641

    
642
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
643
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
644
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
645
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
646

    
647
    return 0;
648
    }
649

    
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
/**
652
 * Aborts a single Effect.
653
 * 
654
 * @param effect the Effect we want to abort.
655
 * @return number of Effects aborted. Always either 0 or 1.
656
 */
657
  public int abortEffect(Effect effect)
658
    {
659
    switch(effect.getType())
660
      {
661
      case MATRIX     : return mM.removeEffect(effect);
662
      case VERTEX     : return mV.removeEffect(effect);
663
      case FRAGMENT   : return mF.removeEffect(effect);
664
      case POSTPROCESS: return mP.removeEffect(effect);
665
      default         : return 0;
666
      }
667
    }
668

    
669
///////////////////////////////////////////////////////////////////////////////////////////////////
670
/**
671
 * Abort all Effects of a given name, for example all rotations.
672
 * 
673
 * @param name one of the constants defined in {@link EffectName}
674
 * @return number of Effects aborted.
675
 */
676
  public int abortByName(EffectName name)
677
    {
678
    switch(name.getType())
679
      {
680
      case MATRIX     : return mM.removeByName(name);
681
      case VERTEX     : return mV.removeByName(name);
682
      case FRAGMENT   : return mF.removeByName(name);
683
      case POSTPROCESS: return mP.removeByName(name);
684
      default                : return 0;
685
      }
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689
/**
690
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
691
 * single (InputSurface,MeshObject) combo.
692
 *
693
 * @param type {@link EffectType}
694
 * @return The maximum number of effects of a given type.
695
 */
696
  @SuppressWarnings("unused")
697
  public static int getMax(EffectType type)
698
    {
699
    return EffectQueue.getMax(type.ordinal());
700
    }
701

    
702
///////////////////////////////////////////////////////////////////////////////////////////////////
703
/**
704
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
705
 * This can fail if:
706
 * <ul>
707
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
708
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
709
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
710
 *     time only decreasing the value of 'max' is permitted.
711
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
712
 * </ul>
713
 *
714
 * @param type {@link EffectType}
715
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
716
 *            than Byte.MAX_VALUE
717
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
718
 */
719
  @SuppressWarnings("unused")
720
  public static boolean setMax(EffectType type, int max)
721
    {
722
    return EffectQueue.setMax(type.ordinal(),max);
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726
/**
727
 * Add a new Effect to our queue.
728
 *
729
 * @param effect The Effect to add.
730
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
731
 */
732
  public boolean apply(Effect effect)
733
    {
734
    switch(effect.getType())
735
      {
736
      case MATRIX      : return mM.add(effect);
737
      case VERTEX      : return mV.add(effect);
738
      case FRAGMENT    : return mF.add(effect);
739
      case POSTPROCESS : return mP.add(effect);
740
      }
741

    
742
    return false;
743
    }
744
  }
(2-2/21)