Project

General

Profile

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

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

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[1];
80

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

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

    
92
  /// OIT CLEAR PROGRAM ///
93
  private static DistortedProgram mOITClearProgram;
94
  private static int mOITClearDepthH;
95
  private static int mOITClearTexCorrH;
96
  private static int mOITClearSizeH;
97

    
98
  /// OIT BUILD PROGRAM ///
99
  private static DistortedProgram mOITBuildProgram;
100
  private static int mOITBuildTextureH;
101
  private static int mOITBuildDepthTextureH;
102
  private static int mOITBuildDepthH;
103
  private static int mOITBuildTexCorrH;
104
  private static int mOITBuildSizeH;
105
  private static int mOITBuildNumRecordsH;
106

    
107
  /// OIT COLLAPSE PROGRAM ///
108
  private static DistortedProgram mOITCollapseProgram;
109
  private static int mOITCollapseDepthTextureH;
110
  private static int mOITCollapseDepthH;
111
  private static int mOITCollapseTexCorrH;
112
  private static int mOITCollapseSizeH;
113

    
114
  /// OIT RENDER PROGRAM ///
115
  private static DistortedProgram mOITRenderProgram;
116
  private static int mOITRenderDepthH;
117
  private static int mOITRenderTexCorrH;
118
  private static int mOITRenderSizeH;
119

    
120
  /// MAIN OIT PROGRAM ///
121
  private static DistortedProgram mMainOITProgram;
122
  private static int mMainOITTextureH;
123
  private static int mMainOITSizeH;
124
  private static int mMainOITNumRecordsH;
125
  /// END PROGRAMS //////
126

    
127
  private static long mNextID =0;
128
  private long mID;
129

    
130
  private EffectQueueMatrix mM;
131
  private EffectQueueFragment mF;
132
  private EffectQueueVertex mV;
133
  private EffectQueuePostprocess mP;
134

    
135
  private boolean matrixCloned, vertexCloned, fragmentCloned, postprocessCloned;
136

    
137
///////////////////////////////////////////////////////////////////////////////////////////////////
138

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

    
145
    int numF = FragmentEffect.getNumEnabled();
146
    int numV = VertexEffect.getNumEnabled();
147

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

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

    
158
    String[] feedback = { "v_Position", "v_endPosition" };
159

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

    
171
    int mainProgramH = mMainProgram.getProgramHandle();
172
    EffectQueueFragment.getUniforms(mainProgramH,0);
173
    EffectQueueVertex.getUniforms(mainProgramH,0);
174
    EffectQueueMatrix.getUniforms(mainProgramH,0);
175
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
176

    
177
    // BLIT PROGRAM ////////////////////////////////////
178
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
179
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
180

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

    
191
    int blitProgramH = mBlitProgram.getProgramHandle();
192
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
193
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
194

    
195
    // BLIT DEPTH PROGRAM ////////////////////////////////////
196
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
197
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
198

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

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

    
215
    // NORMAL PROGRAM //////////////////////////////////////
216
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
217
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
218

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

    
229
    int normalProgramH = mNormalProgram.getProgramHandle();
230
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
231
    }
232

    
233
  ///////////////////////////////////////////////////////////////////////////////////////////////////
234

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

    
241
    int numF = FragmentEffect.getNumEnabled();
242
    int numV = VertexEffect.getNumEnabled();
243

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

    
251
    String enabledEffectV= VertexEffect.getGLSL();
252
    String enabledEffectF= FragmentEffect.getGLSL();
253

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

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

    
273
    // OIT CLEAR PROGRAM ////////////////////////////////////
274
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
275
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
276

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

    
287
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
288
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
289
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
290
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
291

    
292
    // OIT BUILD PROGRAM ////////////////////////////////////
293
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
294
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
295

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

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

    
314
    // OIT COLLAPSE PROGRAM ///////////////////////////
315
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
316
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
317

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

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

    
334
    // OIT RENDER PROGRAM ///////////////////////////
335
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
336
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
337

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

    
348
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
349
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
350
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
351
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
352
    }
353

    
354
///////////////////////////////////////////////////////////////////////////////////////////////////
355

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

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

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404

    
405
  EffectQueuePostprocess getPostprocess()
