Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 466450b5

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
  /// NORMAL PROGRAM /////
74
  private static DistortedProgram mNormalProgram;
75
  private static int mNormalMVPMatrixH;
76

    
77
  /// OIT SSBO BUFFER ///
78
  private static int[] mLinkedListSSBO = new int[1];
79
  private static int[] mAtomicCounter = new int[Distorted.FBO_QUEUE_SIZE];
80
  private static int   mCurrBuffer;
81

    
82
  static
83
    {
84
    mLinkedListSSBO[0]= -1;
85
    mCurrBuffer       =  0;
86

    
87
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)  mAtomicCounter[i] = -1;
88
    }
89

    
90
  ///////////////////////////////////////////////////////////////
91
  // meaning: allocate 1.0 screenful of places for transparent
92
  // fragments in the SSBO backing up the OIT render method.
93
  private static float mBufferSize=1.0f;
94

    
95
  /// OIT CLEAR PROGRAM ///
96
  private static DistortedProgram mOITClearProgram;
97
  private static int mOITClearDepthH;
98
  private static int mOITClearTexCorrH;
99
  private static int mOITClearSizeH;
100

    
101
  /// OIT BUILD PROGRAM ///
102
  private static DistortedProgram mOITBuildProgram;
103
  private static int mOITBuildTextureH;
104
  private static int mOITBuildDepthTextureH;
105
  private static int mOITBuildDepthH;
106
  private static int mOITBuildTexCorrH;
107
  private static int mOITBuildSizeH;
108
  private static int mOITBuildNumRecordsH;
109

    
110
  /// OIT COLLAPSE PROGRAM ///
111
  private static DistortedProgram mOITCollapseProgram;
112
  private static int mOITCollapseDepthTextureH;
113
  private static int mOITCollapseDepthH;
114
  private static int mOITCollapseTexCorrH;
115
  private static int mOITCollapseSizeH;
116

    
117
  /// OIT RENDER PROGRAM ///
118
  private static DistortedProgram mOITRenderProgram;
119
  private static int mOITRenderDepthH;
120
  private static int mOITRenderTexCorrH;
121
  private static int mOITRenderSizeH;
122

    
123
  /// MAIN OIT PROGRAM ///
124
  private static DistortedProgram mMainOITProgram;
125
  private static int mMainOITTextureH;
126
  private static int mMainOITSizeH;
127
  private static int mMainOITNumRecordsH;
128
  /// END PROGRAMS //////
129

    
130
  private static long mNextID =0;
131
  private long mID;
132

    
133
  private EffectQueueMatrix mM;
134
  private EffectQueueFragment mF;
135
  private EffectQueueVertex mV;
136
  private EffectQueuePostprocess mP;
137

    
138
  private boolean matrixCloned, vertexCloned, fragmentCloned, postprocessCloned;
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

    
142
  static void createPrograms(Resources resources)
