Project

General

Profile

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

library / src / main / java / org / distorted / library / main / Distorted.java @ bfe45b4a

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.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.content.res.Resources;
26
import android.opengl.GLES31;
27
import android.util.Log;
28

    
29
import org.distorted.library.R;
30
import org.distorted.library.effect.Effect;
31
import org.distorted.library.effect.EffectType;
32
import org.distorted.library.effect.FragmentEffect;
33
import org.distorted.library.effect.PostprocessEffect;
34
import org.distorted.library.effect.VertexEffect;
35
import org.distorted.library.mesh.MeshBase;
36
import org.distorted.library.message.EffectMessageSender;
37
import org.distorted.library.program.DistortedProgram;
38

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

    
45
///////////////////////////////////////////////////////////////////////////////////////////////////
46
/**
47
 * A singleton class used to control various global settings.
48
 */
49
public class Distorted 
50
  {
51
  public static final int GLSL = 310;
52
  public static final String GLSL_VERSION= "#version 310 es\n";
53
  /**
54
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
55
   * backing up our DistortedTexture.
56
   * <p>
57
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
58
   * apply different effects. Used in the copy constructor.
59
   */
60
  public static final int CLONE_SURFACE = 0x1;
61
  /**
62
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
63
   * <p>
64
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
65
   */
66
  public static final int CLONE_MATRIX = 0x2;
67
  /**
68
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
69
   * <p>
70
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
71
   */
72
  public static final int CLONE_VERTEX  = 0x4;
73
  /**
74
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
75
   * <p>
76
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
77
   */
78
  public static final int CLONE_FRAGMENT= 0x8;
79
   /**
80
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
81
   * <p>
82
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
83
   */
84
  public static final int CLONE_POSTPROCESS= 0x10;
85
  /**
86
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
87
   * <p>
88
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
89
   * on the screen with (optionally) different Effects.
90
   */
91
  public static final int CLONE_CHILDREN= 0x20;
92

    
93
  /**
94
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
95
   * of FBO_QUEUE_SIZE FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
96
   * might be missing part of the Objects)
97
   *
98
   * This bug only exists on Mali driver r12.
99
   *
100
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
101
   */
102
  static final int FBO_QUEUE_SIZE = 4;
103
  /**
104
   * Number of Main program variants (ATM 3: MAIN, MAIN OIT, PREPROCESS)
105
   */
106
  static final int MAIN_VARIANTS = 3;
107

    
108
  private static boolean mInitialized=false;
109

    
110
  //////////////////////////////////////////////////////////////////////////////////////////////
111
  /// MAIN PROGRAM ///
112
  private static DistortedProgram mMainProgram;
113
  private static int mMainTextureH;
114

    
115
  /// NORMAL PROGRAM /////
116
  private static DistortedProgram mNormalProgram;
117
  private static int mNormalMVPMatrixH;
118

    
119
  /// MAIN OIT PROGRAM ///
120
  private static DistortedProgram mMainOITProgram;
121
  private static int mMainOITTextureH;
122
  private static int mMainOITSizeH;
123
  private static int mMainOITNumRecordsH;
124

    
125
  /// BLIT PROGRAM ///
126
  private static DistortedProgram mBlitProgram;
127
  private static int mBlitTextureH;
128
  private static int mBlitDepthH;
129
  private static final FloatBuffer mQuadPositions;
130

    
131
  static
132
    {
133
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
134
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
135
    mQuadPositions.put(positionData).position(0);
136
    }
137

    
138
  /// BLIT DEPTH PROGRAM ///
139
  private static DistortedProgram mBlitDepthProgram;
140
  private static int mBlitDepthTextureH;
141
  private static int mBlitDepthDepthTextureH;
142
  private static int mBlitDepthDepthH;
143
  private static int mBlitDepthTexCorrH;
144

    
145
  /// OIT SSBO BUFFER ///
146
  private static int[] mLinkedListSSBO = new int[1];
147
  private static int[] mAtomicCounter = new int[Distorted.FBO_QUEUE_SIZE];
148
  private static int   mCurrBuffer;
149

    
150
  static
151
    {
152
    mLinkedListSSBO[0]= -1;
153
    mCurrBuffer       =  0;
154

    
155
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)  mAtomicCounter[i] = -1;
156
    }
157

    
158
  ///////////////////////////////////////////////////////////////
159
  // meaning: allocate 1.0 screenful of places for transparent
160
  // fragments in the SSBO backing up the OIT render method.