406
    {
407
    return mP;
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411

    
412
  void newNode(DistortedNode node)
413
    {
414
    mM.newNode(node);
415
    mF.newNode(node);
416
    mV.newNode(node);
417
    mP.newNode(node);
418
    }
419

    
420
///////////////////////////////////////////////////////////////////////////////////////////////////
421

    
422
  private void displayNormals(MeshObject mesh)
423
    {
424
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
425
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
426
    DistortedRenderState.switchOffDrawing();
427
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
428
    DistortedRenderState.restoreDrawing();
429
    GLES31.glEndTransformFeedback();
430
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
431

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

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442

    
443
  void drawPrivOIT(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
444
    {
445
    float halfZ = halfW*mesh.zFactor;
446

    
447
    mM.compute(currTime);
448
    mV.compute(currTime,halfW,halfH,halfZ);
449
    mF.compute(currTime,halfW,halfH);
450
    mP.compute(currTime);
451

    
452
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
453

    
454
    mMainOITProgram.useProgram();
455
    GLES31.glUniform1i(mMainOITTextureH, 0);
456
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
457
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
458

    
459
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
460
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
461
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
462
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
463
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
464

    
465
    mM.send(surface,halfW,halfH,halfZ,marginInPixels,1);
466
    mV.send(1);
467
    mF.send(1);
468

    
469
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
470

    
471
    if( mesh.mShowNormals ) displayNormals(mesh);
472
    }
473

    
474
///////////////////////////////////////////////////////////////////////////////////////////////////
475

    
476
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
477
    {
478
    float halfZ = halfW*mesh.zFactor;
479

    
480
    mM.compute(currTime);
481
    mV.compute(currTime,halfW,halfH,halfZ);
482
    mF.compute(currTime,halfW,halfH);
483
    mP.compute(currTime);
484

    
485
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
486

    
487
    mMainProgram.useProgram();
488
    GLES31.glUniform1i(mMainTextureH, 0);
489

    
490
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
491
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
492
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
493
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
494
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
495

    
496
    mM.send(surface,halfW,halfH,halfZ,marginInPixels,0);
497
    mV.send(0);
498
    mF.send(0);
499

    
500
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
501

    
502
    if( mesh.mShowNormals ) displayNormals(mesh);
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506
/**
507
 * Only for use by the library itself.
508
 *
509
 * @y.exclude
510
 */
511
  public static void blitPriv(DistortedOutputSurface surface)
512
    {
513
    mBlitProgram.useProgram();
514

    
515
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
516
    GLES31.glUniform1i(mBlitTextureH, 0);
517
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
518
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
519
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
520
    }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523

    
524
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
525
    {
526
    mBlitDepthProgram.useProgram();
527

    
528
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
529
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
530
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
531
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
532
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
533
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
534
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538
// reset atomic counter to 0
539

    
540
  static void zeroOutAtomic()
541
    {
542
    if( mAtomicCounter[0]<0 )
543
      {
544
      GLES31.glGenBuffers(1,mAtomicCounter,0);
545
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[0]);
546
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
547
      GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
548
      GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
549
      }
550

    
551
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[0] );
552

    
553
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
554
                                                                GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
555
    if( atomicBuf!=null )
556
      {
557
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
558

    
559
      //int counter = atomicIntBuf.get(0);
560
      //android.util.Log.e("counter", "now = "+counter+" w="+surface.mWidth+" h="+surface.mHeight
561
      //                             +" diff="+(counter-surface.mWidth*surface.mHeight));
562
      atomicIntBuf.put(0,0);
563
      }
564
    else
565
      {
566
      android.util.Log.e("effects", "failed to map atomic buffer");
567
      }
568

    
569
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
570
    GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0);
571
    }
572

    
573
///////////////////////////////////////////////////////////////////////////////////////////////////
574
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
575

    
576
  static void oitClear(DistortedOutputSurface surface)
577
    {
578
    if( mLinkedListSSBO[0]<0 )
579
      {
580
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
581

    
582
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
583
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
584
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
585
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
586
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
587
      }
588

    
589
    mOITClearProgram.useProgram();
590

    
591
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
592
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
593
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
594
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
595
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
596
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
597
    }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600
// Pass2 of the OIT algorithm - build per-pixel linked lists.
601

    
602
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
603
    {
604
    mOITBuildProgram.useProgram();
605

    
606
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
607
    GLES31.glUniform1i(mOITBuildTextureH, 0);
608
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
609
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
610
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
611
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
612
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
613
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
614
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
615
    }
616

    
617
///////////////////////////////////////////////////////////////////////////////////////////////////
618
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
619

    
620
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
621
    {
622
    mOITCollapseProgram.useProgram();
623

    
624
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
625
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
626
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
627
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
628
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
629
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
630
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
631
    }
632

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
635

    
636
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
637
    {
638
    mOITRenderProgram.useProgram();
639

    
640
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
641
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
642
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
643
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
644
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
645
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649

    
650
  private void releasePriv()
651
    {
652
    if( !matrixCloned      ) mM.abortAll(false);
653
    if( !vertexCloned      ) mV.abortAll(false);
654
    if( !fragmentCloned    ) mF.abortAll(false);
655
    if( !postprocessCloned ) mP.abortAll(false);
656

    
657
    mM = null;
658
    mV = null;
659
    mF = null;
660
    mP = null;
661
    }
662

    
663
///////////////////////////////////////////////////////////////////////////////////////////////////
664

    
665
  static void onPause()
666
    {
667
    mLinkedListSSBO[0]= -1;
668
    mAtomicCounter[0] = -1;
669
    }
670

    
671
///////////////////////////////////////////////////////////////////////////////////////////////////
672

    
673
  static void onDestroy()
674
    {
675
    mNextID =  0;
676
    }
677

    
678
///////////////////////////////////////////////////////////////////////////////////////////////////
679
// PUBLIC API
680
///////////////////////////////////////////////////////////////////////////////////////////////////
681
/**
682
 * Create empty effect queue.
683
 */
684
  public DistortedEffects()
685
    {
686
    mID = ++mNextID;
687
    initializeEffectLists(this,0);
688
    }
689

    
690
///////////////////////////////////////////////////////////////////////////////////////////////////
691
/**
692
 * Copy constructor.
693
 * <p>
694
 * Whatever we do not clone gets created just like in the default constructor.
695
 *
696
 * @param dc    Source object to create our object from
697
 * @param flags A bitmask of values specifying what to copy.
698
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
699
 */
700
  public DistortedEffects(DistortedEffects dc, int flags)
701
    {
702
    mID = ++mNextID;
703
    initializeEffectLists(dc,flags);
704
    }
705

    
706
///////////////////////////////////////////////////////////////////////////////////////////////////
707
/**
708
 * Releases all resources. After this call, the queue should not be used anymore.
709
 */
710
  @SuppressWarnings("unused")
711
  public synchronized void delete()
712
    {
713
    releasePriv();
714
    }
715

    
716
///////////////////////////////////////////////////////////////////////////////////////////////////
717
/**
718
 * Returns unique ID of this instance.
719
 *
720
 * @return ID of the object.
721
 */
722
  public long getID()
723
      {
724
      return mID;
725
      }
726

    
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728
/**
729
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
730
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
731
 * 
732
 * @param el A class implementing the EffectListener interface that wants to get notifications.
733
 */
734
  @SuppressWarnings("unused")
735
  public void registerForMessages(EffectListener el)
736
    {
737
    mM.registerForMessages(el);
738
    mV.registerForMessages(el);
739
    mF.registerForMessages(el);
740
    mP.registerForMessages(el);
741
    }
742

    
743
///////////////////////////////////////////////////////////////////////////////////////////////////
744
/**
745
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
746
 * 
747
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
748
 */
749
  @SuppressWarnings("unused")
750
  public void deregisterForMessages(EffectListener el)
751
    {
752
    mM.deregisterForMessages(el);
753
    mV.deregisterForMessages(el);
754
    mF.deregisterForMessages(el);
755
    mP.deregisterForMessages(el);
756
    }
757

    
758
///////////////////////////////////////////////////////////////////////////////////////////////////
759
/**
760
 * Aborts all Effects.
761
 * @return Number of effects aborted.
762
 */
763
  public int abortAllEffects()
764
    {
765
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
766
    }
767

    
768
///////////////////////////////////////////////////////////////////////////////////////////////////
769
/**
770
 * Aborts all Effects of a given type, for example all MATRIX Effects.
771
 * 
772
 * @param type one of the constants defined in {@link EffectType}
773
 * @return Number of effects aborted.
774
 */
775
  public int abortByType(EffectType type)
776
    {
777
    switch(type)
778
      {
779
      case MATRIX     : return mM.abortAll(true);
780
      case VERTEX     : return mV.abortAll(true);
781
      case FRAGMENT   : return mF.abortAll(true);
782
      case POSTPROCESS: return mP.abortAll(true);
783
      default         : return 0;
784
      }
785
    }
786

    
787
///////////////////////////////////////////////////////////////////////////////////////////////////
788
/**
789
 * Aborts an Effect by its ID.
790
 *
791
 * @param id the Id of the Effect to be removed, as returned by getID().
792
 * @return Number of effects aborted.
793
 */
794
  public int abortById(long id)
795
    {
796
    long type = id&EffectType.MASK;
797

    
798
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
799
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
800
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
801
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
802

    
803
    return 0;
804
    }
805

    
806
///////////////////////////////////////////////////////////////////////////////////////////////////
807
/**
808
 * Aborts a single Effect.
809
 * 
810
 * @param effect the Effect we want to abort.
811
 * @return number of Effects aborted. Always either 0 or 1.
812
 */
813
  public int abortEffect(Effect effect)
814
    {
815
    switch(effect.getType())
816
      {
817
      case MATRIX     : return mM.removeEffect(effect);
818
      case VERTEX     : return mV.removeEffect(effect);
819
      case FRAGMENT   : return mF.removeEffect(effect);
820
      case POSTPROCESS: return mP.removeEffect(effect);
821
      default         : return 0;
822
      }
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * Abort all Effects of a given name, for example all rotations.
828
 * 
829
 * @param name one of the constants defined in {@link EffectName}
830
 * @return number of Effects aborted.
831
 */
832
  public int abortByName(EffectName name)
833
    {
834
    switch(name.getType())
835
      {
836
      case MATRIX     : return mM.removeByName(name);
837
      case VERTEX     : return mV.removeByName(name);
838
      case FRAGMENT   : return mF.removeByName(name);
839
      case POSTPROCESS: return mP.removeByName(name);
840
      default                : return 0;
841
      }
842
    }
843

    
844
///////////////////////////////////////////////////////////////////////////////////////////////////
845
/**
846
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
847
 * single (InputSurface,MeshObject) combo.
848
 *
849
 * @param type {@link EffectType}
850
 * @return The maximum number of effects of a given type.
851
 */
852
  @SuppressWarnings("unused")
853
  public static int getMax(EffectType type)
854
    {
855
    return EffectQueue.getMax(type.ordinal());
856
    }
857

    
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859
/**
860
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
861
 * This can fail if:
862
 * <ul>
863
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
864
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
865
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
866
 *     time only decreasing the value of 'max' is permitted.
867
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
868
 * </ul>
869
 *
870
 * @param type {@link EffectType}
871
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
872
 *            than Byte.MAX_VALUE
873
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
874
 */
875
  @SuppressWarnings("unused")
876
  public static boolean setMax(EffectType type, int max)
877
    {
878
    return EffectQueue.setMax(type.ordinal(),max);
879
    }
880

    
881
///////////////////////////////////////////////////////////////////////////////////////////////////
882
/**
883
 * Add a new Effect to our queue.
884
 *
885
 * @param effect The Effect to add.
886
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
887
 */
888
  public boolean apply(Effect effect)
889
    {
890
    switch(effect.getType())
891
      {
892
      case MATRIX      : return mM.add(effect);
893
      case VERTEX      : return mV.add(effect);
894
      case FRAGMENT    : return mF.add(effect);
895
      case POSTPROCESS : return mP.add(effect);
896
      }
897

    
898
    return false;
899
    }
900
  }
(2-2/21)