Project

General

Profile

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

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

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.mesh.MeshBase;
33
import org.distorted.library.message.EffectListener;
34
import org.distorted.library.program.DistortedProgram;
35

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

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

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

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

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

    
74
  /// NORMAL PROGRAM /////
75
  private static DistortedProgram mNormalProgram;
76
  private static int mNormalMVPMatrixH;
77

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

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

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

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

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

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

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

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

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

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

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

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

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

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

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

    
407
///////////////////////////////////////////////////////////////////////////////////////////////////
408

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

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415

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

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

    
426
  private void displayNormals(MeshBase mesh)
427
    {
428
    int num = mesh.getNumVertices();
429
    int tfo = mesh.getTFO();
430

    
431
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
432
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
433
    DistortedRenderState.switchOffDrawing();
434
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, num );
435
    DistortedRenderState.restoreDrawing();
436
    GLES31.glEndTransformFeedback();
437
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
438

    
439
    mNormalProgram.useProgram();
440
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
441
    mesh.bindTransformAttribs(mNormalProgram);
442
    GLES31.glLineWidth(8.0f);
443
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
444
    }
445

    
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447

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

    
454
///////////////////////////////////////////////////////////////////////////////////////////////////
455

    
456
  void drawPrivOIT(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
457
    {
458
    float halfZ = halfW*mesh.getZFactor();
459

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

    
465
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
466

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

    
472
    mesh.bindVertexAttribs(mMainOITProgram);
473

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

    
478
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
479

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

    
490
///////////////////////////////////////////////////////////////////////////////////////////////////
491

    
492
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
493
    {
494
    float halfZ = halfW*mesh.getZFactor();
495

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

    
501
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
502

    
503
    mMainProgram.useProgram();
504
    GLES31.glUniform1i(mMainTextureH, 0);
505

    
506
    mesh.bindVertexAttribs(mMainProgram);
507

    
508
    mM.send(surface,halfW,halfH,halfZ,0,0);
509
    mV.send(0);
510
    mF.send(0);
511

    
512
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
513

    
514
    if( mesh.getShowNormals() ) displayNormals(mesh);
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518
/**
519
 * Only for use by the library itself.
520
 *
521
 * @y.exclude
522
 */
523
  public static void blitPriv(DistortedOutputSurface surface)
524
    {
525
    mBlitProgram.useProgram();
526

    
527
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
528
    GLES31.glUniform1i(mBlitTextureH, 0);
529
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
530
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
531
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
532
    }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535

    
536
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
537
    {
538
    mBlitDepthProgram.useProgram();
539

    
540
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
541
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
542
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
543
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
544
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
545
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
546
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550

    
551
  private static int printPreviousBuffer()
552
    {
553
    int counter = 0;
554

    
555
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
556
                                                                GLES31.GL_MAP_READ_BIT);
557
    if( atomicBuf!=null )
558
      {
559
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
560
      counter = atomicIntBuf.get(0);
561
      }
562
    else
563
      {
564
      android.util.Log.e("effects", "print: failed to map atomic buffer");
565
      }
566

    
567
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
568

    
569
    return counter;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573

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

    
588
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
589
    }
590

    
591
///////////////////////////////////////////////////////////////////////////////////////////////////
592
// reset atomic counter to 0
593

    
594
  static int zeroOutAtomic()
595
    {
596
    int counter = 0;
597

    
598
    if( mAtomicCounter[0]<0 )
599
      {
600
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
601

    
602
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
603
        {
604
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
605
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
606
        zeroBuffer();
607
        }
608
      }
609

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

    
618
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
619

    
620
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
621
    zeroBuffer();
622

    
623
    return counter;
624
    }
625

    
626
///////////////////////////////////////////////////////////////////////////////////////////////////
627
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
628

    
629
  static void oitClear(DistortedOutputSurface surface, int counter)
630
    {
631
    if( mLinkedListSSBO[0]<0 )
632
      {
633
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
634

    
635
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
636
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
637
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
638
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
639

    
640
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
641
      }
642

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

    
647
    if( overflow>1.0f )
648
      {
649
      //android.util.Log.e("effects", "previous frame rendered "+counter+
650
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
651

    
652
      mBufferSize *= (int)(overflow+1.0f);
653
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
654
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
655
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
656
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
657
      }
658

    
659
    mOITClearProgram.useProgram();
660

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

    
669
///////////////////////////////////////////////////////////////////////////////////////////////////
670
// Pass2 of the OIT algorithm - build per-pixel linked lists.
671

    
672
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
673
    {
674
    mOITBuildProgram.useProgram();
675

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

    
687
///////////////////////////////////////////////////////////////////////////////////////////////////
688
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
689

    
690
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
691
    {
692
    mOITCollapseProgram.useProgram();
693

    
694
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
695
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
696
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
697
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
698
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
699
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
700
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
701
    }
702

    
703
///////////////////////////////////////////////////////////////////////////////////////////////////
704
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
705

    
706
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
707
    {
708
    mOITRenderProgram.useProgram();
709

    
710
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
711
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
712
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
713
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
714
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
715
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
716
    }
717

    
718
///////////////////////////////////////////////////////////////////////////////////////////////////
719

    
720
  private void releasePriv()
721
    {
722
    if( !matrixCloned      ) mM.abortAll(false);
723
    if( !vertexCloned      ) mV.abortAll(false);
724
    if( !fragmentCloned    ) mF.abortAll(false);
725
    if( !postprocessCloned ) mP.abortAll(false);
726

    
727
    mM = null;
728
    mV = null;
729
    mF = null;
730
    mP = null;
731
    }
732

    
733
///////////////////////////////////////////////////////////////////////////////////////////////////
734

    
735
  static void onPause()
736
    {
737
    mLinkedListSSBO[0]= -1;
738

    
739
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743

    
744
  static void onDestroy()
745
    {
746
    mNextID =  0;
747
    }
748

    
749
///////////////////////////////////////////////////////////////////////////////////////////////////
750

    
751
  static void setSSBOSize(float size)
752
    {
753
    mBufferSize = size;
754
    }
755

    
756
///////////////////////////////////////////////////////////////////////////////////////////////////
757
// PUBLIC API
758
///////////////////////////////////////////////////////////////////////////////////////////////////
759
/**
760
 * Create empty effect queue.
761
 */
762
  public DistortedEffects()
763
    {
764
    mID = ++mNextID;
765
    initializeEffectLists(this,0);
766
    }
767

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

    
784
///////////////////////////////////////////////////////////////////////////////////////////////////
785
/**
786
 * Releases all resources. After this call, the queue should not be used anymore.
787
 */
788
  @SuppressWarnings("unused")
789
  public synchronized void delete()
790
    {
791
    releasePriv();
792
    }
793

    
794
///////////////////////////////////////////////////////////////////////////////////////////////////
795
/**
796
 * Returns unique ID of this instance.
797
 *
798
 * @return ID of the object.
799
 */
800
  public long getID()
801
      {
802
      return mID;
803
      }
804

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

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

    
836
///////////////////////////////////////////////////////////////////////////////////////////////////
837
/**
838
 * Aborts all Effects.
839
 * @return Number of effects aborted.
840
 */
841
  public int abortAllEffects()
842
    {
843
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
844
    }
845

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

    
865
///////////////////////////////////////////////////////////////////////////////////////////////////
866
/**
867
 * Aborts an Effect by its ID.
868
 *
869
 * @param id the Id of the Effect to be removed, as returned by getID().
870
 * @return Number of effects aborted.
871
 */
872
  public int abortById(long id)
873
    {
874
    long type = id&EffectType.MASK;
875

    
876
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
877
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
878
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
879
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
880

    
881
    return 0;
882
    }
883

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

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

    
922
///////////////////////////////////////////////////////////////////////////////////////////////////
923
/**
924
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
925
 * single (InputSurface,MeshBase) combo.
926
 *
927
 * @param type {@link EffectType}
928
 * @return The maximum number of effects of a given type.
929
 */
930
  @SuppressWarnings("unused")
931
  public static int getMax(EffectType type)
932
    {
933
    return EffectQueue.getMax(type.ordinal());
934
    }
935

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

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

    
976
    return false;
977
    }
978
  }
(3-3/17)