161
  private static float mBufferSize=1.0f;
162

    
163
  /// OIT CLEAR PROGRAM ///
164
  private static DistortedProgram mOITClearProgram;
165
  private static int mOITClearDepthH;
166
  private static int mOITClearTexCorrH;
167
  private static int mOITClearSizeH;
168

    
169
  /// OIT BUILD PROGRAM ///
170
  private static DistortedProgram mOITBuildProgram;
171
  private static int mOITBuildTextureH;
172
  private static int mOITBuildDepthTextureH;
173
  private static int mOITBuildDepthH;
174
  private static int mOITBuildTexCorrH;
175
  private static int mOITBuildSizeH;
176
  private static int mOITBuildNumRecordsH;
177

    
178
  /// OIT COLLAPSE PROGRAM ///
179
  private static DistortedProgram mOITCollapseProgram;
180
  private static int mOITCollapseDepthTextureH;
181
  private static int mOITCollapseDepthH;
182
  private static int mOITCollapseTexCorrH;
183
  private static int mOITCollapseSizeH;
184

    
185
  /// OIT RENDER PROGRAM ///
186
  private static DistortedProgram mOITRenderProgram;
187
  private static int mOITRenderDepthH;
188
  private static int mOITRenderTexCorrH;
189
  private static int mOITRenderSizeH;
190

    
191
  /// END PROGRAMS //////
192

    
193
///////////////////////////////////////////////////////////////////////////////////////////////////
194
// private: hide this from Javadoc
195

    
196
  private Distorted()
197
    {
198

    
199
    }
200

    
201
///////////////////////////////////////////////////////////////////////////////////////////////////
202

    
203
  static void createPrograms(Resources resources)
204
    {
205
    // MAIN PROGRAM ////////////////////////////////////
206
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
207
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
208

    
209
    int numF = FragmentEffect.getNumEnabled();
210
    int numV = VertexEffect.getNumEnabled();
211

    
212
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
213
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
214
    String enabledEffectV= VertexEffect.getGLSL();
215
    String enabledEffectF= FragmentEffect.getGLSL();
216

    
217
    String[] feedback = { "v_Position", "v_endPosition" };
218

    
219
    try
220
      {
221
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
222
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
223
      }
224
    catch(Exception e)
225
      {
226
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
227
      throw new RuntimeException(e.getMessage());
228
      }
229

    
230
    int mainProgramH = mMainProgram.getProgramHandle();
231
    EffectQueue.getUniforms(mainProgramH,0);
232
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
233

    
234
    // BLIT PROGRAM ////////////////////////////////////
235
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
236
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
237

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

    
248
    int blitProgramH = mBlitProgram.getProgramHandle();
249
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
250
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
251

    
252
    // BLIT DEPTH PROGRAM ////////////////////////////////////
253
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
254
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
255

    
256
    try
257
      {
258
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
259
      }
260
    catch(Exception e)
261
      {
262
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
263
      throw new RuntimeException(e.getMessage());
264
      }
265

    
266
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
267
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
268
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
269
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
270
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
271

    
272
    // NORMAL PROGRAM //////////////////////////////////////
273
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
274
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
275

    
276
    try
277
      {
278
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
279
      }
280
    catch(Exception e)
281
      {
282
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
283
      throw new RuntimeException(e.getMessage());
284
      }
285

    
286
    int normalProgramH = mNormalProgram.getProgramHandle();
287
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
288
    }
289

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291

    
292
  static void createProgramsOIT(Resources resources)
293
    {
294
    // MAIN OIT PROGRAM ////////////////////////////////
295
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
296
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
297

    
298
    int numF = FragmentEffect.getNumEnabled();
299
    int numV = VertexEffect.getNumEnabled();
300

    
301
    String mainVertHeader= Distorted.GLSL_VERSION +
302
                           ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") +
303
                           ("#define OIT\n");
304
    String mainFragHeader= Distorted.GLSL_VERSION +
305
                           ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") +
306
                           ("#define OIT\n");
307

    
308
    String enabledEffectV= VertexEffect.getGLSL();
309
    String enabledEffectF= FragmentEffect.getGLSL();
310

    
311
    try
312
      {
313
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
314
                                             enabledEffectV, enabledEffectF, Distorted.GLSL, null);
315
      }
316
    catch(Exception e)
317
      {
318
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
319
      throw new RuntimeException(e.getMessage());
320
      }