143
    {
144
    // MAIN PROGRAM ////////////////////////////////////
145
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
146
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
147

    
148
    int numF = FragmentEffect.getNumEnabled();
149
    int numV = VertexEffect.getNumEnabled();
150

    
151
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
152
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
153
    String enabledEffectV= VertexEffect.getGLSL();
154
    String enabledEffectF= FragmentEffect.getGLSL();
155

    
156
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
157
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
158
    //android.util.Log.e("Effects", "enabledV= "+enabledEffectV);
159
    //android.util.Log.e("Effects", "enabledF= "+enabledEffectF);
160

    
161
    String[] feedback = { "v_Position", "v_endPosition" };
162

    
163
    try
164
      {
165
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
166
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
167
      }
168
    catch(Exception e)
169
      {
170
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
171
      throw new RuntimeException(e.getMessage());
172
      }
173

    
174
    int mainProgramH = mMainProgram.getProgramHandle();
175
    EffectQueueFragment.getUniforms(mainProgramH,0);
176
    EffectQueueVertex.getUniforms(mainProgramH,0);
177
    EffectQueueMatrix.getUniforms(mainProgramH,0);
178
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
179

    
180
    // BLIT PROGRAM ////////////////////////////////////
181
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
182
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
183

    
184
    try
185
      {
186
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
187
      }
188
    catch(Exception e)
189
      {
190
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
191
      throw new RuntimeException(e.getMessage());
192
      }
193

    
194
    int blitProgramH = mBlitProgram.getProgramHandle();
195
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
196
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
197

    
198
    // BLIT DEPTH PROGRAM ////////////////////////////////////
199
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
200
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
201

    
202
    try
203
      {
204
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
205
      }
206
    catch(Exception e)
207
      {
208
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
209
      throw new RuntimeException(e.getMessage());
210
      }
211

    
212
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
213
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
214
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
215
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
216
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
217

    
218
    // NORMAL PROGRAM //////////////////////////////////////
219
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
220
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
221

    
222
    try
223
      {
224
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
225
      }
226
    catch(Exception e)
227
      {
228
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
229
      throw new RuntimeException(e.getMessage());
230
      }
231

    
232
    int normalProgramH = mNormalProgram.getProgramHandle();
233
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

    
238
  static void createProgramsOIT(Resources resources)
239
    {
240
    // MAIN OIT PROGRAM ////////////////////////////////
241
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
242
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
243

    
244
    int numF = FragmentEffect.getNumEnabled();
245
    int numV = VertexEffect.getNumEnabled();
246

    
247
    String mainVertHeader= Distorted.GLSL_VERSION +
248
                           ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") +
249
                           ("#define OIT\n");
250
    String mainFragHeader= Distorted.GLSL_VERSION +
251
                           ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") +
252
                           ("#define OIT\n");
253

    
254
    String enabledEffectV= VertexEffect.getGLSL();
255
    String enabledEffectF= FragmentEffect.getGLSL();
256

    
257
    try
258
      {
259
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
260
                                             enabledEffectV, enabledEffectF, Distorted.GLSL, null);
261
      }
262
    catch(Exception e)
263
      {
264
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
265
      throw new RuntimeException(e.getMessage());
266
      }
267

    
268
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
269
    EffectQueueFragment.getUniforms(mainOITProgramH,1);
270
    EffectQueueVertex.getUniforms(mainOITProgramH,1);
271
    EffectQueueMatrix.getUniforms(mainOITProgramH,1);
272
    mMainOITTextureH    = GLES31.glGetUniformLocation( mainOITProgramH, "u_Texture");
273
    mMainOITSizeH       = GLES31.glGetUniformLocation( mainOITProgramH, "u_Size");
274
    mMainOITNumRecordsH = GLES31.glGetUniformLocation( mainOITProgramH, "u_numRecords");
275

    
276
    // OIT CLEAR PROGRAM ////////////////////////////////////
277
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
278
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
279

    
280
    try
281
      {
282
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
283
      }
284
    catch(Exception e)
285
      {
286
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
287
      throw new RuntimeException(e.getMessage());
288
      }
289

    
290
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
291
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
292
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
293
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
294

    
295
    // OIT BUILD PROGRAM ////////////////////////////////////
296
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
297
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
298

    
299
    try
300
      {
301
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
302
      }
303
    catch(Exception e)
304
      {
305
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
306
      throw new RuntimeException(e.getMessage());
307
      }
308

    
309
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
310
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
311
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
312
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
313
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
314
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
315
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
316

    
317
    // OIT COLLAPSE PROGRAM ///////////////////////////
318
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
319
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
320

    
321
    try
322
      {
323
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
324
      }
325
    catch(Exception e)
326
      {
327
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
328
      throw new RuntimeException(e.getMessage());
329
      }
330

    
331
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
332
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
333
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
334
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
335
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
336

    
337
    // OIT RENDER PROGRAM ///////////////////////////
338
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
339
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
340

    
341
    try
342
      {
343
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
344
      }
345
    catch(Exception e)
346
      {
347
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
348
      throw new RuntimeException(e.getMessage());
349
      }
350

    
351
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
352
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
353
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
354
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  private void initializeEffectLists(DistortedEffects d, int flags)
360
    {
361
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
362
      {
363
      mM = d.mM;
364
      matrixCloned = true;
365
      }
366
    else
367
      {
368
      mM = new EffectQueueMatrix(mID);
369
      matrixCloned = false;
370
      }
371
    
372
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
373
      {
374
      mV = d.mV;
375
      vertexCloned = true;
376
      }
377
    else
378
      {
379
      mV = new EffectQueueVertex(mID);
380
      vertexCloned = false;
381
      }
382
    
383
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
384
      {
385
      mF = d.mF;
386
      fragmentCloned = true;
387
      }
388
    else
389
      {
390
      mF = new EffectQueueFragment(mID);
391
      fragmentCloned = false;
392
      }
393

    
394
    if( (flags & Distorted.CLONE_POSTPROCESS) != 0 )
395
      {
396
      mP = d.mP;
397
      postprocessCloned = true;
398
      }
399
    else
400
      {
401
      mP = new EffectQueuePostprocess(mID);
402
      postprocessCloned = false;
403
      }
404
    }
405

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407

    
408
  EffectQueuePostprocess getPostprocess()
409
    {
410
    return mP;
411
    }
412

    
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414

    
415
  void newNode(DistortedNode node)
416
    {
417
    mM.newNode(node);
418
    mF.newNode(node);
419
    mV.newNode(node);
420
    mP.newNode(node);
421
    }
422

    
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424

    
425
  private void displayNormals(MeshObject mesh)
426
    {
427
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.getTFO() );
428
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
429
    DistortedRenderState.switchOffDrawing();
430
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
431
    DistortedRenderState.restoreDrawing();
432
    GLES31.glEndTransformFeedback();
433
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
434

    
435
    mNormalProgram.useProgram();
436
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
437
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getTFO() );
438
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
439
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
440
    GLES31.glLineWidth(8.0f);