321

    
322
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
323
    EffectQueue.getUniforms(mainOITProgramH,1);
324
    mMainOITTextureH    = GLES31.glGetUniformLocation( mainOITProgramH, "u_Texture");
325
    mMainOITSizeH       = GLES31.glGetUniformLocation( mainOITProgramH, "u_Size");
326
    mMainOITNumRecordsH = GLES31.glGetUniformLocation( mainOITProgramH, "u_numRecords");
327

    
328
    // OIT CLEAR PROGRAM ////////////////////////////////////
329
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
330
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
331

    
332
    try
333
      {
334
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
335
      }
336
    catch(Exception e)
337
      {
338
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
339
      throw new RuntimeException(e.getMessage());
340
      }
341

    
342
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
343
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
344
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
345
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
346

    
347
    // OIT BUILD PROGRAM ////////////////////////////////////
348
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
349
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
350

    
351
    try
352
      {
353
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
354
      }
355
    catch(Exception e)
356
      {
357
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
358
      throw new RuntimeException(e.getMessage());
359
      }
360

    
361
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
362
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
363
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
364
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
365
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
366
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
367
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
368

    
369
    // OIT COLLAPSE PROGRAM ///////////////////////////
370
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
371
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
372

    
373
    try
374
      {
375
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
376
      }
377
    catch(Exception e)
378
      {
379
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
380
      throw new RuntimeException(e.getMessage());
381
      }
382

    
383
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
384
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
385
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
386
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
387
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
388

    
389
    // OIT RENDER PROGRAM ///////////////////////////
390
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
391
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
392

    
393
    try
394
      {
395
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
396
      }
397
    catch(Exception e)
398
      {
399
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
400
      throw new RuntimeException(e.getMessage());
401
      }
402

    
403
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
404
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
405
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
406
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
407
    }
408

    
409

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

    
412
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
413
    {
414
    int num = mesh.getNumVertices();
415
    int tfo = mesh.getTFO();
416

    
417
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
418
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
419
    DistortedRenderState.switchOffDrawing();
420
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, num );
421
    DistortedRenderState.restoreDrawing();
422
    GLES31.glEndTransformFeedback();
423
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
424

    
425
    Distorted.mNormalProgram.useProgram();
426
    GLES31.glUniformMatrix4fv(Distorted.mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
427
    mesh.bindTransformAttribs(Distorted.mNormalProgram);
428
    GLES31.glLineWidth(8.0f);
429
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
430
    }