441
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*mesh.numVertices);
442
    }
443

    
444
///////////////////////////////////////////////////////////////////////////////////////////////////
445

    
446
  void send(float halfW, float halfH, float halfZ, float margin, DistortedOutputSurface surface, int variant)
447
    {
448
    mM.send(surface,halfW,halfH,halfZ,margin,variant);
449
    mV.send(variant);
450
    }
451

    
452
///////////////////////////////////////////////////////////////////////////////////////////////////
453

    
454
  void drawPrivOIT(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
455
    {
456
    float halfZ = halfW*mesh.zFactor;
457

    
458
    mM.compute(currTime);
459
    mV.compute(currTime,halfW,halfH,halfZ);
460
    mF.compute(currTime,halfW,halfH);
461
    mP.compute(currTime);
462

    
463
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
464

    
465
    mMainOITProgram.useProgram();
466
    GLES31.glUniform1i(mMainOITTextureH, 0);
467
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
468
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
469

    
470
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getVBO() );
471
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
472
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
473
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
474
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
475

    
476
    mM.send(surface,halfW,halfH,halfZ,0,1);
477
    mV.send(1);
478
    mF.send(1);
479

    
480
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
481

    
482
    if( mesh.mShowNormals )
483
      {
484
      mMainProgram.useProgram();
485
      mM.send(surface,halfW,halfH,halfZ,0,0);
486
      mV.send(0);
487
      mF.send(0);
488
      displayNormals(mesh);
489
      }
490
    }
491

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

    
494
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
495
    {
496
    float halfZ = halfW*mesh.zFactor;
497

    
498
    mM.compute(currTime);
499
    mV.compute(currTime,halfW,halfH,halfZ);
500
    mF.compute(currTime,halfW,halfH);
501
    mP.compute(currTime);
502

    
503
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
504

    
505
    mMainProgram.useProgram();
506
    GLES31.glUniform1i(mMainTextureH, 0);
507

    
508
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getVBO() );
509
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
510
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
511
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
512
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
513

    
514
    mM.send(surface,halfW,halfH,halfZ,0,0);
515
    mV.send(0);
516
    mF.send(0);
517

    
518
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
519

    
520
    if( mesh.mShowNormals ) displayNormals(mesh);
521
    }
522

    
523
///////////////////////////////////////////////////////////////////////////////////////////////////
524
/**
525
 * Only for use by the library itself.
526
 *
527
 * @y.exclude
528
 */
529
  public static void blitPriv(DistortedOutputSurface surface)
530
    {
531
    mBlitProgram.useProgram();
532

    
533
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
534
    GLES31.glUniform1i(mBlitTextureH, 0);
535
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
536
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
537
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
538
    }
539

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541

    
542
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
543
    {
544
    mBlitDepthProgram.useProgram();
545

    
546
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
547
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
548
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
549
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
550
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
551
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
552
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
553
    }
554

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556

    
557
  private static int printPreviousBuffer()
558
    {
559
    int counter = 0;
560

    
561
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
562
                                                                GLES31.GL_MAP_READ_BIT);
563
    if( atomicBuf!=null )
564
      {
565
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
566
      counter = atomicIntBuf.get(0);
567
      }
568
    else
569
      {
570
      android.util.Log.e("effects", "print: failed to map atomic buffer");
571
      }
572

    
573
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
574

    
575
    return counter;
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579

    
580
  private static void zeroBuffer()
581
    {
582
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
583
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
584
    if( atomicBuf!=null )
585
      {
586
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
587
      atomicIntBuf.put(0,0);
588
      }
589
    else
590
      {
591
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
592
      }
593

    
594
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
595
    }
596

    
597
///////////////////////////////////////////////////////////////////////////////////////////////////
598
// reset atomic counter to 0
599

    
600
  static int zeroOutAtomic()