431

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433

    
434
  static void drawPrivOIT(EffectQueue[] queues, float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
435
    {
436
    float halfZ = halfW*mesh.getZFactor();
437

    
438
    EffectQueue.compute(queues, currTime, halfW, halfH, halfZ );
439
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
440

    
441
    Distorted.mMainOITProgram.useProgram();
442
    GLES31.glUniform1i(Distorted.mMainOITTextureH, 0);
443
    GLES31.glUniform2ui(Distorted.mMainOITSizeH, surface.mWidth, surface.mHeight);
444
    GLES31.glUniform1ui(Distorted.mMainOITNumRecordsH, (int)(Distorted.mBufferSize*surface.mWidth*surface.mHeight) );
445

    
446
    mesh.bindVertexAttribs(Distorted.mMainOITProgram);
447

    
448
    float inflate = mesh.getInflate();
449

    
450
    EffectQueue.send(queues, surface, inflate, halfW, halfH, halfZ, 1 );
451
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
452

    
453
    if( mesh.getShowNormals() )
454
      {
455
      Distorted.mMainProgram.useProgram();
456
      EffectQueue.send(queues, surface, inflate, halfW, halfH, halfZ, 0 );
457
      displayNormals(queues,mesh);
458
      }
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  static void drawPriv(EffectQueue[] queues, float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
464
    {
465
    float halfZ = halfW*mesh.getZFactor();
466

    
467
    EffectQueue.compute(queues, currTime, halfW, halfH, halfZ );
468
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
469
    Distorted.mMainProgram.useProgram();
470
    GLES31.glUniform1i(Distorted.mMainTextureH, 0);
471
    mesh.bindVertexAttribs(Distorted.mMainProgram);
472
    EffectQueue.send(queues, surface, mesh.getInflate(), halfW, halfH, halfZ, 0 );
473
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
474

    
475
    if( mesh.getShowNormals() ) displayNormals(queues,mesh);
476
    }
477

    
478
///////////////////////////////////////////////////////////////////////////////////////////////////
479

    
480
  static void blitPriv(DistortedOutputSurface surface)
481
    {
482
    mBlitProgram.useProgram();
483

    
484
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
485
    GLES31.glUniform1i(mBlitTextureH, 0);
486
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
487
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
488
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
489
    }
490

    
491
///////////////////////////////////////////////////////////////////////////////////////////////////
492

    
493
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
494
    {
495
    mBlitDepthProgram.useProgram();
496

    
497
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
498
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
499
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
500
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
501
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
502
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
503
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
504
    }
505

    
506
///////////////////////////////////////////////////////////////////////////////////////////////////
507

    
508
  private static int printPreviousBuffer()
509
    {
510
    int counter = 0;
511

    
512
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
513
                                                                GLES31.GL_MAP_READ_BIT);
514
    if( atomicBuf!=null )
515
      {
516
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
517
      counter = atomicIntBuf.get(0);
518
      }
519
    else
520
      {
521
      android.util.Log.e("effects", "print: failed to map atomic buffer");
522
      }
523

    
524
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
525

    
526
    return counter;
527
    }
528

    
529
///////////////////////////////////////////////////////////////////////////////////////////////////
530

    
531
  private static void zeroBuffer()
532
    {
533
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
534
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
535
    if( atomicBuf!=null )
536
      {
537
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
538
      atomicIntBuf.put(0,0);
539
      }
540
    else
541
      {
542
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
543
      }
544

    
545
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549
// reset atomic counter to 0
550

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

    
555
    if( mAtomicCounter[0]<0 )
556
      {
557
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
558

    
559
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
560
        {
561
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
562
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
563
        zeroBuffer();
564
        }
565
      }
566

    
567
    // reading the value of the buffer on every frame would slow down rendering by
568
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
569
    if( mCurrBuffer==0 )
570
      {
571
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
572
      counter = printPreviousBuffer();
573
      }
574

    
575
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
576

    
577
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
578
    zeroBuffer();
579

    
580
    return counter;
581
    }
582

    
583
///////////////////////////////////////////////////////////////////////////////////////////////////
584
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
585

    
586
  static void oitClear(DistortedOutputSurface surface, int counter)
587
    {
588
    if( mLinkedListSSBO[0]<0 )
589
      {
590
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
591

    
592
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
593
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
594
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
595
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
596

    
597
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
598
      }
599

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

    
604
    if( overflow>1.0f )
605
      {
606
      //android.util.Log.e("effects", "previous frame rendered "+counter+
607
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
608

    
609
      mBufferSize *= (int)(overflow+1.0f);
610
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
611
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
612
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
613
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
614
      }
615

    
616
    mOITClearProgram.useProgram();
617

    
618
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
619
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
620
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
621
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
622
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
623
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
624
    }
625

    
626
///////////////////////////////////////////////////////////////////////////////////////////////////
627
// Pass2 of the OIT algorithm - build per-pixel linked lists.
628

    
629
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
630
    {
631
    mOITBuildProgram.useProgram();
632

    
633
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
634
    GLES31.glUniform1i(mOITBuildTextureH, 0);
635
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
636
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
637
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
638
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
639
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
640
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
641
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
646

    
647
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
648
    {
649
    mOITCollapseProgram.useProgram();
650

    
651
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
652
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
653
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
654
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
655
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
656
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
657
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
658
    }
659

    
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
662

    
663
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
664
    {
665
    mOITRenderProgram.useProgram();
666

    
667
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
668
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
669
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
670
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
671
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
672
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
673
    }
674

    
675
///////////////////////////////////////////////////////////////////////////////////////////////////
676

    
677
  static void setSSBOSize(float size)
678
    {
679
    mBufferSize = size;
680
    }
681

    
682
///////////////////////////////////////////////////////////////////////////////////////////////////
683
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
684
// PowerVR GE8100 compiler fails to compile OIT programs.
685

    
686
  private static void detectBuggyDrivers()
687
    {
688
    String vendor  = GLES31.glGetString(GLES31.GL_VENDOR);
689
    String version = GLES31.glGetString(GLES31.GL_VERSION);
690
    String renderer= GLES31.glGetString(GLES31.GL_RENDERER);
691

    
692
    /*
693
    android.util.Log.e("DISTORTED", "GLSL Version "+GLES31.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
694
    android.util.Log.e("DISTORTED", "GL Version "  +GLES31.glGetString(GLES31.GL_VERSION));
695
    android.util.Log.e("DISTORTED", "GL Vendor "   +GLES31.glGetString(GLES31.GL_VENDOR));
696
    android.util.Log.e("DISTORTED", "GL Renderer " +GLES31.glGetString(GLES31.GL_RENDERER));
697
    */
698

    
699
    if( vendor.contains("ARM") )
700
      {
701
      if( version.contains("r12") )
702
        {
703
        android.util.Log.e("DISTORTED", "You are running this on a ARM Mali driver r12.\nThis is a buggy driver, please update to r22. Problems with flashing expected.");
704
        }
705
      }
706
    else if( vendor.contains("Imagination") )
707
      {
708
      if( renderer.contains("GE8") )
709
        {
710
        android.util.Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
711
        }
712
      }
713
    }
714

    
715
///////////////////////////////////////////////////////////////////////////////////////////////////
716
/**
717
 * Have we called onCreate yet, ie have we initialized the library?
718
 * @return <code>true</code> if the library is initialized and ready for action.
719
 */
720
  public static boolean isInitialized()
721
    {
722
    return mInitialized;
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726
/**
727
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
728
 * I.e. best called from GLSurfaceView.onCreate().
729
 * <p>
730
 * Needs to be called from a thread holding the OpenGL context.
731
 *   
732
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
733
 */
734
  public static void onCreate(final Context context) throws Exception
735
    {
736
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
737
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
738
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+configurationInfo.getGlEsVersion());
739

    
740
    mInitialized = true;
741

    
742
    detectBuggyDrivers();
743

    
744
    EffectMessageSender.startSending();
745

    
746
    final Resources resources = context.getResources();
747

    
748
    Exception exception=null;
749

    
750
    try
751
      {
752
      createPrograms(resources);
753
      }
754
    catch(Exception ex)
755
      {
756
      exception = ex;
757
      }
758

    
759
    try
760
      {
761
      createProgramsOIT(resources);
762
      }
763
    catch(Exception ex)
764
      {
765
      exception = ex;
766
      }
767

    
768
    try
769
      {
770
      EffectQueuePostprocess.createPrograms(resources);
771
      }
772
    catch(Exception ex)
773
      {
774
      exception = ex;
775
      }
776

    
777
    try
778
      {
779
      PostprocessEffect.createPrograms();
780
      }
781
    catch(Exception ex)
782
      {
783
      exception = ex;
784
      }
785

    
786
    if( exception!=null)
787
      {
788
      throw exception;
789
      }
790
    }
791

    
792
///////////////////////////////////////////////////////////////////////////////////////////////////
793
/**
794
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
795
 * Must be called from Activity.onPause().
796
 */
797
  public static void onPause()
798
    {
799
    DistortedObject.onPause();
800

    
801
    mLinkedListSSBO[0]= -1;
802

    
803
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
804
    }
805

    
806
///////////////////////////////////////////////////////////////////////////////////////////////////
807
/**
808
 * Call this so that the Library can release its internal data structures.
809
 * Must be called from Activity.onDestroy(). 
810
 */
811
  public static void onDestroy()
812
    {
813
    DistortedObject.onDestroy();
814
    DistortedNodeData.onDestroy();
815
    DistortedEffects.onDestroy();
816
    DistortedMaster.onDestroy();
817
    DistortedOutputSurface.onDestroy();
818
    EffectQueue.onDestroy();
819
    Effect.onDestroy();
820
    EffectMessageSender.stopSending();
821

    
822
    mInitialized = false;
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
828
 * single (InputSurface,MeshBase) combo.
829
 *
830
 * @param type {@link EffectType}
831
 * @return The maximum number of effects of a given type.
832
 */
833
  @SuppressWarnings("unused")
834
  public static int getMax(EffectType type)
835
    {
836
    return EffectQueue.getMax(type.ordinal());
837
    }
838

    
839
///////////////////////////////////////////////////////////////////////////////////////////////////
840
/**
841
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
842
 * This can fail if:
843
 * <ul>
844
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
845
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
846
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
847
 *     time only decreasing the value of 'max' is permitted.
848
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
849
 * </ul>
850
 *
851
 * @param type {@link EffectType}
852
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
853
 *            than Byte.MAX_VALUE
854
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
855
 */
856
  @SuppressWarnings("unused")
857
  public static boolean setMax(EffectType type, int max)
858
    {
859
    return EffectQueue.setMax(type.ordinal(),max);
860
    }
861
  }
(1-1/19)