601
    {
602
    int counter = 0;
603

    
604
    if( mAtomicCounter[0]<0 )
605
      {
606
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
607

    
608
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
609
        {
610
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
611
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
612
        zeroBuffer();
613
        }
614
      }
615

    
616
    // reading the value of the buffer on every frame would slow down rendering by
617
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
618
    if( mCurrBuffer==0 )
619
      {
620
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
621
      counter = printPreviousBuffer();
622
      }
623

    
624
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
625

    
626
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
627
    zeroBuffer();
628

    
629
    return counter;
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
634

    
635
  static void oitClear(DistortedOutputSurface surface, int counter)
636
    {
637
    if( mLinkedListSSBO[0]<0 )
638
      {
639
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
640

    
641
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
642
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
643
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
644
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
645

    
646
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
647
      }
648

    
649
    // See if we have overflown the SSBO in one of the previous frames.
650
    // If yes, assume we need to make the SSBO larger.
651
    float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
652

    
653
    if( overflow>1.0f )
654
      {
655
      //android.util.Log.e("effects", "previous frame rendered "+counter+
656
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
657

    
658
      mBufferSize *= (int)(overflow+1.0f);
659
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
660
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
661
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
662
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
663
      }
664

    
665
    mOITClearProgram.useProgram();
666

    
667
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
668
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
669
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
670
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
671
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
672
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
673
    }
674

    
675
///////////////////////////////////////////////////////////////////////////////////////////////////
676
// Pass2 of the OIT algorithm - build per-pixel linked lists.
677

    
678
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
679
    {
680
    mOITBuildProgram.useProgram();
681

    
682
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
683
    GLES31.glUniform1i(mOITBuildTextureH, 0);
684
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
685
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
686
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
687
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
688
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
689
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
690
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
691
    }
692

    
693
///////////////////////////////////////////////////////////////////////////////////////////////////
694
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
695

    
696
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
697
    {
698
    mOITCollapseProgram.useProgram();
699

    
700
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
701
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
702
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
703
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
704
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
705
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
706
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
707
    }
708

    
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
711

    
712
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
713
    {
714
    mOITRenderProgram.useProgram();
715

    
716
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
717
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
718
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
719
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
720
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
721
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
722
    }
723

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725

    
726
  private void releasePriv()
727
    {
728
    if( !matrixCloned      ) mM.abortAll(false);
729
    if( !vertexCloned      ) mV.abortAll(false);
730
    if( !fragmentCloned    ) mF.abortAll(false);
731
    if( !postprocessCloned ) mP.abortAll(false);
732

    
733
    mM = null;
734
    mV = null;
735
    mF = null;
736
    mP = null;
737
    }
738

    
739
///////////////////////////////////////////////////////////////////////////////////////////////////
740

    
741
  static void onPause()
742
    {
743
    mLinkedListSSBO[0]= -1;
744

    
745
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
746
    }
747

    
748
///////////////////////////////////////////////////////////////////////////////////////////////////
749

    
750
  static void onDestroy()
751
    {
752
    mNextID =  0;
753
    }
754

    
755
///////////////////////////////////////////////////////////////////////////////////////////////////
756

    
757
  static void setSSBOSize(float size)
758
    {
759
    mBufferSize = size;
760
    }
761

    
762
///////////////////////////////////////////////////////////////////////////////////////////////////
763
// PUBLIC API
764
///////////////////////////////////////////////////////////////////////////////////////////////////
765
/**
766
 * Create empty effect queue.
767
 */
768
  public DistortedEffects()
769
    {
770
    mID = ++mNextID;
771
    initializeEffectLists(this,0);
772
    }
773

    
774
///////////////////////////////////////////////////////////////////////////////////////////////////
775
/**
776
 * Copy constructor.
777
 * <p>
778
 * Whatever we do not clone gets created just like in the default constructor.
779
 *
780
 * @param dc    Source object to create our object from
781
 * @param flags A bitmask of values specifying what to copy.
782
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
783
 */
784
  public DistortedEffects(DistortedEffects dc, int flags)
785
    {
786
    mID = ++mNextID;
787
    initializeEffectLists(dc,flags);
788
    }
789

    
790
///////////////////////////////////////////////////////////////////////////////////////////////////
791
/**
792
 * Releases all resources. After this call, the queue should not be used anymore.
793
 */
794
  @SuppressWarnings("unused")
795
  public synchronized void delete()
796
    {
797
    releasePriv();
798
    }
799

    
800
///////////////////////////////////////////////////////////////////////////////////////////////////
801
/**
802
 * Returns unique ID of this instance.
803
 *
804
 * @return ID of the object.
805
 */
806
  public long getID()
807
      {
808
      return mID;
809
      }
810

    
811
///////////////////////////////////////////////////////////////////////////////////////////////////
812
/**
813
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
814
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
815
 * 
816
 * @param el A class implementing the EffectListener interface that wants to get notifications.
817
 */
818
  @SuppressWarnings("unused")
819
  public void registerForMessages(EffectListener el)
820
    {
821
    mM.registerForMessages(el);
822
    mV.registerForMessages(el);
823
    mF.registerForMessages(el);
824
    mP.registerForMessages(el);
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828
/**
829
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
830
 * 
831
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
832
 */
833
  @SuppressWarnings("unused")
834
  public void deregisterForMessages(EffectListener el)
835
    {
836
    mM.deregisterForMessages(el);
837
    mV.deregisterForMessages(el);
838
    mF.deregisterForMessages(el);
839
    mP.deregisterForMessages(el);
840
    }
841

    
842
///////////////////////////////////////////////////////////////////////////////////////////////////
843
/**
844
 * Aborts all Effects.
845
 * @return Number of effects aborted.
846
 */
847
  public int abortAllEffects()
848
    {
849
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
850
    }
851

    
852
///////////////////////////////////////////////////////////////////////////////////////////////////
853
/**
854
 * Aborts all Effects of a given type, for example all MATRIX Effects.
855
 * 
856
 * @param type one of the constants defined in {@link EffectType}
857
 * @return Number of effects aborted.
858
 */
859
  public int abortByType(EffectType type)
860
    {
861
    switch(type)
862
      {
863
      case MATRIX     : return mM.abortAll(true);
864
      case VERTEX     : return mV.abortAll(true);
865
      case FRAGMENT   : return mF.abortAll(true);
866
      case POSTPROCESS: return mP.abortAll(true);
867
      default         : return 0;
868
      }
869
    }
870

    
871
///////////////////////////////////////////////////////////////////////////////////////////////////
872
/**
873
 * Aborts an Effect by its ID.
874
 *
875
 * @param id the Id of the Effect to be removed, as returned by getID().
876
 * @return Number of effects aborted.
877
 */
878
  public int abortById(long id)
879
    {
880
    long type = id&EffectType.MASK;
881

    
882
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
883
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
884
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
885
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
886

    
887
    return 0;
888
    }
889

    
890
///////////////////////////////////////////////////////////////////////////////////////////////////
891
/**
892
 * Aborts a single Effect.
893
 * 
894
 * @param effect the Effect we want to abort.
895
 * @return number of Effects aborted. Always either 0 or 1.
896
 */
897
  public int abortEffect(Effect effect)
898
    {
899
    switch(effect.getType())
900
      {
901
      case MATRIX     : return mM.removeEffect(effect);
902
      case VERTEX     : return mV.removeEffect(effect);
903
      case FRAGMENT   : return mF.removeEffect(effect);
904
      case POSTPROCESS: return mP.removeEffect(effect);
905
      default         : return 0;
906
      }
907
    }
908

    
909
///////////////////////////////////////////////////////////////////////////////////////////////////
910
/**
911
 * Abort all Effects of a given name, for example all rotations.
912
 * 
913
 * @param name one of the constants defined in {@link EffectName}
914
 * @return number of Effects aborted.
915
 */
916
  public int abortByName(EffectName name)
917
    {
918
    switch(name.getType())
919
      {
920
      case MATRIX     : return mM.removeByName(name);
921
      case VERTEX     : return mV.removeByName(name);
922
      case FRAGMENT   : return mF.removeByName(name);
923
      case POSTPROCESS: return mP.removeByName(name);
924
      default                : return 0;
925
      }
926
    }
927

    
928
///////////////////////////////////////////////////////////////////////////////////////////////////
929
/**
930
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
931
 * single (InputSurface,MeshObject) combo.
932
 *
933
 * @param type {@link EffectType}
934
 * @return The maximum number of effects of a given type.
935
 */
936
  @SuppressWarnings("unused")
937
  public static int getMax(EffectType type)
938
    {
939
    return EffectQueue.getMax(type.ordinal());
940
    }
941

    
942
///////////////////////////////////////////////////////////////////////////////////////////////////
943
/**
944
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
945
 * This can fail if:
946
 * <ul>
947
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
948
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
949
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
950
 *     time only decreasing the value of 'max' is permitted.
951
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
952
 * </ul>
953
 *
954
 * @param type {@link EffectType}
955
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
956
 *            than Byte.MAX_VALUE
957
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
958
 */
959
  @SuppressWarnings("unused")
960
  public static boolean setMax(EffectType type, int max)
961
    {
962
    return EffectQueue.setMax(type.ordinal(),max);
963
    }
964

    
965
///////////////////////////////////////////////////////////////////////////////////////////////////
966
/**
967
 * Add a new Effect to our queue.
968
 *
969
 * @param effect The Effect to add.
970
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
971
 */
972
  public boolean apply(Effect effect)
973
    {
974
    switch(effect.getType())
975
      {
976
      case MATRIX      : return mM.add(effect);
977
      case VERTEX      : return mV.add(effect);
978
      case FRAGMENT    : return mF.add(effect);
979
      case POSTPROCESS : return mP.add(effect);
980
      }
981

    
982
    return false;
983
    }
984
  }
(3-3/21)